Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-4624 - Fixed plugin loading dependency issue

dragonmacher35d9534bde8e
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/editor/TextEditorManagerPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/editor/TextEditorManagerPlugin.java
deleted file mode 100644
index b336fe4b90..0000000000
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/editor/TextEditorManagerPlugin.java
+++ /dev/null
@@ -1,86 +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.plugin.core.editor;
-
-import ghidra.app.CorePluginPackage;
-import ghidra.app.plugin.PluginCategoryNames;
-import ghidra.app.plugin.ProgramPlugin;
-import ghidra.app.services.TextEditorService;
-import ghidra.framework.plugintool.*;
-import ghidra.framework.plugintool.util.PluginStatus;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.swing.JComponent;
-import javax.swing.JOptionPane;
-
-import docking.widgets.OptionDialog;
-
-//@formatter:off
-@PluginInfo(
- status = PluginStatus.STABLE,
- packageName = CorePluginPackage.NAME,
- category = PluginCategoryNames.COMMON,
- shortDescription = "Generic Text Editor",
- description = "Provides a service to opening and editing text files.",
- servicesProvided = { TextEditorService.class }
-)
-//@formatter:on
-public class TextEditorManagerPlugin extends ProgramPlugin implements TextEditorService {
-
- private List<TextEditorComponentProvider> editors = new ArrayList<>();
-
- public TextEditorManagerPlugin(PluginTool tool) {
- super(tool);
- }
-
- @Override
- public void edit(String name, InputStream inputStream) {
- try {
- TextEditorComponentProvider provider = new TextEditorComponentProvider( this, name, inputStream );
- editors.add( provider );
- tool.showComponentProvider( provider, true );
- }
- catch (IOException e) {
- JOptionPane.showMessageDialog( null, "Unable to edit " + name + " due to I/O error.", "Edit", JOptionPane.ERROR_MESSAGE );
- }
- }
-
- public List<TextEditorComponentProvider> getEditors() {
- return editors;
- }
-
- public boolean removeTextFile(TextEditorComponentProvider editor, String textFileName) {
- if ( editor.isChanged() ) {
- JComponent parentComponent = editor.getComponent();
- if ( tool.isVisible( editor ) ) {
- parentComponent = editor.getComponent();
- }
- int result = OptionDialog.showYesNoDialog( parentComponent, getName(),
- "'"+textFileName+"' has been modified. Discard changes?");
- if (result != OptionDialog.OPTION_ONE) {
- return false;
- }
- }
- tool.removeComponentProvider( editor );
- editors.remove( editor );
- return true;
- }
-
-}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/reachability/FRPathsModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/reachability/FRPathsModel.java
index 92c63241a7..d877b9ccff 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/reachability/FRPathsModel.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/reachability/FRPathsModel.java
@@ -17,8 +17,7 @@ package ghidra.app.plugin.core.reachability;
import java.util.*;
-import docking.widgets.table.AbstractDynamicTableColumn;
-import docking.widgets.table.TableColumnDescriptor;
+import docking.widgets.table.*;
import ghidra.docking.settings.Settings;
import ghidra.framework.plugintool.ServiceProvider;
import ghidra.program.model.address.Address;
@@ -38,6 +37,8 @@ public class FRPathsModel extends AddressBasedTableModel<FRVertex> {
protected FRPathsModel(ServiceProvider serviceProvider, Program program) {
super("Function Reachability Paths Model", serviceProvider, program, null);
+
+ setDefaultTableSortState(TableSortState.createUnsortedSortState());
}
@Override
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/services/TextEditorService.java b/Ghidra/Features/Base/src/main/java/ghidra/app/services/TextEditorService.java
deleted file mode 100644
index 6659501356..0000000000
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/services/TextEditorService.java
+++ /dev/null
@@ -1,32 +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.services;
-
-import java.io.InputStream;
-
-public interface TextEditorService {
-
- /**
- * Shows an text editor component with the contents of the specified {@link InputStream}.
- * <p>
- *
- * @param name String name of file
- * @param inputStream {@link InputStream} with content that should be displayed in the
- * edit window. Stream closed by this service.
- */
- public void edit(String name, InputStream inputStream);
-
-}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java
index 994c510f55..dfb3ad573d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java
@@ -31,7 +31,8 @@ import ghidra.app.CorePluginPackage;
import ghidra.app.context.ListingActionContext;
import ghidra.app.events.ProgramActivatedPluginEvent;
import ghidra.app.plugin.PluginCategoryNames;
-import ghidra.app.services.*;
+import ghidra.app.services.FileImporterService;
+import ghidra.app.services.ProgramManager;
import ghidra.app.util.bin.ByteProvider;
import ghidra.app.util.importer.LibrarySearchPathManager;
import ghidra.app.util.opinion.LoaderMap;
@@ -71,7 +72,6 @@ import ghidra.util.task.*;
category = PluginCategoryNames.COMMON,
shortDescription = "Import External Files (NEW)",
description = ImporterPlugin.IMPORTER_PLUGIN_DESC,
- servicesRequired = { TextEditorService.class },
servicesProvided = { FileImporterService.class },
eventsConsumed = { ProgramActivatedPluginEvent.class }
)
@@ -281,8 +281,7 @@ public class ImporterPlugin extends Plugin
}
catch (IOException e) {
Msg.showError(JavaFileListHandler.class, tool.getToolFrame(),
- "Packed DB Import Failed",
- "Failed to import " + f.getName(), e);
+ "Packed DB Import Failed", "Failed to import " + f.getName(), e);
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FSBActionManager.java b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FSBActionManager.java
index 48fa673f15..0884965b75 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FSBActionManager.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FSBActionManager.java
@@ -38,7 +38,6 @@ import docking.widgets.label.GIconLabel;
import docking.widgets.tree.GTree;
import docking.widgets.tree.GTreeNode;
import ghidra.app.services.ProgramManager;
-import ghidra.app.services.TextEditorService;
import ghidra.app.util.bin.ByteProvider;
import ghidra.app.util.importer.LibrarySearchPathManager;
import ghidra.formats.gfilesystem.*;
@@ -58,6 +57,7 @@ import ghidra.util.exception.CancelledException;
import ghidra.util.exception.CryptoException;
import ghidra.util.task.TaskLauncher;
import ghidra.util.task.TaskMonitor;
+import utilities.util.FileUtilities;
/**
* Handles the menu actions for the {@link FileSystemBrowserComponentProvider}.
@@ -92,8 +92,6 @@ class FSBActionManager {
protected FileSystemBrowserPlugin plugin;
protected FileSystemBrowserComponentProvider provider;
- private TextEditorService textEditorService;
-
private GTree gTree;
private GhidraFileChooser chooserExport;
@@ -103,12 +101,11 @@ class FSBActionManager {
private FileSystemService fsService = FileSystemService.getInstance();
FSBActionManager(FileSystemBrowserPlugin plugin, FileSystemBrowserComponentProvider provider,
- TextEditorService textEditorService, GTree gTree) {
+ GTree gTree) {
this.plugin = plugin;
this.provider = provider;
- this.textEditorService = textEditorService;
this.gTree = gTree;
createActions();
@@ -201,9 +198,9 @@ class FSBActionManager {
OptionDialog.showYesNoDialog(null, "Search Project for matching program?",
"Search entire Project for matching program? (WARNING, could take large amount of time)") == OptionDialog.YES_OPTION;
- Map<FSRL, DomainFile> matchedFSRLs = doSearch
- ? ProgramMappingService.searchProjectForMatchingFiles(List.of(fsrl), monitor)
- : Map.of();
+ Map<FSRL, DomainFile> matchedFSRLs =
+ doSearch ? ProgramMappingService.searchProjectForMatchingFiles(List.of(fsrl), monitor)
+ : Map.of();
DomainFile domainFile = matchedFSRLs.get(fsrl);
if (domainFile != null) {
@@ -293,9 +290,9 @@ class FSBActionManager {
"Search entire Project for matching programs? " +
"(WARNING, could take large amount of time)") == OptionDialog.YES_OPTION;
- Map<FSRL, DomainFile> matchedFSRLs = doSearch
- ? ProgramMappingService.searchProjectForMatchingFiles(fsrlList, monitor)
- : Map.of();
+ Map<FSRL, DomainFile> matchedFSRLs =
+ doSearch ? ProgramMappingService.searchProjectForMatchingFiles(fsrlList, monitor)
+ : Map.of();
List<FSRL> unmatchedFSRLs = new ArrayList<>();
for (FSRL fsrl : fsrlList) {
@@ -342,43 +339,40 @@ class FSBActionManager {
// DockingActions
//----------------------------------------------------------------------------------
private DockingAction createExportAction() {
- return new ActionBuilder("FSB Export", plugin.getName())
- .withContext(FSBActionContext.class)
+ return new ActionBuilder("FSB Export", plugin.getName()).withContext(FSBActionContext.class)
.enabledWhen(ac -> ac.notBusy() && ac.getFileFSRL() != null)
.popupMenuIcon(ImageManager.EXTRACT)
.popupMenuPath("Export...")
.popupMenuGroup("F", "C")
- .onAction(
- ac -> {
- FSRL fsrl = ac.getFileFSRL();
- if (fsrl == null) {
- return;
- }
- if (chooserExport == null) {
- chooserExport = new GhidraFileChooser(provider.getComponent());
- chooserExport.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);
- chooserExport.setTitle("Select Where To Export File");
- chooserExport.setApproveButtonText("Export");
- }
- File selectedFile =
- new File(chooserExport.getCurrentDirectory(), fsrl.getName());
- chooserExport.setSelectedFile(selectedFile);
- File outputFile = chooserExport.getSelectedFile();
- if (outputFile == null) {
+ .onAction(ac -> {
+ FSRL fsrl = ac.getFileFSRL();
+ if (fsrl == null) {
+ return;
+ }
+ if (chooserExport == null) {
+ chooserExport = new GhidraFileChooser(provider.getComponent());
+ chooserExport.setFileSelectionMode(GhidraFileChooserMode.FILES_ONLY);
+ chooserExport.setTitle("Select Where To Export File");
+ chooserExport.setApproveButtonText("Export");
+ }
+ File selectedFile =
+ new File(chooserExport.getCurrentDirectory(), fsrl.getName());
+ chooserExport.setSelectedFile(selectedFile);
+ File outputFile = chooserExport.getSelectedFile();
+ if (outputFile == null) {
+ return;
+ }
+ if (outputFile.exists()) {
+ int answer = OptionDialog.showYesNoDialog(provider.getComponent(),
+ "Confirm Overwrite", outputFile.getAbsolutePath() + "\n" +
+ "The file already exists.\n" + "Do you want to overwrite it?");
+ if (answer == OptionDialog.NO_OPTION) {
return;
}
- if (outputFile.exists()) {
- int answer = OptionDialog.showYesNoDialog(provider.getComponent(),
- "Confirm Overwrite", outputFile.getAbsolutePath() + "\n" +
- "The file already exists.\n" +
- "Do you want to overwrite it?");
- if (answer == OptionDialog.NO_OPTION) {
- return;
- }
- }
- gTree.runTask(monitor -> doExtractFile(fsrl, outputFile,
- ac.getSelectedNode(), monitor));
- })
+ }
+ gTree.runTask(
+ monitor -> doExtractFile(fsrl, outputFile, ac.getSelectedNode(), monitor));
+ })
.build();
}
@@ -389,37 +383,36 @@ class FSBActionManager {
.popupMenuIcon(ImageManager.EXTRACT)
.popupMenuPath("Export All...")
.popupMenuGroup("F", "C")
- .onAction(
- ac -> {
- FSRL fsrl = ac.getFSRL(true);
- if (fsrl == null) {
- return;
- }
- if (fsrl instanceof FSRLRoot) {
- fsrl = fsrl.appendPath("/");
- }
- if (chooserExportAll == null) {
- chooserExportAll = new GhidraFileChooser(provider.getComponent());
- chooserExportAll
- .setFileSelectionMode(GhidraFileChooserMode.DIRECTORIES_ONLY);
- chooserExportAll.setTitle("Select Export Directory");
- chooserExportAll.setApproveButtonText("Export All");
- }
- chooserExportAll.setSelectedFile(null);
- File outputFile = chooserExportAll.getSelectedFile();
- if (outputFile == null) {
- return;
- }
+ .onAction(ac -> {
+ FSRL fsrl = ac.getFSRL(true);
+ if (fsrl == null) {
+ return;
+ }
+ if (fsrl instanceof FSRLRoot) {
+ fsrl = fsrl.appendPath("/");
+ }
+ if (chooserExportAll == null) {
+ chooserExportAll = new GhidraFileChooser(provider.getComponent());
+ chooserExportAll
+ .setFileSelectionMode(GhidraFileChooserMode.DIRECTORIES_ONLY);
+ chooserExportAll.setTitle("Select Export Directory");
+ chooserExportAll.setApproveButtonText("Export All");
+ }
+ chooserExportAll.setSelectedFile(null);
+ File outputFile = chooserExportAll.getSelectedFile();
+ if (outputFile == null) {
+ return;
+ }
- if (!outputFile.isDirectory()) {
- Msg.showInfo(this, provider.getComponent(), "Export All",
- "Selected file is not a directory.");
- return;
- }
- Component parentComp = plugin.getTool().getActiveWindow();
- TaskLauncher.launch(
- new GFileSystemExtractAllTask(fsrl, outputFile, parentComp));
- })
+ if (!outputFile.isDirectory()) {
+ Msg.showInfo(this, provider.getComponent(), "Export All",
+ "Selected file is not a directory.");
+ return;
+ }
+ Component parentComp = plugin.getTool().getActiveWindow();
+ TaskLauncher
+ .launch(new GFileSystemExtractAllTask(fsrl, outputFile, parentComp));
+ })
.build();
}
@@ -430,14 +423,13 @@ class FSBActionManager {
.popupMenuIcon(ImageManager.VIEW_AS_IMAGE)
.popupMenuPath("View As Image")
.popupMenuGroup("G")
- .onAction(
- ac -> {
- FSRL fsrl = ac.getFileFSRL();
- if (fsrl != null) {
- gTree.runTask(
- monitor -> doViewAsImage(fsrl, ac.getSelectedNode(), monitor));
- }
- })
+ .onAction(ac -> {
+ FSRL fsrl = ac.getFileFSRL();
+ if (fsrl != null) {
+ gTree.runTask(
+ monitor -> doViewAsImage(fsrl, ac.getSelectedNode(), monitor));
+ }
+ })
.build();
}
@@ -448,14 +440,12 @@ class FSBActionManager {
.popupMenuIcon(ImageManager.VIEW_AS_TEXT)
.popupMenuPath("View As Text")
.popupMenuGroup("G")
- .onAction(
- ac -> {
- FSRL fsrl = ac.getFileFSRL();
- if (fsrl != null) {
- gTree.runTask(
- monitor -> doViewAsText(fsrl, ac.getSelectedNode(), monitor));
- }
- })
+ .onAction(ac -> {
+ FSRL fsrl = ac.getFileFSRL();
+ if (fsrl != null) {
+ gTree.runTask(monitor -> doViewAsText(fsrl, ac.getSelectedNode(), monitor));
+ }
+ })
.build();
}
@@ -471,8 +461,7 @@ class FSBActionManager {
.popupMenuGroup("L")
.onAction(ac -> {
FSRLRoot fsFSRL = SelectFromListDialog.selectFromList(
- fsService.getMountedFilesystems(),
- "Select filesystem",
+ fsService.getMountedFilesystems(), "Select filesystem",
"Choose filesystem to view", f -> f.toPrettyString());
FileSystemRef fsRef;
@@ -526,11 +515,10 @@ class FSBActionManager {
.popupMenuGroup("A", "A")
.popupMenuIcon(ImageManager.INFO)
.description("Show information about a file")
- .onAction(
- ac -> {
- FSRL fsrl = ac.getFSRL(true);
- gTree.runTask(monitor -> showInfoForFile(fsrl, monitor));
- })
+ .onAction(ac -> {
+ FSRL fsrl = ac.getFSRL(true);
+ gTree.runTask(monitor -> showInfoForFile(fsrl, monitor));
+ })
.build();
}
@@ -541,20 +529,19 @@ class FSBActionManager {
.popupMenuIcon(ImageManager.OPEN_FILE_SYSTEM)
.popupMenuPath("Open File System in new window")
.popupMenuGroup("C")
- .onAction(
- ac -> {
- if (!(ac.getSelectedNode() instanceof FSBFileNode) ||
- ac.getSelectedNode().getFSRL() == null) {
- return;
- }
- FSBFileNode selectedNode = (FSBFileNode) ac.getSelectedNode();
- FSRL containerFSRL = selectedNode.getFSRL();
- if (containerFSRL != null) {
- gTree.runTask(monitor -> {
- doOpenFileSystem(containerFSRL, selectedNode, false, monitor);
- });
- }
- })
+ .onAction(ac -> {
+ if (!(ac.getSelectedNode() instanceof FSBFileNode) ||
+ ac.getSelectedNode().getFSRL() == null) {
+ return;
+ }
+ FSBFileNode selectedNode = (FSBFileNode) ac.getSelectedNode();
+ FSRL containerFSRL = selectedNode.getFSRL();
+ if (containerFSRL != null) {
+ gTree.runTask(monitor -> {
+ doOpenFileSystem(containerFSRL, selectedNode, false, monitor);
+ });
+ }
+ })
.build();
}
@@ -620,8 +607,7 @@ class FSBActionManager {
}
private DockingAction createCloseAction() {
- return new ActionBuilder("FSB Close", plugin.getName())
- .withContext(FSBActionContext.class)
+ return new ActionBuilder("FSB Close", plugin.getName()).withContext(FSBActionContext.class)
.enabledWhen(ac -> ac.notBusy() && ac.getSelectedNode() instanceof FSBRootNode)
.description("Close")
.toolBarIcon(ImageManager.CLOSE)
@@ -724,7 +710,7 @@ class FSBActionManager {
if (fsrl == null) {
return;
}
-
+
gTree.runTask(monitor -> {
if (!ensureFileAccessable(fsrl, ac.getSelectedNode(), monitor)) {
return;
@@ -782,15 +768,13 @@ class FSBActionManager {
.popupMenuPath("Clear Cached Passwords")
.popupMenuGroup("Z", "B")
.description("Clear cached container file passwords")
- .onAction(
- ac -> {
- CachedPasswordProvider ccp =
- CryptoProviders.getInstance().getCachedCryptoProvider();
- int preCount = ccp.getCount();
- ccp.clearCache();
- Msg.info(this,
- "Cleared " + (preCount - ccp.getCount()) + " cached passwords.");
- })
+ .onAction(ac -> {
+ CachedPasswordProvider ccp =
+ CryptoProviders.getInstance().getCachedCryptoProvider();
+ int preCount = ccp.getCount();
+ ccp.clearCache();
+ Msg.info(this, "Cleared " + (preCount - ccp.getCount()) + " cached passwords.");
+ })
.build();
}
@@ -816,10 +800,9 @@ class FSBActionManager {
}
monitor.setMessage("Exporting...");
try (ByteProvider fileBP = fsService.getByteProvider(fsrl, false, monitor)) {
- long bytesCopied =
- FSUtilities.copyByteProviderToFile(fileBP, outputFile, monitor);
- Msg.info(this, "Exported " + fsrl.getName() + " to " + outputFile + ", " +
- bytesCopied + " bytes copied.");
+ long bytesCopied = FSUtilities.copyByteProviderToFile(fileBP, outputFile, monitor);
+ Msg.info(this, "Exported " + fsrl.getName() + " to " + outputFile + ", " + bytesCopied +
+ " bytes copied.");
}
catch (IOException | CancelledException | UnsupportedOperationException e) {
FSUtilities.displayException(this, plugin.getTool().getActiveWindow(),
@@ -873,8 +856,7 @@ class FSBActionManager {
}
catch (IOException | CancelledException e) {
FSUtilities.displayException(this, plugin.getTool().getActiveWindow(),
- "Open Filesystem",
- "Error opening filesystem for " + containerFSRL.getName(), e);
+ "Open Filesystem", "Error opening filesystem for " + containerFSRL.getName(), e);
}
}
@@ -894,13 +876,13 @@ class FSBActionManager {
}
Swing.runLater(() -> {
JLabel label = new GIconLabel(icon);
- JOptionPane.showMessageDialog(null, label,
- "Image Viewer: " + fsrl.getName(), JOptionPane.INFORMATION_MESSAGE);
+ JOptionPane.showMessageDialog(null, label, "Image Viewer: " + fsrl.getName(),
+ JOptionPane.INFORMATION_MESSAGE);
});
}
catch (IOException | CancelledException e) {
- FSUtilities.displayException(this, parent, "Error Viewing Image File",
- e.getMessage(), e);
+ FSUtilities.displayException(this, parent, "Error Viewing Image File", e.getMessage(),
+ e);
}
}
@@ -923,13 +905,15 @@ class FSBActionManager {
"File " + fsrl.getName() + " is empty (0 bytes).");
return;
}
+
try {
- // textEditorService closes the inputStream, and must be
- // called on the swing thread or you get concurrentmodification
- // exceptions.
ByteArrayInputStream bais =
new ByteArrayInputStream(fileBP.readBytes(0, fileBP.length()));
- Swing.runLater(() -> textEditorService.edit(fsrl.getName(), bais));
+
+ String text = FileUtilities.getText(bais);
+ Swing.runLater(() -> {
+ new TextEditorComponentProvider(fsrl.getName(), text);
+ });
}
catch (IOException e) {
Msg.showError(this, parent, "View As Text Failed",
@@ -937,8 +921,8 @@ class FSBActionManager {
}
}
catch (IOException | CancelledException e) {
- FSUtilities.displayException(this, parent, "Error Viewing Text File",
- e.getMessage(), e);
+ FSUtilities.displayException(this, parent, "Error Viewing Text File", e.getMessage(),
+ e);
}
}
@@ -1009,27 +993,19 @@ class FSBActionManager {
// static lookup tables for rendering file attributes
//---------------------------------------------------------------------------------------------
private static final Function<Object, String> PLAIN_TOSTRING = o -> o.toString();
- private static final Function<Object, String> SIZE_TOSTRING = o -> (o instanceof Long)
- ? FSUtilities.formatSize((Long) o)
- : o.toString();
- private static final Function<Object, String> UNIX_ACL_TOSTRING = o -> (o instanceof Number)
- ? String.format("%05o", (Number) o)
- : o.toString();
- private static final Function<Object, String> DATE_TOSTRING = o -> (o instanceof Date)
- ? FSUtilities.formatFSTimestamp((Date) o)
- : o.toString();
- private static final Function<Object, String> FSRL_TOSTRING = o -> (o instanceof FSRL)
- ? ((FSRL) o).toPrettyString().replace("|", "|\n\t")
- : o.toString();
+ private static final Function<Object, String> SIZE_TOSTRING =
+ o -> (o instanceof Long) ? FSUtilities.formatSize((Long) o) : o.toString();
+ private static final Function<Object, String> UNIX_ACL_TOSTRING =
+ o -> (o instanceof Number) ? String.format("%05o", (Number) o) : o.toString();
+ private static final Function<Object, String> DATE_TOSTRING =
+ o -> (o instanceof Date) ? FSUtilities.formatFSTimestamp((Date) o) : o.toString();
+ private static final Function<Object, String> FSRL_TOSTRING =
+ o -> (o instanceof FSRL) ? ((FSRL) o).toPrettyString().replace("|", "|\n\t") : o.toString();
private static final Map<FileAttributeType, Function<Object, String>> FAT_TOSTRING_FUNCS =
- Map.ofEntries(
- entry(FSRL_ATTR, FSRL_TOSTRING),
- entry(SIZE_ATTR, SIZE_TOSTRING),
- entry(COMPRESSED_SIZE_ATTR, SIZE_TOSTRING),
- entry(CREATE_DATE_ATTR, DATE_TOSTRING),
- entry(MODIFIED_DATE_ATTR, DATE_TOSTRING),
- entry(ACCESSED_DATE_ATTR, DATE_TOSTRING),
+ Map.ofEntries(entry(FSRL_ATTR, FSRL_TOSTRING), entry(SIZE_ATTR, SIZE_TOSTRING),
+ entry(COMPRESSED_SIZE_ATTR, SIZE_TOSTRING), entry(CREATE_DATE_ATTR, DATE_TOSTRING),
+ entry(MODIFIED_DATE_ATTR, DATE_TOSTRING), entry(ACCESSED_DATE_ATTR, DATE_TOSTRING),
entry(UNIX_ACL_ATTR, UNIX_ACL_TOSTRING));
/**
@@ -1096,8 +1072,7 @@ class FSBActionManager {
}
private String getHTMLInfoStringForAttributes(List<FileAttributes> fileAttributesList) {
- StringBuilder sb =
- new StringBuilder("<html>\n<table>\n");
+ StringBuilder sb = new StringBuilder("<html>\n<table>\n");
sb.append("<tr><th>Property</th><th>Value</th></tr>\n");
for (FileAttributes fattrs : fileAttributesList) {
if (fattrs != fileAttributesList.get(0)) {
@@ -1105,17 +1080,15 @@ class FSBActionManager {
sb.append("<tr><td colspan=2><hr></td></tr>");
}
List<FileAttribute<?>> sortedAttribs = fattrs.getAttributes();
- Collections.sort(sortedAttribs,
- (o1, o2) -> Integer.compare(o1.getAttributeType().ordinal(),
- o2.getAttributeType().ordinal()));
+ Collections.sort(sortedAttribs, (o1, o2) -> Integer
+ .compare(o1.getAttributeType().ordinal(), o2.getAttributeType().ordinal()));
FileAttributeTypeGroup group = null;
for (FileAttribute<?> attr : sortedAttribs) {
if (attr.getAttributeType().getGroup() != group) {
group = attr.getAttributeType().getGroup();
if (group != FileAttributeTypeGroup.GENERAL_INFO) {
- sb
- .append("<tr><td><b>")
+ sb.append("<tr><td><b>")
.append(group.getDescriptiveName())
.append("</b></td><td><hr></td></tr>\n");
}
@@ -1126,8 +1099,7 @@ class FSBActionManager {
String html = HTMLUtilities.escapeHTML(valStr);
html = html.replace("\n", "<br>\n");
- sb
- .append("<tr><td>")
+ sb.append("<tr><td>")
.append(attr.getAttributeDisplayName())
.append(":</td><td>")
.append(html)
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserComponentProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserComponentProvider.java
index 1ff10a424a..a8f32f6b82 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserComponentProvider.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserComponentProvider.java
@@ -31,7 +31,6 @@ import docking.widgets.tree.GTreeNode;
import docking.widgets.tree.support.GTreeRenderer;
import generic.theme.GThemeDefaults.Colors.Palette;
import ghidra.app.services.ProgramManager;
-import ghidra.app.services.TextEditorService;
import ghidra.formats.gfilesystem.*;
import ghidra.framework.plugintool.ComponentProviderAdapter;
import ghidra.plugin.importer.ProgramMappingService;
@@ -163,8 +162,7 @@ class FileSystemBrowserComponentProvider extends ComponentProviderAdapter
}
});
- actionManager = new FSBActionManager(plugin, this,
- plugin.getTool().getService(TextEditorService.class), gTree);
+ actionManager = new FSBActionManager(plugin, this, gTree);
// TODO: fix this Help stuff
setHelpLocation(
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserPlugin.java
index e927ae8df7..9da72ef754 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserPlugin.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/FileSystemBrowserPlugin.java
@@ -32,7 +32,8 @@ import docking.widgets.filechooser.GhidraFileChooserMode;
import ghidra.app.CorePluginPackage;
import ghidra.app.events.ProgramActivatedPluginEvent;
import ghidra.app.plugin.PluginCategoryNames;
-import ghidra.app.services.*;
+import ghidra.app.services.FileSystemBrowserService;
+import ghidra.app.services.ProgramManager;
import ghidra.formats.gfilesystem.*;
import ghidra.framework.main.ApplicationLevelPlugin;
import ghidra.framework.main.FrontEndService;
@@ -63,13 +64,11 @@ import utilities.util.FileUtilities;
shortDescription = "Browse Filesystems in containers",
description = "This plugin allows users to browse and use the contents of containers (zips, tars, filesystems, etc)",
servicesProvided = { FileSystemBrowserService.class },
- servicesRequired = { TextEditorService.class },
eventsConsumed = { ProgramActivatedPluginEvent.class }
)
//@formatter:on
public class FileSystemBrowserPlugin extends Plugin
- implements ApplicationLevelPlugin, ProjectListener,
- FileSystemBrowserService {
+ implements ApplicationLevelPlugin, ProjectListener, FileSystemBrowserService {
/* package */ DockingAction openFilesystemAction;
/* package */ DockingAction showFileSystemImplsAction;
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/editor/TextEditorComponentProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/TextEditorComponentProvider.java
similarity index 73%
rename from Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/editor/TextEditorComponentProvider.java
rename to Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/TextEditorComponentProvider.java
index fb16b9ac13..72376a7748 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/editor/TextEditorComponentProvider.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/TextEditorComponentProvider.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package ghidra.app.plugin.core.editor;
+package ghidra.plugins.fsbrowser;
import java.awt.Dimension;
import java.awt.Font;
@@ -33,8 +33,8 @@ import docking.options.editor.FontEditor;
import docking.widgets.OptionDialog;
import docking.widgets.filechooser.GhidraFileChooser;
import generic.theme.*;
+import ghidra.framework.main.AppInfo;
import ghidra.framework.plugintool.ComponentProviderAdapter;
-import ghidra.util.HelpLocation;
import ghidra.util.Msg;
import ghidra.util.datastruct.FixedSizeStack;
import resources.Icons;
@@ -45,7 +45,6 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
private static final int MAX_UNDO_REDO_SIZE = 50;
private static final String LAST_SAVED_TEXT_FILE_DIR = "LastSavedTextFileDirectory";
- private TextEditorManagerPlugin plugin;
private File textFile;
private String textFileName;
private DockingAction saveAction;
@@ -60,23 +59,17 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
private FixedSizeStack<UndoableEdit> undoStack = new FixedSizeStack<>(MAX_UNDO_REDO_SIZE);
private FixedSizeStack<UndoableEdit> redoStack = new FixedSizeStack<>(MAX_UNDO_REDO_SIZE);
- TextEditorComponentProvider(TextEditorManagerPlugin plugin, String textFileName,
- InputStream inputStream) throws IOException {
- super(plugin.getTool(), TITLE, plugin.getName());
+ TextEditorComponentProvider(String textFileName, String text) {
+ super(AppInfo.getFrontEndTool(), TITLE, "TextEditorComponentProvider");
this.textFileName = textFileName;
- String textContents = loadTextFile(inputStream);
- initialize(plugin, textContents);
+ initialize(text);
}
public String getText() {
return textarea.getText();
}
- private void initialize(TextEditorManagerPlugin p, String textContents) {
- this.plugin = p;
-
- setHelpLocation(new HelpLocation(p.getName(), p.getName()));
-
+ private void initialize(String textContents) {
title = textFileName + (isReadOnly() ? " (Read-Only) " : "");
setTitle(title);
@@ -87,9 +80,10 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
addToTool();
setVisible(true);
- p.getTool().setStatusInfo("Press F1 for help.");
createActions();
+
+ contextChanged();
}
private boolean isReadOnly() {
@@ -99,26 +93,21 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
private void clearUndoRedoStack() {
undoStack.clear();
redoStack.clear();
- updateUndoRedoAction();
- }
-
- private void updateUndoRedoAction() {
- undoAction.setEnabled(!undoStack.isEmpty());
- redoAction.setEnabled(!redoStack.isEmpty());
+ contextChanged();
}
private void undo() {
UndoableEdit item = undoStack.pop();
redoStack.push(item);
item.undo();
- updateUndoRedoAction();
+ contextChanged();
}
private void redo() {
UndoableEdit item = redoStack.pop();
undoStack.push(item);
item.redo();
- updateUndoRedoAction();
+ contextChanged();
}
boolean isChanged() {
@@ -144,27 +133,8 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
}
}
- private String loadTextFile(InputStream inputStream) throws IOException {
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
- return loadTextFile(reader);
- }
- }
-
- private String loadTextFile(BufferedReader reader) throws IOException {
- StringBuilder buffer = new StringBuilder();
- while (true) {
- String line = reader.readLine();
- if (line == null) {
- break;
- }
- buffer.append(line);
- buffer.append('\n');
- }
- return buffer.toString();
- }
-
private void createActions() {
- undoAction = new DockingAction("Undo", plugin.getName()) {
+ undoAction = new DockingAction("Undo", getName()) {
@Override
public void actionPerformed(ActionContext context) {
undo();
@@ -172,17 +142,15 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
@Override
public boolean isEnabledForContext(ActionContext context) {
- Object contextObject = context.getContextObject();
- return contextObject == TextEditorComponentProvider.this;
+ return !undoStack.isEmpty();
}
};
undoAction.setDescription("Undo");
- undoAction.setToolBarData(
- new ToolBarData(new GIcon("icon.undo"), "UndoRedo"));
- undoAction.setEnabled(false);
- plugin.getTool().addLocalAction(this, undoAction);
+ undoAction.setToolBarData(new ToolBarData(new GIcon("icon.undo"), "UndoRedo"));
+ undoAction.setKeyBindingData(new KeyBindingData("ctrl z"));
+ addLocalAction(undoAction);
- redoAction = new DockingAction("Redo", plugin.getName()) {
+ redoAction = new DockingAction("Redo", getName()) {
@Override
public void actionPerformed(ActionContext context) {
redo();
@@ -190,17 +158,15 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
@Override
public boolean isEnabledForContext(ActionContext context) {
- Object contextObject = context.getContextObject();
- return contextObject == TextEditorComponentProvider.this;
+ return !redoStack.isEmpty();
}
};
redoAction.setDescription("Redo");
- redoAction.setToolBarData(
- new ToolBarData(new GIcon("icon.redo"), "UndoRedo"));
- redoAction.setEnabled(false);
- plugin.getTool().addLocalAction(this, redoAction);
+ redoAction.setToolBarData(new ToolBarData(new GIcon("icon.redo"), "UndoRedo"));
+ redoAction.setKeyBindingData(new KeyBindingData("ctrl shift z"));
+ addLocalAction(redoAction);
- saveAction = new DockingAction("Save File", plugin.getName()) {
+ saveAction = new DockingAction("Save File", getName()) {
@Override
public void actionPerformed(ActionContext context) {
save();
@@ -208,45 +174,33 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
@Override
public boolean isEnabledForContext(ActionContext context) {
- Object contextObject = context.getContextObject();
- return contextObject == TextEditorComponentProvider.this;
+ return isChanged;
}
};
saveAction.setDescription("Save");
- saveAction.setToolBarData(
- new ToolBarData(Icons.SAVE_ICON, "Save"));
- saveAction.setEnabled(false);
- plugin.getTool().addLocalAction(this, saveAction);
+ saveAction.setToolBarData(new ToolBarData(Icons.SAVE_ICON, "Save"));
+ saveAction.setKeyBindingData(new KeyBindingData("ctrl-s"));
+ addLocalAction(saveAction);
- saveAsAction = new DockingAction("Save File As", plugin.getName()) {
+ saveAsAction = new DockingAction("Save File As", getName()) {
@Override
public void actionPerformed(ActionContext context) {
saveAs();
}
-
- @Override
- public boolean isEnabledForContext(ActionContext context) {
- Object contextObject = context.getContextObject();
- return contextObject == TextEditorComponentProvider.this;
- }
};
saveAsAction.setDescription("Save As...");
- saveAsAction.setToolBarData(
- new ToolBarData(Icons.SAVE_AS_ICON, "Save"));
- saveAsAction.setEnabled(true);
- plugin.getTool().addLocalAction(this, saveAsAction);
+ saveAsAction.setToolBarData(new ToolBarData(Icons.SAVE_AS_ICON, "Save"));
+ addLocalAction(saveAsAction);
- fontAction = new DockingAction("Select Font", plugin.getName()) {
+ fontAction = new DockingAction("Select Font", getName()) {
@Override
public void actionPerformed(ActionContext context) {
doSelectFont();
}
};
- fontAction.setToolBarData(
- new ToolBarData(new GIcon("icon.font"), "ZZFont"));
+ fontAction.setToolBarData(new ToolBarData(new GIcon("icon.font"), "ZZFont"));
fontAction.setDescription("Select Font");
- fontAction.setEnabled(true);
- plugin.getTool().addLocalAction(this, fontAction);
+ addLocalAction(fontAction);
/****************************************************************/
// DO NOT REMOVE THIS CODE!!
@@ -341,11 +295,9 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
@Override
public void closeComponent() {
- if (plugin.removeTextFile(this, textFileName)) {
- clearUndoRedoStack();
- super.closeComponent();
- plugin.getTool().removeComponentProvider(this);
- }
+ clearUndoRedoStack();
+ super.closeComponent();
+ getTool().removeComponentProvider(this);
}
@Override
@@ -357,12 +309,7 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
// Inner Classes
//==================================================================================================
- /**
- * Special JTextArea that knows how to properly handle it's key events.
- * @see #processKeyBinding(KeyStroke, KeyEvent, int, boolean)
- */
private class KeyMasterTextArea extends JTextArea {
- private static final long serialVersionUID = 1L;
private KeyMasterTextArea(String text) {
super(text);
@@ -390,7 +337,7 @@ public class TextEditorComponentProvider extends ComponentProviderAdapter {
UndoableEdit item = e.getEdit();
undoStack.push(item);
redoStack.clear();
- updateUndoRedoAction();
+ contextChanged();
});
setCaretPosition(0);
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/ErrLogExpandableDialog.java b/Ghidra/Framework/Docking/src/main/java/docking/ErrLogExpandableDialog.java
index fed06a9180..303cbda5bf 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/ErrLogExpandableDialog.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/ErrLogExpandableDialog.java
@@ -378,6 +378,16 @@ public class ErrLogExpandableDialog extends AbstractErrDialog {
public boolean doesIndent() {
return false;
}
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(this);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return this == obj;
+ }
}
static class ReportExceptionNode extends GTreeLazyNode implements NodeWithText {
@@ -444,6 +454,16 @@ public class ErrLogExpandableDialog extends AbstractErrDialog {
public boolean doesIndent() {
return true;
}
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(this);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return this == obj;
+ }
}
static class ReportStackTraceNode extends GTreeLazyNode implements NodeWithText {
@@ -497,6 +517,16 @@ public class ErrLogExpandableDialog extends AbstractErrDialog {
public boolean doesIndent() {
return false;
}
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(this);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return this == obj;
+ }
}
static class ReportCauseNode extends ReportExceptionNode {
@@ -561,6 +591,16 @@ public class ErrLogExpandableDialog extends AbstractErrDialog {
public boolean doesIndent() {
return false;
}
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(this);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return this == obj;
+ }
}
private static class ExcTreeTransferHandler extends TransferHandler
diff --git a/Ghidra/Framework/Project/src/main/java/ghidra/framework/plugintool/PluginManager.java b/Ghidra/Framework/Project/src/main/java/ghidra/framework/plugintool/PluginManager.java
index e8ffc738f9..ad8372af90 100644
--- a/Ghidra/Framework/Project/src/main/java/ghidra/framework/plugintool/PluginManager.java
+++ b/Ghidra/Framework/Project/src/main/java/ghidra/framework/plugintool/PluginManager.java
@@ -18,6 +18,7 @@ package ghidra.framework.plugintool;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
+import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -197,18 +198,26 @@ class PluginManager {
}
// Find any unresolved dependencies in the plugins we are trying to load.
- // Delay throwing an exception until later so we can load the plugins that don't have problems.
+ // Delay throwing an exception so we can load the plugins that don't have problems.
Map<Class<?>, PluginException> dependencyProblemResults = new HashMap<>();
- Set<Class<?>> unresolvedDependencySet = resolveDependencies(dependencyProblemResults);
+ Set<PluginDependency> unresolvedDependencySet =
+ resolveDependencies(dependencyProblemResults);
if (!unresolvedDependencySet.isEmpty()) {
- for (Class<?> dependency : unresolvedDependencySet) {
+ for (PluginDependency pd : unresolvedDependencySet) {
+ Class<?> dependency = pd.dependency();
PluginException cause = dependencyProblemResults.get(dependency);
- errMsg.append("Unresolved dependency: " + dependency.getName() + "\n");
+ String dependencyName = dependency.getName();
+ String dependentName = pd.dependant().getName();
+ String message = """
+ Unresolved dependency: %s. Used by plugin: %s
+ """.formatted(dependencyName, dependentName);
+
+ errMsg.append(message).append('\n');
if (cause != null) {
- errMsg.append("Reason: " + cause.getMessage() + "\n");
+ errMsg.append("Reason: ").append(cause.getMessage()).append('\n');
}
- errMsg.append("\n");
- report.addCause(new PluginException("Unresolved dependency: " + dependency, cause));
+
+ report.addCause(new PluginException(message, cause));
}
cleanupPluginsWithUnresolvedDependencies();
}
@@ -219,18 +228,17 @@ class PluginManager {
for (Iterator<Plugin> it = sortedPlugins.iterator(); it.hasNext();) {
Plugin p = it.next();
try {
- // allow each plugin to acquire services
- p.init();
+ p.init(); // allow each plugin to acquire services
}
catch (Throwable t) {
Msg.error(this, "Unexpected Exception: " + t.getMessage(), t);
errMsg.append("Initializing " + p.getName() + " failed: " + t + "\n");
report.addCause(t);
- badList.add(p); // remove plugin from the tool
- it.remove(); // remove the plugin from the iterator so we don't call it later
// NOTE: other plugins that depend on this failed plugin will still be
// init()'d as well, which opens a small window of problem causing.
+ badList.add(p); // remove plugin from the tool
+ it.remove(); // remove the plugin from the iterator so we don't call it later
}
}
@@ -252,6 +260,7 @@ class PluginManager {
for (Plugin p : sortedPlugins) {
p.processLastEvents(lastEvents);
}
+
if (errMsg.length() > 0) {
throw new PluginException(errMsg.toString(), report);
}
@@ -289,9 +298,7 @@ class PluginManager {
}
SaveState saveState = new SaveState("PLUGIN_STATE");
- Iterator<Plugin> it = pluginList.iterator();
- while (it.hasNext()) {
- Plugin p = it.next();
+ for (Plugin p : pluginList) {
p.writeConfigState(saveState);
if (!saveState.isEmpty()) {
Element pluginElem = saveState.saveToXml();
@@ -438,39 +445,96 @@ class PluginManager {
return null;
}
- private Set<Class<?>> resolveDependencies(
+ private Set<PluginDependency> resolveDependencies(
Map<Class<?>, PluginException> dependencyProblemResults) {
- Set<Class<?>> dependencySet = new HashSet<>();
+
+ Set<PluginDependency> dependencies = new HashSet<>();
do {
- getUnresolvedDependencies(dependencySet, dependencyProblemResults);
+ getUnresolvedDependencies(dependencies);
}
- while (addDependencies(dependencySet, dependencyProblemResults));
- return dependencySet;
+ while (addDependencies(dependencies, dependencyProblemResults));
+ return dependencies;
}
- private void getUnresolvedDependencies(Set<Class<?>> dependencySet,
- Map<Class<?>, PluginException> dependencyProblemResults) {
- dependencySet.clear();
+ private void getUnresolvedDependencies(Set<PluginDependency> dependencies) {
+ dependencies.clear();
for (Plugin p : pluginList) {
- dependencySet.addAll(p.getMissingRequiredServices());
+ List<Class<?>> missingServices = p.getMissingRequiredServices();
+ for (Class<?> missingService : missingServices) {
+ dependencies.add(new PluginDependency(p.getClass(), missingService));
+ }
}
}
/**
- * @param dependencySet set of service interface classes that are required by some plugin
+ * @param dependencies set of service interface classes that are required by some plugin
* and are not provided by a loaded plugin.
* @return boolean true if there was any progress on resolving dependencies, false
* if there was no progress or nothing to do.
*/
- private boolean addDependencies(Set<Class<?>> dependencySet,
+ private boolean addDependencies(Set<PluginDependency> dependencies,
Map<Class<?>, PluginException> dependencyProblemResults) {
boolean fixedDependency = false;
- for (Class<?> depClass : dependencySet) {
- fixedDependency |= fixDependency(depClass, dependencyProblemResults);
+ for (PluginDependency pd : dependencies) {
+ Class<?> dependency = pd.dependency();
+ fixedDependency |= fixDependency(dependency, dependencyProblemResults);
}
return fixedDependency;
}
+ private Class<? extends Plugin> discoverServiceProvider(Class<?> dependency) {
+
+ Class<? extends Plugin> pluginClass =
+ PluginUtils.getDefaultProviderForServiceClass(dependency);
+ if (pluginClass != null) {
+ return pluginClass;
+ }
+
+ //
+ // This is searching for any non-loaded Plugin that implements the required service
+ // interface. Under normal tool configuration, we will not get to this point, since we will
+ // have loaded default service providers using the "defaultProvider" annotation attribute.
+ //
+ // This code attempts to find the needed plugins by finding service providers that either
+ // implement the service interface or declare that they provide an implementation.
+ //
+ List<Class<? extends Plugin>> plugins = ClassSearcher.getClasses(Plugin.class)
+ .stream()
+ .filter(pluginsConfiguration::accepts)
+ .collect(Collectors.toList());
+ List<Class<? extends Plugin>> serviceProviders = new ArrayList<>();
+ for (Class<? extends Plugin> pc : plugins) {
+
+ if (dependency.isAssignableFrom(pc)) {
+ serviceProviders.add(pc);
+ continue;
+ }
+
+ PluginDescription pd = PluginDescription.getPluginDescription(pc);
+ List<Class<?>> servicesProvided = pd.getServicesProvided();
+ for (Class<?> service : servicesProvided) {
+ if (dependency.isAssignableFrom(service)) {
+ serviceProviders.add(pc);
+ }
+ }
+ }
+
+ if (serviceProviders.isEmpty()) {
+ return null;
+ }
+
+ Class<? extends Plugin> choice = serviceProviders.get(0);
+ if (serviceProviders.size() != 1) {
+ // no choice to be made; just return the only implementation we found
+ Msg.warn(this, """
+ Unable to find the preferred service provider implementation for %s.
+ Picking %s
+ """.formatted(dependency.getName(), choice.getName()));
+ }
+
+ return choice;
+ }
+
/**
* Tries to find and pull in the plugin that provides a service.
*
@@ -479,44 +543,23 @@ class PluginManager {
*/
private boolean fixDependency(Class<?> dependency,
Map<Class<?>, PluginException> dependencyProblemResults) {
- Class<? extends Plugin> pluginClass =
- PluginUtils.getDefaultProviderForServiceClass(dependency);
- if (pluginClass == null) {
- // TODO: this following loop is searching for any non-loaded Plugin that implements
- // the required service class interface.
- // This doesn't seem exactly right as a Service implementation shouldn't
- // be automagically pulled in and instantiated UNLESS it was specified as the
- // "defaultProvider", which we've already checked for in the previous
- // PluginUtils.getDefaultProviderForServiceClass().
- // TODO: this also should be filtered by the PluginClassManager so we don't
- // pull in classes that have been excluded.
- for (Class<? extends Plugin> pc : ClassSearcher.getClasses(Plugin.class)) {
- if (dependency.isAssignableFrom(pc)) {
- pluginClass = pc;
- break;
- }
- }
- }
+
+ Class<? extends Plugin> pluginClass = discoverServiceProvider(dependency);
if (pluginClass == null) {
return false;
}
if (getLoadedPlugin(pluginClass) != null) {
- // This should not happen and means that our world view is corrupted.
- // A plugin that is already loaded that should have satisfied the dependency
- // for some reason didn't.
- // Warn about the situation and don't try to create another instance of this plugin.
- Msg.warn(this,
- "Plugin " + pluginClass.getSimpleName() + " provides service " +
- dependency.getSimpleName() +
- " but that dependency failed to be resolved correctly in a previous step.");
+ // This will not typically happen, since a plugin that is already loaded that should
+ // have satisfied the dependency. This can happen though if the dependency discovery
+ // process had to do extra work to find unsatisfied dependencies.
return true;
}
try {
- // create a new Plugin instance and get its services published.
- // when its added to the pluginList, it will be initialized in
- // addPluginInstances() after the resolveDependencies() and related methods finish.
+ // Create a new Plugin instance and get its services published. When its added to the
+ // pluginList, it will be initialized in addPluginInstances() after the
+ // resolveDependencies() and related methods finish.
PluginUtils.assertUniquePluginName(pluginClass);
Plugin p = PluginUtils.instantiatePlugin(pluginClass, tool);
@@ -533,9 +576,7 @@ class PluginManager {
private void initConfigStates(Map<String, SaveState> map) throws PluginException {
StringBuilder errMsg = new StringBuilder();
- Iterator<Plugin> it = pluginList.iterator();
- while (it.hasNext()) {
- Plugin p = it.next();
+ for (Plugin p : pluginList) {
readSaveState(p, map, errMsg);
}
if (errMsg.length() > 0) {
@@ -567,7 +608,6 @@ class PluginManager {
private List<Plugin> getPluginsByServiceOrder(int startIndex) {
List<Plugin> plugins = new ArrayList<>(pluginList.subList(startIndex, pluginList.size()));
List<Plugin> orderedList = new ArrayList<>(plugins.size());
-// showList("Before:", pluginList);
while (plugins.size() > 0) {
int n = plugins.size();
for (Iterator<Plugin> it = plugins.iterator(); it.hasNext();) {
@@ -583,19 +623,9 @@ class PluginManager {
plugins.clear();
}
}
-// showList("After:",orderedList);
return orderedList;
}
-// private void showList(String title, ArrayList list) {
-// Err.debug(this, title);
-// Iterator it = list.iterator();
-// while(it.hasNext()) {
-// Plugin p = (Plugin)it.next();
-// Err.debug(this, " "+p.getName());
-// }
-// }
-
/**
* Checks to make sure no plugins in the list provide any services used by plugin p.
* @param usingPlugin the plugin whose used services should not be provided by any plugins in the list
@@ -682,9 +712,6 @@ class PluginManager {
return false;
}
- /**
- * Close all the plugins.
- */
void close() {
for (Plugin p : pluginList) {
p.close();
@@ -709,4 +736,7 @@ class PluginManager {
}
}
+ private record PluginDependency(Class<?> dependant, Class<?> dependency) {
+ // a simple record to tie together a dependant and its required dependency
+ }
}