Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-7168 - Data Types Table - Added a table of all data types

dragonmacher6e60d7735ecd
diff --git a/Ghidra/Features/Base/certification.manifest b/Ghidra/Features/Base/certification.manifest
index d9a184e025..ffec254450 100644
--- a/Ghidra/Features/Base/certification.manifest
+++ b/Ghidra/Features/Base/certification.manifest
@@ -348,6 +348,7 @@ src/main/help/help/topics/DataTypeEditors/images/UnionEditorPacked.png||GHIDRA||
src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_archives.html||GHIDRA||||END|
src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_description.htm||GHIDRA||||END|
src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_window.html||GHIDRA||||END|
+src/main/help/help/topics/DataTypeManagerPlugin/data_types_table.html||GHIDRA||||END|
src/main/help/help/topics/DataTypeManagerPlugin/images/CommitDialog.png||GHIDRA||||END|
src/main/help/help/topics/DataTypeManagerPlugin/images/DataTypeManager.png||GHIDRA||||END|
src/main/help/help/topics/DataTypeManagerPlugin/images/DataTypeTreeWithAssociations.png||GHIDRA||||END|
diff --git a/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_window.html b/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_window.html
index 29e57a469f..0d1af2c499 100644
--- a/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_window.html
+++ b/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_type_manager_window.html
@@ -779,6 +779,7 @@
structures that contain any of the specified offsets.</P>
</BLOCKQUOTE>
+
<H3><A name="Export_Data_Types"></A>Export Data Type(s)</H3>
<BLOCKQUOTE>
@@ -834,7 +835,7 @@
<P class="relatedtopic">Related Topics:</P>
<UL>
- <LI><A href="data_type_manager_description.htm">Data Type Manager</A></LI>
+ <LI><A href="data_type_manager_description.htm">Data Type Manager</A></LI>
<LI><A href="../DataPlugin/Data.htm#DataTypes">Data Types</A></LI>
<LI><A href="../DataPlugin/Data.htm#ApplyDataType">Apply Data Types</A></LI>
<LI><A href="../DataTypeEditors/StructureEditor.htm">Edit Structure</A></LI>
diff --git a/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_types_table.html b/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_types_table.html
new file mode 100644
index 0000000000..4d4f7ea93e
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/help/help/topics/DataTypeManagerPlugin/data_types_table.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<HTML>
+ <HEAD>
+
+ <TITLE>Data Types Table</TITLE>
+ <LINK rel="stylesheet" type="text/css" href="help/shared/DefaultStyle.css">
+ </HEAD>
+
+ <BODY>
+
+ <H1><A name="Data_Types_Table"></A>Data Types Table</H1>
+
+ <P>The Data Types Table offers a way to view all data types from the
+ <A href="data_type_manager_window.html">Data Type Manager</A> tree in a table view. This
+ allows the user to find and work with types in ways that are not possible in a tree structure.
+ The right-click menu of the table provides some actions that are found in the tree.
+ </P>
+
+ <P>The Data Types Table can be shown using the <B>Show Data Types Table</B> action, which is
+ available from the drop-down menu of the Data Type Manager's header.
+ </P>
+
+ <H2>Drag and Drop</H2>
+
+ <BLOCKQUOTE>
+ <P>You can drag types from the table to the tree to copy / move data types between categories
+ and archives.
+ </P>
+ </BLOCKQUOTE>
+
+
+ <H2>Actions</H2>
+
+ <BLOCKQUOTE>
+
+ <H3><A name="Select_Data_Types_in_Tree"></A>Select Data Types in Tree</H3>
+ <BLOCKQUOTE>
+ <P>
+ This action will use the type selected in the table and select the type in the Data
+ Type Manager tree. This will add to the current tree selection, allowing you to select
+ multiple types in the tree by repeating the action.
+ </P>
+ </BLOCKQUOTE>
+
+
+ <H3><A name="Program_Types_Filter"></A>Program Types Filter</H3>
+ <BLOCKQUOTE>
+ <P>
+ This toggle action provides a way to quickly show only data types that belong to the
+ Program Data Type Manager.
+ </P>
+ </BLOCKQUOTE>
+
+
+ <H3><A name="Data_Types_Table_Clone"></A>Data Types Table Clone</H3>
+ <BLOCKQUOTE>
+ <P>
+ This action will create a new
+ <A href="help/topics/Snapshots/Snapshots.html#Snapshots_Start">snapshot</A> Data Types
+ Table provide with the same data type filter settings, table filter settings and column
+ filter settings. The program types showin in the snapshot view will be the types from
+ the program that was in the source provider used to create the snapshot window.
+ </P>
+
+ <BLOCKQUOTE>
+ <P>
+ <IMG src="help/shared/tip.png" alt="">
+ You can rename any of the Data Type Table provider windows by right-clicking on the
+ tab or the title area.
+ </P>
+ </BLOCKQUOTE>
+ </BLOCKQUOTE>
+
+ </BLOCKQUOTE>
+
+ <P class="relatedtopic">Related Topics:</P>
+
+ <BLOCKQUOTE>
+ <UL>
+ <LI><A href="data_type_manager_description.htm">Data Type Manager</A></LI>
+ <LI><A href="help/topics/DataPlugin/Data.htm#DataTypes">Data Types</A></LI>
+ </UL>
+ </BLOCKQUOTE>
+
+ <BR>
+ <BR>
+ <BR>
+ </BODY>
+</HTML>
\ No newline at end of file
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeContext.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeContext.java
new file mode 100644
index 0000000000..db5cd40656
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeContext.java
@@ -0,0 +1,44 @@
+/* ###
+ * 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.datamgr;
+
+import java.util.List;
+
+import ghidra.program.model.data.DataType;
+
+/**
+ * A context interface that signals the context providers selected data types.
+ */
+public interface DataTypeContext {
+
+ /**
+ * {@return the selected data type. If more than one type is selected, then this method will
+ * return null.}
+ */
+ public DataType getSelectedDataType();
+
+ /**
+ * {@return the selected data types}
+ */
+ public List<DataType> getSelectedDataTypes();
+
+ /**
+ * {@return true if one or more data types is selected. Use this over
+ * {@link #getSelectedDataTypes()} when speed is important, such as when checking action
+ * enablement.}
+ */
+ public boolean hasSelectedDataTypes();
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPlugin.java
index 840ed472c6..cbbca1cc9b 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPlugin.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPlugin.java
@@ -33,7 +33,7 @@ import docking.action.*;
import docking.action.builder.ActionBuilder;
import docking.actions.PopupActionProvider;
import docking.widgets.OptionDialog;
-import docking.widgets.tree.GTreeNode;
+import docking.widgets.tree.*;
import generic.jar.ResourceFile;
import generic.util.Path;
import ghidra.app.CorePluginPackage;
@@ -44,12 +44,12 @@ import ghidra.app.plugin.core.datamgr.actions.associate.*;
import ghidra.app.plugin.core.datamgr.archive.DuplicateIdException;
import ghidra.app.plugin.core.datamgr.archive.InvalidArchive;
import ghidra.app.plugin.core.datamgr.editor.DataTypeEditorManager;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeStoreNode;
-import ghidra.app.plugin.core.datamgr.tree.DtFilterState;
+import ghidra.app.plugin.core.datamgr.tree.*;
import ghidra.app.plugin.core.datamgr.util.*;
import ghidra.app.services.*;
import ghidra.app.util.datatype.DataTypeSelectionDialog;
import ghidra.framework.Application;
+import ghidra.framework.data.DomainFileProxy;
import ghidra.framework.model.*;
import ghidra.framework.options.SaveState;
import ghidra.framework.plugintool.PluginInfo;
@@ -101,6 +101,8 @@ public class DataTypeManagerPlugin extends ProgramPlugin
private ArchiveManager archiveManager;
private DataTypesProvider provider;
+ private DataTypesTableProvider tableProvider;
+ private List<DataTypesTableProvider> disconnectedTableProviders = new ArrayList<>();
private Map<String, DockingAction> recentlyOpenedArchiveMap;
private Map<String, DockingAction> installArchiveMap;
@@ -129,6 +131,7 @@ public class DataTypeManagerPlugin extends ProgramPlugin
archiveManager = new ArchiveManager(this);
dataTypePropertyManager = new DataTypePropertyManager();
provider = new DataTypesProvider(this, "DataTypes Provider");
+ tableProvider = new DataTypesTableProvider(this);
createActions();
archiveManager.addArchiveManagerListener(new ArchiveManagerListener() {
@@ -458,6 +461,8 @@ public class DataTypeManagerPlugin extends ProgramPlugin
program.addListener(this);
provider.programActivated(program);
archiveManager.setProgram(program);
+ tableProvider.programActivated(program);
+
dataTypePropertyManager.programOpened(program);
}
@@ -467,6 +472,13 @@ public class DataTypeManagerPlugin extends ProgramPlugin
// have to perform any cleanup that is done by that method.
provider.programClosed(program);
editorManager.dismissEditors(program.getDataTypeManager());
+
+ List<DataTypesTableProvider> snapshots = new LinkedList<>(disconnectedTableProviders);
+ for (DataTypesTableProvider snapshot : snapshots) {
+ if (program.equals(snapshot.getProgram())) {
+ snapshot.closeComponent();
+ }
+ }
}
@Override
@@ -535,6 +547,10 @@ public class DataTypeManagerPlugin extends ProgramPlugin
return provider;
}
+ DataTypesTableProvider getTableProvider() {
+ return tableProvider;
+ }
+
public Clipboard getClipboard() {
return clipboard;
}
@@ -666,8 +682,100 @@ public class DataTypeManagerPlugin extends ProgramPlugin
}
@Override
- public void edit(DataType dt) {
- editorManager.edit(dt);
+ public void edit(DataType dataType) {
+
+ dataType = DataTypeUtils.getBaseDataType(dataType);
+
+ dataType = getEditableDataType(dataType);
+
+ if (dataType != null) {
+ getEditorManager().edit(dataType);
+ }
+ }
+
+ private DataType getEditableDataType(DataType dataType) {
+
+ DataTypeManager dtm = dataType.getDataTypeManager();
+ DataTypeStore dataStore = dtm.getDataStore();
+ if (dataStore.isChangeable()) {
+ return dataType;
+ }
+
+ if (isUnmodifiableProjectArchive(dataStore)) {
+ return null;
+ }
+
+ if (dataStore instanceof FileDataTypeArchive fileArchive) {
+ if (!fileArchive.isChangeable()) {
+ if (!askToOpenArchiveForUpdate()) {
+ return null;
+ }
+
+ fileArchive = openForUpdate(fileArchive);
+
+ CategoryPath path = dataType.getCategoryPath();
+ String dataTypeName = dataType.getName();
+ return updateDataType(path, dataTypeName, fileArchive);
+ }
+ }
+
+ return null;
+ }
+
+ private boolean isUnmodifiableProjectArchive(DataTypeStore dataStore) {
+ if (!(dataStore instanceof ProjectDataTypeArchive projectArchive)) {
+ return false;
+ }
+
+ if (dataStore.isChangeable()) {
+ return false;
+ }
+
+ DomainFile domainFile = projectArchive.getDomainFile();
+ DomainFile originalDomainFile = getOriginalDomainFile(domainFile);
+ if (domainFile.getVersion() == originalDomainFile.getLatestVersion() &&
+ originalDomainFile.canCheckout()) {
+ Msg.showInfo(getClass(), null, "Archive Not Checked Out",
+ "You must checkout this archive before you may edit data types.");
+ }
+ else {
+ Msg.showInfo(getClass(), null, "Archive Opened Read-Only",
+ "You may not edit data type within a read-only project archive.");
+ }
+ return true;
+ }
+
+ private DomainFile getOriginalDomainFile(DomainFile domainFile) {
+ if (domainFile instanceof DomainFileProxy proxy) {
+ DomainFile originalDomainFile = proxy.getOriginalDomainFile();
+ if (originalDomainFile != null) {
+ return originalDomainFile;
+ }
+ }
+ return domainFile;
+ }
+
+ private FileDataTypeArchive openForUpdate(FileDataTypeArchive archive) {
+ GTree tree = getProvider().getGTree();
+ GTreeState state = tree.getTreeState();
+ archive = getArchiveManager().reopenFileArchive(archive, true);
+ tree.restoreTreeState(state);
+ return archive;
+ }
+
+ private static DataType updateDataType(CategoryPath path, String dataTypeName,
+ PersistentDataTypeArchive archive) {
+ if (archive == null) {
+ return null;
+ }
+ DataTypeManager dataTypeManager = archive.getDataTypeManager();
+ Category category = dataTypeManager.getCategory(path);
+ return category.getDataType(dataTypeName);
+ }
+
+ private boolean askToOpenArchiveForUpdate() {
+ return (OptionDialog.showYesNoDialog(null, "Open Archive for Edit?",
+ "Archive file is not modifiable.\nDo you want to open for edit?") == OptionDialog.OPTION_ONE);
}
@Override
@@ -865,6 +973,15 @@ public class DataTypeManagerPlugin extends ProgramPlugin
}
}
+ public void setDataTypeSelected(Collection<DataType> types) {
+ provider.clearSelection();
+ if (provider.isVisible()) {
+ for (DataType dt : types) {
+ provider.setDataTypeSelected(dt, true);
+ }
+ }
+ }
+
@Override
public void setCategorySelected(Category category) {
if (provider.isVisible()) {
@@ -962,6 +1079,22 @@ public class DataTypeManagerPlugin extends ProgramPlugin
return currentSelection;
}
+ public DtFilterState getTreeFilterState() {
+ return provider.getFilterState();
+ }
+
+ void showDataTypesTable() {
+ tableProvider.setVisible(true);
+ }
+
+ public void addDisconnectedTableProvider(DataTypesTableProvider dataTypesTableProvider) {
+ disconnectedTableProviders.add(dataTypesTableProvider);
+ }
+
+ public void removeDisconnectedTableProvider(DataTypesTableProvider dataTypesTableProvider) {
+ disconnectedTableProviders.remove(dataTypesTableProvider);
+ }
+
@Override
public List<DockingActionIf> getPopupActions(Tool dockingTool, ActionContext context) {
if (!(context instanceof DataTypesActionContext)) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesActionContext.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesActionContext.java
index edf9a2837c..1f96174253 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesActionContext.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesActionContext.java
@@ -33,13 +33,16 @@ import ghidra.program.model.data.*;
import ghidra.program.model.dtarchive.ProjectDataTypeArchive;
import ghidra.program.model.listing.Program;
-public class DataTypesActionContext extends ProgramActionContext implements DomainFileContext {
+public class DataTypesActionContext extends ProgramActionContext
+ implements DataTypeContext, DomainFileContext {
+
private final GTreeNode clickedNode;
private final boolean isToolbarAction;
private DataTypeArchiveGTree archiveGTree;
private List<DomainFile> domainFiles;
- private List<GTreeNode> clipboardNodes;
+ private List<GTreeNode> clipboardNodes; // lazy
+ private List<DataType> dataTypes; // lazy
public DataTypesActionContext(DataTypesProvider provider, Program program,
DataTypeArchiveGTree archiveGTree, GTreeNode clickedNode) {
@@ -79,6 +82,55 @@ public class DataTypesActionContext extends ProgramActionContext implements Doma
return isToolbarAction;
}
+ @Override
+ public DataType getSelectedDataType() {
+ TreePath[] selectionPaths = archiveGTree.getSelectionPaths();
+ if (selectionPaths.length > 1) {
+ return null;
+ }
+ if (clickedNode instanceof DataTypeNode dtNode) {
+ return dtNode.getDataType();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasSelectedDataTypes() {
+ if (dataTypes != null) {
+ return dataTypes.size() > 1;
+ }
+
+ TreePath[] selectionPaths = archiveGTree.getSelectionPaths();
+ for (TreePath path : selectionPaths) {
+ Object last = path.getLastPathComponent();
+ if (last instanceof DataTypeNode) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public List<DataType> getSelectedDataTypes() {
+
+ if (dataTypes != null) {
+ return dataTypes;
+ }
+
+ List<DataType> types = new ArrayList<>();
+ TreePath[] selectionPaths = archiveGTree.getSelectionPaths();
+ for (TreePath path : selectionPaths) {
+ Object last = path.getLastPathComponent();
+ if (last instanceof DataTypeNode dtNode) {
+ DataType dt = dtNode.getDataType();
+ types.add(dt);
+ }
+ }
+
+ dataTypes = Collections.unmodifiableList(types);
+ return dataTypes;
+ }
+
public GTreeNode getClickedNode() {
return clickedNode;
}
@@ -168,5 +220,4 @@ public class DataTypesActionContext extends ProgramActionContext implements Doma
}
return list;
}
-
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesProvider.java
index fe001d375f..c174015932 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesProvider.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/DataTypesProvider.java
@@ -30,26 +30,23 @@ import docking.action.DockingAction;
import docking.action.ToggleDockingAction;
import docking.event.mouse.GMouseListenerAdapter;
import docking.menu.MultiActionDockingAction;
-import docking.widgets.OptionDialog;
import docking.widgets.textpane.GHtmlTextPane;
-import docking.widgets.tree.*;
+import docking.widgets.tree.GTreeNode;
+import docking.widgets.tree.GTreeState;
import docking.widgets.tree.support.GTreeSelectionEvent.EventOrigin;
import generic.theme.GIcon;
import generic.theme.GThemeDefaults.Colors;
import ghidra.app.plugin.core.datamgr.actions.*;
import ghidra.app.plugin.core.datamgr.actions.associate.*;
import ghidra.app.plugin.core.datamgr.tree.*;
-import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
import ghidra.app.util.ToolTipUtils;
import ghidra.app.util.datatype.DataTypeUrl;
import ghidra.framework.main.projectdata.actions.*;
-import ghidra.framework.model.DomainFile;
import ghidra.framework.options.SaveState;
import ghidra.framework.plugintool.ComponentProviderAdapter;
import ghidra.program.model.data.*;
import ghidra.program.model.data.DataTypeConflictHandler.ConflictResolutionPolicy;
import ghidra.program.model.dtarchive.PersistentDataTypeArchive;
-import ghidra.program.model.dtarchive.FileDataTypeArchive;
import ghidra.program.model.listing.Program;
import ghidra.util.*;
import ghidra.util.task.SwingUpdateManager;
@@ -198,6 +195,8 @@ public class DataTypesProvider extends ComponentProviderAdapter {
addLocalAction(new FindEnumsByValueAction(plugin, "3"));
addLocalAction(new FindStructuresByOffsetAction(plugin, "4"));
addLocalAction(new FindStructuresBySizeAction(plugin, "5"));
+ addLocalAction(new ShowDataTypesTableAction(plugin, "6"));
+
includeDataMembersInSearchAction = new IncludeDataTypesInFilterAction(plugin, this, "6");
addLocalAction(includeDataMembersInSearchAction);
@@ -376,7 +375,10 @@ public class DataTypesProvider extends ComponentProviderAdapter {
return;
}
- editNode(clickedNode);
+ if (clickedNode instanceof DataTypeNode dtNode) {
+ DataType dt = dtNode.getDataType();
+ plugin.edit(dt);
+ }
}
@Override
@@ -557,90 +559,10 @@ public class DataTypesProvider extends ComponentProviderAdapter {
return helpLocation;
}
- private static DataType updateDataType(CategoryPath path, String dataTypeName,
- PersistentDataTypeArchive archive) {
- if (archive == null) {
- return null;
- }
- DataTypeManager dataTypeManager = archive.getDataTypeManager();
- Category category = dataTypeManager.getCategory(path);
- return category.getDataType(dataTypeName);
- }
-
- private boolean askToOpenArchiveForUpdate() {
- return (OptionDialog.showYesNoDialog(archiveGTree, "Open Archive for Edit?",
- "Archive file is not modifiable.\nDo you want to open for edit?") == OptionDialog.OPTION_ONE);
- }
-
//==================================================================================================
// Helper Methods
//==================================================================================================
- public void editNode(GTreeNode node) {
- if (!(node instanceof DataTypeNode)) {
- return;
- }
- DataTypeNode dataTypeNode = (DataTypeNode) node;
-
- if (!dataTypeNode.hasCustomEditor()) {
- return;
- }
-
- DataType dataType = dataTypeNode.getDataType();
- dataType = DataTypeUtils.getBaseDataType(dataType);
- CategoryPath path = dataType.getCategoryPath();
- String dataTypeName = dataType.getName();
- DataTypeStoreNode archiveNode = dataTypeNode.getArchiveNode();
-
- if (isUnmodifiableProjectArchive(archiveNode)) {
- return;
- }
-
- if (archiveNode instanceof FileArchiveNode fileNode) {
- FileDataTypeArchive archive = fileNode.getArchive();
- if (!archive.isChangeable()) {
- if (!askToOpenArchiveForUpdate()) {
- return;
- }
- archive = openForUpdate(archive);
- dataType = updateDataType(path, dataTypeName, archive);
- }
- }
- if (dataType != null) {
- plugin.getEditorManager().edit(dataType);
- }
- }
-
- private FileDataTypeArchive openForUpdate(FileDataTypeArchive archive) {
- GTree tree = plugin.getProvider().getGTree();
- GTreeState state = tree.getTreeState();
- archive = plugin.getArchiveManager().reopenFileArchive(archive, true);
- tree.restoreTreeState(state);
- return archive;
- }
-
- private boolean isUnmodifiableProjectArchive(DataTypeStoreNode archiveNode) {
- if (!(archiveNode instanceof ProjectArchiveNode projectNode)) {
- return false;
- }
-
- if (archiveNode.isModifiable()) {
- return false;
- }
- DomainFile domainFile = projectNode.getDomainFile();
- DomainFile originalDomainFile = projectNode.getOriginalDomainFile();
- if (domainFile.getVersion() == originalDomainFile.getLatestVersion() &&
- originalDomainFile.canCheckout()) {
- Msg.showInfo(getClass(), archiveGTree, "Archive Not Checked Out",
- "You must checkout this archive before you may edit data types.");
- }
- else {
- Msg.showInfo(getClass(), archiveGTree, "Archive Opened Read-Only",
- "You may not edit data type within a read-only project archive.");
- }
- return true;
- }
-
void restore(SaveState saveState) {
ConflictResolutionPolicy conflictMode;
@@ -724,6 +646,15 @@ public class DataTypesProvider extends ComponentProviderAdapter {
* @param dataType the data type to select; may be null
*/
public void setDataTypeSelected(DataType dataType) {
+ setDataTypeSelected(dataType, false);
+ }
+
+ public void clearSelection() {
+ DataTypeArchiveGTree gTree = getGTree();
+ gTree.getSelectionModel().clearSelection();
+ }
+
+ public void setDataTypeSelected(DataType dataType, boolean addToSelection) {
DataTypeArchiveGTree gTree = getGTree();
if (dataType == null) { // clear the selection
gTree.getSelectionModel().clearSelection();
@@ -761,8 +692,14 @@ public class DataTypesProvider extends ComponentProviderAdapter {
return;
}
+ if (addToSelection) {
+ gTree.addSelectedNode(dataTypeNode);
+ }
+ else {
+ gTree.setSelectedNode(dataTypeNode);
+ }
+
TreePath treePath = dataTypeNode.getTreePath();
- gTree.setSelectedNode(dataTypeNode);
gTree.scrollPathToVisible(treePath);
contextChanged();
}
@@ -1056,4 +993,5 @@ public class DataTypesProvider extends ComponentProviderAdapter {
}
}
}
+
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/FilterOnNameOnlyAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/FilterOnNameOnlyAction.java
index 5cca5770d1..1b513c98c9 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/FilterOnNameOnlyAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/FilterOnNameOnlyAction.java
@@ -4,9 +4,9 @@
* 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.
@@ -33,7 +33,7 @@ public class FilterOnNameOnlyAction extends ToggleDockingAction {
super("Filter on Name Only", plugin.getName());
this.provider = provider;
- setMenuBarData(new MenuData(new String[] { "Filter on Name Only" }, null, "VeryLast",
+ setMenuBarData(new MenuData(new String[] { "Filter on Name Only" }, null, "VeryLast2",
MenuData.NO_MNEMONIC, menuSubGroup));
setDescription("Selected indicates to use only the data type name when filtering.");
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/ShowDataTypesTableAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/ShowDataTypesTableAction.java
new file mode 100644
index 0000000000..90d9a664e7
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/ShowDataTypesTableAction.java
@@ -0,0 +1,43 @@
+/* ###
+ * 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.datamgr;
+
+import docking.ActionContext;
+import docking.action.DockingAction;
+import docking.action.MenuData;
+import ghidra.util.HelpLocation;
+
+public class ShowDataTypesTableAction extends DockingAction {
+
+ public static final String NAME = "Show Data Types Table";
+
+ private DataTypeManagerPlugin plugin;
+
+ ShowDataTypesTableAction(DataTypeManagerPlugin plugin, String menuSubGroup) {
+ super(NAME, plugin.getName());
+ this.plugin = plugin;
+
+ setMenuBarData(
+ new MenuData(new String[] { NAME }, null, "VeryLast", -1, menuSubGroup));
+
+ setHelpLocation(new HelpLocation("DataTypeManagerPlugin", "Data_Types_Table"));
+ }
+
+ @Override
+ public void actionPerformed(ActionContext context) {
+ plugin.showDataTypesTable();
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/CompareDataTypesAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/CompareDataTypesAction.java
index 52fe278a20..f3e4965e19 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/CompareDataTypesAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/CompareDataTypesAction.java
@@ -16,16 +16,12 @@
package ghidra.app.plugin.core.datamgr.actions;
import javax.swing.*;
-import javax.swing.tree.TreePath;
import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
import docking.widgets.label.GLabel;
-import docking.widgets.tree.GTree;
import ghidra.app.plugin.core.datamgr.*;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeTreeNode;
import ghidra.app.util.datatype.DataTypeSelectionDialog;
import ghidra.app.util.datatype.DataTypeSelectionEditor;
import ghidra.framework.plugintool.PluginTool;
@@ -48,43 +44,12 @@ public class CompareDataTypesAction extends DockingAction {
setPopupMenuData(new MenuData(new String[] { "Compare..." }, "EditAdvanced"));
}
- @Override
- public boolean isAddToPopup(ActionContext context) {
- DataTypeTreeNode node = getSelectedDataTypeTreeNode(context);
- return node instanceof DataTypeNode;
- }
-
@Override
public boolean isEnabledForContext(ActionContext context) {
- DataTypeTreeNode node = getSelectedDataTypeTreeNode(context);
- if (node == null) {
- return false;
- }
-
- if (!(node instanceof DataTypeNode)) {
+ if (!(context instanceof DataTypeContext dtc)) {
return false;
}
-
- return true;
- }
-
- private DataTypeTreeNode getSelectedDataTypeTreeNode(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
- return null;
- }
-
- GTree gTree = (GTree) context.getContextObject();
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length == 0) {
- return null;
- }
-
- if (selectionPaths.length > 1) {
- return null;
- }
-
- DataTypeTreeNode node = (DataTypeTreeNode) selectionPaths[0].getLastPathComponent();
- return node;
+ return dtc.getSelectedDataType() != null;
}
@Override
@@ -121,8 +86,7 @@ public class CompareDataTypesAction extends DockingAction {
return; // cancelled
}
- DataTypeTreeNode node = getSelectedDataTypeTreeNode(context);
- DataType selectedDt = ((DataTypeNode) node).getDataType();
+ DataType selectedDt = ((DataTypeContext) context).getSelectedDataType();
DataTypeCompareProvider provider =
new DataTypeCompareProvider(tool, plugin.getName(), selectedDt, otherDt);
provider.setVisible(true);
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/DtFilterAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/DtFilterAction.java
index 5067bf078a..1cbad6d0d7 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/DtFilterAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/DtFilterAction.java
@@ -59,7 +59,6 @@ public class DtFilterAction extends DockingAction {
DtFilterDialog dialog = new DtFilterDialog(currentFilterState);
plugin.getTool().showDialog(dialog, provider.getComponent());
- // if not cancelled
if (dialog.isCancelled()) {
return;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/EditAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/EditAction.java
index 035b2e135b..bb08a8184d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/EditAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/EditAction.java
@@ -1,13 +1,12 @@
/* ###
* 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.
@@ -16,11 +15,6 @@
*/
package ghidra.app.plugin.core.datamgr.actions;
-import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
-import ghidra.app.plugin.core.datamgr.DataTypesActionContext;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
-import ghidra.util.HelpLocation;
-
import javax.swing.tree.TreePath;
import docking.ActionContext;
@@ -28,6 +22,11 @@ import docking.action.DockingAction;
import docking.action.MenuData;
import docking.widgets.tree.GTree;
import docking.widgets.tree.GTreeNode;
+import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
+import ghidra.app.plugin.core.datamgr.DataTypesActionContext;
+import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
+import ghidra.program.model.data.DataType;
+import ghidra.util.HelpLocation;
public class EditAction extends DockingAction {
@@ -73,7 +72,7 @@ public class EditAction extends DockingAction {
GTree gTree = (GTree) context.getContextObject();
TreePath[] selectionPaths = gTree.getSelectionPaths();
DataTypeNode node = (DataTypeNode) selectionPaths[0].getLastPathComponent();
-
- plugin.getProvider().editNode(node);
+ DataType dt = node.getDataType();
+ plugin.edit(dt);
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/FindReferencesToDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/FindReferencesToDataTypeAction.java
index 129b68a9b7..296f285f0d 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/FindReferencesToDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/FindReferencesToDataTypeAction.java
@@ -4,9 +4,9 @@
* 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.
@@ -15,16 +15,11 @@
*/
package ghidra.app.plugin.core.datamgr.actions;
-import javax.swing.tree.TreePath;
-
import docking.ActionContext;
import docking.action.MenuData;
-import docking.widgets.tree.GTree;
-import docking.widgets.tree.GTreeNode;
import ghidra.app.actions.AbstractFindReferencesDataTypeAction;
+import ghidra.app.plugin.core.datamgr.DataTypeContext;
import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
-import ghidra.app.plugin.core.datamgr.DataTypesActionContext;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
import ghidra.program.model.data.DataType;
public class FindReferencesToDataTypeAction extends AbstractFindReferencesDataTypeAction {
@@ -38,20 +33,8 @@ public class FindReferencesToDataTypeAction extends AbstractFindReferencesDataTy
@Override
protected DataType getDataType(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
- return null;
- }
-
- Object contextObject = context.getContextObject();
- GTree gtree = (GTree) contextObject;
- TreePath[] selectionPaths = gtree.getSelectionPaths();
- if (selectionPaths.length != 1) {
- return null;
- }
-
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- if (node instanceof DataTypeNode) {
- return ((DataTypeNode) node).getDataType();
+ if (context instanceof DataTypeContext dtc) {
+ return dtc.getSelectedDataType();
}
return null;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/IncludeDataTypesInFilterAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/IncludeDataTypesInFilterAction.java
index 814696cc53..1e1e5286d4 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/IncludeDataTypesInFilterAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/IncludeDataTypesInFilterAction.java
@@ -4,9 +4,9 @@
* 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.
@@ -31,7 +31,7 @@ public class IncludeDataTypesInFilterAction extends ToggleDockingAction {
this.provider = provider;
setMenuBarData(new MenuData(new String[] { "Include Data Members in Filter" }, null,
- "VeryLast", MenuData.NO_MNEMONIC, menuSubGroup));
+ "VeryLast2", MenuData.NO_MNEMONIC, menuSubGroup));
setDescription(
"Selected indicates to include member names and data types in filter operations.");
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/PasteAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/PasteAction.java
index 8db62bbb77..788628a931 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/PasteAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/PasteAction.java
@@ -30,9 +30,10 @@ import docking.widgets.tree.GTreeNode;
import docking.widgets.tree.support.GTreeNodeTransferable;
import ghidra.app.plugin.core.datamgr.*;
import ghidra.app.plugin.core.datamgr.tree.*;
-import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask;
-import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask.ActionType;
+import ghidra.app.plugin.core.datamgr.util.DataTypesCopyMoveTask;
+import ghidra.app.plugin.core.datamgr.util.DataTypesCopyMoveTask.ActionType;
import ghidra.framework.plugintool.PluginTool;
+import ghidra.program.model.data.Category;
public class PasteAction extends DockingAction {
private PluginTool tool;
@@ -155,9 +156,11 @@ public class PasteAction extends DockingAction {
clipboard.setContents(null, null);
}
+ Category destination = destinationNode.getCategory();
ActionType actionType = getActionType(dataTypeTreeNode);
- DataTypeTreeCopyMoveTask task = new DataTypeTreeCopyMoveTask(destinationNode, nodeList,
- actionType, (DataTypeArchiveGTree) gTree, plugin.getConflictHandler());
+ DataTypesCopyMoveTask task =
+ DataTypesCopyMoveTask.forNodes(plugin, gTree, destination, nodeList, actionType);
+
tool.execute(task, 250);
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/ReplaceDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/ReplaceDataTypeAction.java
index bf46f80c47..445547eba7 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/ReplaceDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/ReplaceDataTypeAction.java
@@ -16,16 +16,13 @@
package ghidra.app.plugin.core.datamgr.actions;
import javax.swing.*;
-import javax.swing.tree.TreePath;
import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
import docking.widgets.label.GLabel;
-import docking.widgets.tree.GTree;
-import docking.widgets.tree.GTreeNode;
-import ghidra.app.plugin.core.datamgr.*;
-import ghidra.app.plugin.core.datamgr.tree.*;
+import ghidra.app.plugin.core.datamgr.DataTypeContext;
+import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
import ghidra.app.util.datatype.DataTypeSelectionDialog;
import ghidra.app.util.datatype.DataTypeSelectionEditor;
import ghidra.framework.plugintool.PluginTool;
@@ -51,24 +48,32 @@ public class ReplaceDataTypeAction extends DockingAction {
@Override
public boolean isAddToPopup(ActionContext context) {
- DataTypeTreeNode node = getSelectedDataTypeTreeNode(context);
- return node instanceof DataTypeNode;
+ if (!(context instanceof DataTypeContext dtc)) {
+ return false;
+ }
+
+ DataType dataType = dtc.getSelectedDataType();
+ return dataType != null;
}
@Override
public boolean isEnabledForContext(ActionContext context) {
- DataTypeTreeNode node = getSelectedDataTypeTreeNode(context);
- if (node == null) {
+ if (!(context instanceof DataTypeContext dtc)) {
return false;
}
- if (!(node instanceof DataTypeNode dtNode)) {
+ DataType dataType = dtc.getSelectedDataType();
+ if (dataType == null) {
return false;
}
- if (!dtNode.isModifiable()) {
+
+ DataTypeManager dtm = dataType.getDataTypeManager();
+ DataTypeStore dtStore = dtm.getDataStore();
+ if (!dtStore.isChangeable()) {
return false;
}
- if (dtNode.getDataType() instanceof BadDataType) {
+
+ if (dataType instanceof BadDataType) {
// Although BAD datatype should not appear in tree, if it does replace is
// not supported. Delete should be used instead.
return false;
@@ -76,30 +81,12 @@ public class ReplaceDataTypeAction extends DockingAction {
return true;
}
- private DataTypeTreeNode getSelectedDataTypeTreeNode(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
- return null;
- }
-
- GTree gTree = (GTree) context.getContextObject();
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length == 0) {
- return null;
- }
-
- if (selectionPaths.length > 1) {
- return null;
- }
-
- DataTypeTreeNode node = (DataTypeTreeNode) selectionPaths[0].getLastPathComponent();
- return node;
- }
-
@Override
public void actionPerformed(ActionContext context) {
- DataTypeTreeNode node = getSelectedDataTypeTreeNode(context);
- String name = node.getName();
+ DataTypeContext dtc = (DataTypeContext) context;
+ DataType oldDt = dtc.getSelectedDataType();
+ String name = oldDt.getName();
PluginTool tool = plugin.getTool();
int noSizeRestriction = -1;
@@ -132,12 +119,11 @@ public class ReplaceDataTypeAction extends DockingAction {
return; // cancelled
}
- ArchiveManager archiveManager = plugin.getArchiveManager();
DataTypeManager newDtm = newDt.getDataTypeManager();
DataTypeStore sourceStore = newDtm.getDataStore();
- DataTypeStore destinationStore = findArchive(node);
+ DataTypeManager oldDtm = oldDt.getDataTypeManager();
+ DataTypeStore destinationStore = oldDtm.getDataStore();
- DataType oldDt = ((DataTypeNode) node).getDataType();
DataTypeManager dtm = oldDt.getDataTypeManager();
if (sourceStore != destinationStore) {
oldDt = oldDt.clone(oldDt.getDataTypeManager());
@@ -155,14 +141,4 @@ public class ReplaceDataTypeAction extends DockingAction {
dtm.endTransaction(txId, true);
}
}
-
- private DataTypeStore findArchive(GTreeNode node) {
- while (node != null) {
- if (node instanceof DataTypeStoreNode archiveNode) {
- return archiveNode.getDataTypeStore();
- }
- node = node.getParent();
- }
- return null;
- }
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/AssociateDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/AssociateDataTypeAction.java
index 3c587cffc5..72709aae6a 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/AssociateDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/AssociateDataTypeAction.java
@@ -17,6 +17,7 @@ package ghidra.app.plugin.core.datamgr.actions.associate;
import java.awt.BorderLayout;
import java.awt.Component;
+import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@@ -31,17 +32,14 @@ import docking.widgets.OptionDialog;
import docking.widgets.combobox.GhidraComboBox;
import docking.widgets.label.GLabel;
import docking.widgets.list.GComboBoxCellRenderer;
-import docking.widgets.tree.GTreeNode;
-import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
-import ghidra.app.plugin.core.datamgr.DataTypesActionContext;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeStoreNode;
-import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask;
-import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask.ActionType;
+import ghidra.app.plugin.core.datamgr.*;
+import ghidra.app.plugin.core.datamgr.archive.BuiltInSourceArchive;
import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
+import ghidra.app.plugin.core.datamgr.util.DataTypesCopyMoveTask;
+import ghidra.app.plugin.core.datamgr.util.DataTypesCopyMoveTask.ActionType;
import ghidra.program.model.data.*;
-import ghidra.program.model.dtarchive.PersistentDataTypeArchive;
import ghidra.program.model.dtarchive.DataTypeStore;
+import ghidra.program.model.dtarchive.PersistentDataTypeArchive;
import ghidra.program.model.listing.Program;
import ghidra.util.Msg;
import ghidra.util.layout.PairLayout;
@@ -64,65 +62,57 @@ public class AssociateDataTypeAction extends DockingAction {
@Override
public boolean isEnabledForContext(ActionContext context) {
- // enable this action if any node is a non-built-in data type
- if (!(context instanceof DataTypesActionContext dtac)) {
- return false;
- }
- List<GTreeNode> dtNodes = getDataTypeNodes(dtac);
- if (dtNodes.isEmpty()) {
+
+ if (!(context instanceof DataTypeContext dtContext)) {
return false;
}
- DataTypeStore singleDataTypeStore = getSingleDataTypeStore(dtNodes);
- // NOTE: We only support program-to-archive since other cases become rather complicated
- // when considering dependencies that must get copied and how their associations should be
- // handled.
- return singleDataTypeStore instanceof Program;
+ return dtContext.hasSelectedDataTypes();
}
- private List<GTreeNode> getDataTypeNodes(DataTypesActionContext ctx) {
- List<GTreeNode> allNodes = ctx.getSelectedNodes();
- return allNodes.stream()
- .filter(n -> (n instanceof DataTypeNode dtn &&
- !(dtn.getDataType() instanceof BuiltInDataType)))
- .collect(Collectors.toList());
+ private boolean isAlreadyAssociated(DataTypeContext dtc) {
+ List<DataType> types = dtc.getSelectedDataTypes();
+ for (DataType dt : types) {
+ if (isDisassociatable(dt)) {
+ return true;
+ }
+ }
+ return false;
}
- private boolean isAlreadyAssociated(DataTypesActionContext dtContext) {
- List<DataTypeNode> nodes = dtContext.getDisassociatableNodes();
- return !nodes.isEmpty();
+ private boolean isDisassociatable(DataType dt) {
+ DataTypeManager dataTypeManager = dt.getDataTypeManager();
+ SourceArchive sourceArchive = dt.getSourceArchive();
+ if (sourceArchive == null || dataTypeManager == null ||
+ sourceArchive.equals(BuiltInSourceArchive.INSTANCE) ||
+ sourceArchive.getSourceArchiveID().equals(dataTypeManager.getUniversalID())) {
+ return false;
+ }
+ return true;
}
- private DataTypeStore getSingleDataTypeStore(List<GTreeNode> nodes) {
+ private DataTypeStore getSingleDataTypeStore(Collection<DataType> types) {
+
+ DataTypeStore store = null;
+ for (DataType dt : types) {
- DataTypeStore dtArchive = null;
- for (GTreeNode node : nodes) {
- DataTypeStore archive = findDataStore(node);
- if (dtArchive == null) {
- dtArchive = archive;
+ DataTypeManager dtm = dt.getDataTypeManager();
+ DataTypeStore dataStore = dtm.getDataStore();
+ if (store == null) {
+ store = dataStore;
continue;
}
- if (dtArchive != archive) {
+ if (store != dataStore) {
return null;
}
}
- return dtArchive;
- }
-
- private static DataTypeStore findDataStore(GTreeNode node) {
- while (node != null) {
- if (node instanceof DataTypeStoreNode archiveNode) {
- return archiveNode.getDataTypeStore();
- }
- node = node.getParent();
- }
- return null;
+ return store;
}
private List<PersistentDataTypeArchive> getDestinationArchives(DataTypeStore excluded) {
-
- List<PersistentDataTypeArchive> archives = plugin.getArchiveManager().getOpenArchives();
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ List<PersistentDataTypeArchive> archives = archiveManager.getOpenArchives();
List<PersistentDataTypeArchive> destArchives = archives.stream()
.filter(a -> !a.equals(excluded))
.sorted((a1, a2) -> a1.getName().compareToIgnoreCase(a2.getName()))
@@ -134,13 +124,20 @@ public class AssociateDataTypeAction extends DockingAction {
@Override
public void actionPerformed(ActionContext context) {
- List<GTreeNode> dtNodes = getDataTypeNodes((DataTypesActionContext) context);
- if (dtNodes.isEmpty()) {
- return;
- }
- DataTypeStore dtStore = getSingleDataTypeStore(dtNodes);
- if (dtStore == null) {
- return;
+ DataTypeContext dtContext = (DataTypeContext) context;
+
+ List<DataType> types = dtContext.getSelectedDataTypes();
+ DataTypeStore dtStore = getSingleDataTypeStore(types);
+
+ // NOTE: We only support program-to-archive since other cases become rather complicated
+ // when considering dependencies that must get copied and how their associations should be
+ // handled.
+ if (!(dtStore instanceof Program)) {
+ if (types.isEmpty()) {
+ Msg.showInfo(this, null, "Cannot Associate Types",
+ "Can only associate types from the program");
+ return;
+ }
}
if (!dtStore.isChangeable()) {
@@ -149,8 +146,9 @@ public class AssociateDataTypeAction extends DockingAction {
return;
}
- if (isAlreadyAssociated((DataTypesActionContext) context)) {
- Msg.showInfo(this, getProviderComponent(), "Already Associated",
+ Component component = context.getSourceComponent();
+ if (isAlreadyAssociated(dtContext)) {
+ Msg.showInfo(this, component, "Already Associated",
"One or more of the currently selected nodes are already associated\n" +
"with a source archive.");
return;
@@ -158,13 +156,13 @@ public class AssociateDataTypeAction extends DockingAction {
List<PersistentDataTypeArchive> archives = getDestinationArchives(dtStore);
if (archives.isEmpty()) {
- Msg.showInfo(this, getProviderComponent(), "No Source Archives Open",
+ Msg.showInfo(this, component, "No Source Archives Open",
"No source archives open. Please open the desired source archive.");
return;
}
ChooseArchiveDialog dialog = new ChooseArchiveDialog(archives);
- dialog.show();
+ dialog.show(component);
if (dialog.isCancelled()) {
return;
}
@@ -172,17 +170,14 @@ public class AssociateDataTypeAction extends DockingAction {
PersistentDataTypeArchive destinationArchive = dialog.getArchive();
Category destinationCategory = dialog.getCategory();
- DataTypeTreeCopyMoveTask task =
- new DataTypeTreeCopyMoveTask(destinationArchive, destinationCategory, dtNodes,
- ActionType.COPY, plugin.getProvider().getGTree(), plugin.getConflictHandler());
+ DataTypesCopyMoveTask task =
+ new DataTypesCopyMoveTask(plugin, destinationArchive, destinationCategory, types, null,
+ ActionType.COPY);
+
task.setPromptToAssociateTypes(false); // do not prompt the user; they have already decided
TaskLauncher.launch(task);
}
- private JComponent getProviderComponent() {
- return plugin.getProvider().getComponent();
- }
-
private class ChooseArchiveDialog extends DialogComponentProvider {
private Category category;
@@ -315,8 +310,7 @@ public class AssociateDataTypeAction extends DockingAction {
return isCancelled;
}
- void show() {
- JComponent parent = getProviderComponent();
+ void show(Component parent) {
DockingWindowManager.showDialog(parent, this);
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/CommitSingleDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/CommitSingleDataTypeAction.java
index b497af044b..b4ea887e36 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/CommitSingleDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/CommitSingleDataTypeAction.java
@@ -16,17 +16,13 @@
package ghidra.app.plugin.core.datamgr.actions.associate;
import javax.swing.Icon;
-import javax.swing.tree.TreePath;
import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
import docking.widgets.OptionDialog;
-import docking.widgets.tree.GTree;
-import docking.widgets.tree.GTreeNode;
import generic.theme.GIcon;
import ghidra.app.plugin.core.datamgr.*;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
import ghidra.program.model.data.*;
import ghidra.util.Msg;
@@ -52,23 +48,15 @@ public class CommitSingleDataTypeAction extends DockingAction {
@Override
public boolean isEnabledForContext(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
+ if (!(context instanceof DataTypeContext dtc)) {
return false;
}
- Object contextObject = context.getContextObject();
- GTree gTree = (GTree) contextObject;
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length != 1) {
+ DataType dataType = dtc.getSelectedDataType();
+ if (dataType == null) {
return false;
}
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- if (!(node instanceof DataTypeNode)) {
- return false;
- }
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
ArchiveManager archiveManager = plugin.getArchiveManager();
DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dataType);
@@ -88,23 +76,15 @@ public class CommitSingleDataTypeAction extends DockingAction {
@Override
public void actionPerformed(ActionContext context) {
- GTree gTree = (GTree) context.getContextObject();
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length != 1) {
- return;
- }
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- if (!(node instanceof DataTypeNode)) {
- return;
- }
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
+
+ DataType dataType = ((DataTypeContext) context).getSelectedDataType();
DataTypeManager dtm = dataType.getDataTypeManager();
ArchiveManager archiveManager = plugin.getArchiveManager();
DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dataType);
if (syncStatus == DataTypeSyncState.CONFLICT) {
- int result = OptionDialog.showOptionDialog(gTree, "Lose Changes in Archive?",
+ int result = OptionDialog.showOptionDialog(context.getSourceComponent(),
+ "Lose Changes in Archive?",
"This data type has changes in the archive that will be\n" +
"overwritten if you commit this data type",
"Continue?", OptionDialog.WARNING_MESSAGE);
@@ -112,23 +92,28 @@ public class CommitSingleDataTypeAction extends DockingAction {
return;
}
}
+
SourceArchive sourceArchive = dataType.getSourceArchive();
DataTypeManager sourceDTM =
plugin.getArchiveManager().getDataTypeManager(sourceArchive);
if (sourceDTM == null) {
- Msg.showInfo(getClass(), gTree, "Commit Failed",
+ Msg.showInfo(this, context.getSourceComponent(), "Commit Failed",
"Source Archive not open: " + sourceArchive.getName());
return;
}
+
if (!sourceDTM.isUpdatable()) {
- DataTypeUtils.showUnmodifiableArchiveErrorMessage(gTree, "Commit Failed!", sourceDTM);
+ DataTypeUtils.showUnmodifiableArchiveErrorMessage(context.getSourceComponent(),
+ "Commit Failed!", sourceDTM);
return;
}
+
if (!dataType.getDataTypeManager().isUpdatable()) {
- DataTypeUtils.showUnmodifiableArchiveErrorMessage(gTree, "Commit Failed",
- dataType.getDataTypeManager());
+ DataTypeUtils.showUnmodifiableArchiveErrorMessage(context.getSourceComponent(),
+ "Commit Failed", dataType.getDataTypeManager());
return;
}
+
plugin.commit(dataType);
// Source archive data type manager was already checked for null above.
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/DisassociateDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/DisassociateDataTypeAction.java
index 8a6a111d38..8d3e8035ad 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/DisassociateDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/DisassociateDataTypeAction.java
@@ -20,20 +20,20 @@ import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.swing.SwingConstants;
-import javax.swing.tree.TreePath;
import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
import docking.widgets.OptionDialog;
-import docking.widgets.tree.*;
+import docking.widgets.tree.GTreeNode;
+import docking.widgets.tree.GTreeState;
import ghidra.app.plugin.core.datamgr.*;
import ghidra.app.plugin.core.datamgr.archive.BuiltInSourceArchive;
import ghidra.app.plugin.core.datamgr.tree.DataTypeArchiveGTree;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
import ghidra.program.model.data.*;
import ghidra.util.HTMLUtilities;
+import ghidra.util.Msg;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.*;
@@ -52,91 +52,79 @@ public class DisassociateDataTypeAction extends DockingAction {
@Override
public boolean isEnabledForContext(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
+ if (!(context instanceof DataTypeContext dtc)) {
return false;
}
- DataTypesActionContext dtContext = (DataTypesActionContext) context;
- List<DataTypeNode> nodes = dtContext.getDisassociatableNodes();
- return !nodes.isEmpty();
+ return dtc.hasSelectedDataTypes();
}
- private List<DataTypeNode> getDisassociatableNodes(TreePath[] paths) {
-
- List<DataTypeNode> nodes = new ArrayList<>();
- for (TreePath treePath : paths) {
- DataTypeNode node = getDisassociatableNode(treePath);
- if (node != null) {
- nodes.add(node);
+ private List<DataType> getDisassociatableTypes(DataTypeContext dtc) {
+ List<DataType> result = new ArrayList<>();
+ List<DataType> types = dtc.getSelectedDataTypes();
+ for (DataType dt : types) {
+ if (isDisassociatable(dt)) {
+ result.add(dt);
}
}
- return nodes;
+ return result;
}
- private DataTypeNode getDisassociatableNode(TreePath path) {
- GTreeNode node = (GTreeNode) path.getLastPathComponent();
- if (!(node instanceof DataTypeNode)) {
- return null;
- }
-
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
- DataTypeManager dataTypeManager = dataType.getDataTypeManager();
- SourceArchive sourceArchive = dataType.getSourceArchive();
+ private boolean isDisassociatable(DataType dt) {
+ DataTypeManager dataTypeManager = dt.getDataTypeManager();
+ SourceArchive sourceArchive = dt.getSourceArchive();
if (sourceArchive == null || dataTypeManager == null ||
sourceArchive.equals(BuiltInSourceArchive.INSTANCE) ||
sourceArchive.getSourceArchiveID().equals(dataTypeManager.getUniversalID())) {
-
- return null;
+ return false;
}
- return dataTypeNode;
+ return true;
}
@Override
public void actionPerformed(ActionContext context) {
- Object contextObject = context.getContextObject();
- GTree gTree = (GTree) contextObject;
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- List<DataTypeNode> nodes = getDisassociatableNodes(selectionPaths);
+ DataTypeContext dtc = (DataTypeContext) context;
+ List<DataType> types = getDisassociatableTypes(dtc);
+
+ if (types.isEmpty()) {
+ Msg.showInfo(this, null, "No Disassociatable Types Selected",
+ "No disassociatable types selected");
+ return;
+ }
//@formatter:off
- Optional<DataTypeManager> unmodifiableDtm = nodes
+ Optional<DataTypeManager> unmodifiableDtm = types
.stream()
- .map(node -> {
- DataType dataType = node.getDataType();
- DataTypeManager dtm = dataType.getDataTypeManager();
- return dtm;
- })
- .filter(dtm -> {
- return !dtm.isUpdatable();
- })
+ .map(dt -> dt.getDataTypeManager())
+ .filter(dtm -> !dtm.isUpdatable())
.findAny();
//@formatter:on
if (unmodifiableDtm.isPresent()) {
DataTypeManager dtm = unmodifiableDtm.get();
- DataTypeUtils.showUnmodifiableArchiveErrorMessage(gTree, "Disassociate Failed", dtm);
+ DataTypeUtils.showUnmodifiableArchiveErrorMessage(context.getSourceComponent(),
+ "Disassociate Failed", dtm);
return;
}
- if (!confirmOperation(nodes)) {
+ if (!confirmOperation(types.size())) {
return;
}
//@formatter:off
MonitoredRunnable r =
- monitor -> doDisassociate(nodes, monitor);
+ monitor -> doDisassociate(types, monitor);
new TaskBuilder("Disassociate From Archive", r)
.setStatusTextAlignment(SwingConstants.LEADING)
.launchModal();
//@formatter:on
}
- private boolean confirmOperation(List<DataTypeNode> nodes) {
+ private boolean confirmOperation(int size) {
String message = "This will <b>permanently</b> disassociate these datatypes" +
" from the archive.<br><br>Are you sure you want to <b><u>disassociate</u></b> " +
- nodes.size() + " datatype(s)?";
+ size + " datatype(s)?";
String asHtml = HTMLUtilities.wrapAsHTML(message);
int result = OptionDialog.showYesNoDialog(plugin.getTool().getToolFrame(),
"Confirm Disassociate", asHtml);
@@ -151,10 +139,7 @@ public class DisassociateDataTypeAction extends DockingAction {
archives.forEach(archive -> tree.collapseAll(archive));
}
- private void doDisassociate(List<DataTypeNode> nodes, TaskMonitor monitor) {
-
- List<DataType> dataTypes =
- nodes.stream().map(node -> node.getDataType()).collect(Collectors.toList());
+ private void doDisassociate(List<DataType> types, TaskMonitor monitor) {
//
// Note: we collapse the node before performing this work because there is a
@@ -171,7 +156,7 @@ public class DisassociateDataTypeAction extends DockingAction {
collapseArchiveNodes(tree);
try {
- disassociateTypes(dataTypes, monitor);
+ disassociateTypes(types, monitor);
}
catch (CancelledException e) {
// nothing to report
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/RevertDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/RevertDataTypeAction.java
index 4f30c65a3e..83340aadc4 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/RevertDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/RevertDataTypeAction.java
@@ -15,15 +15,12 @@
*/
package ghidra.app.plugin.core.datamgr.actions.associate;
-import javax.swing.tree.TreePath;
+import java.awt.Component;
import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
-import docking.widgets.tree.GTree;
-import docking.widgets.tree.GTreeNode;
import ghidra.app.plugin.core.datamgr.*;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
import ghidra.program.model.data.*;
import ghidra.util.Msg;
@@ -41,27 +38,17 @@ public class RevertDataTypeAction extends DockingAction {
@Override
public boolean isEnabledForContext(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
+ if (!(context instanceof DataTypeContext dtc)) {
return false;
}
- Object contextObject = context.getContextObject();
- GTree gTree = (GTree) contextObject;
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length != 1) {
+ DataType dataType = dtc.getSelectedDataType();
+ if (dataType == null) {
return false;
}
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- if (!(node instanceof DataTypeNode)) {
- return false;
- }
-
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
ArchiveManager archiveManager = plugin.getArchiveManager();
DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dataType);
-
switch (syncStatus) {
case UNKNOWN:
return false;
@@ -78,29 +65,24 @@ public class RevertDataTypeAction extends DockingAction {
@Override
public void actionPerformed(ActionContext context) {
- GTree gTree = (GTree) context.getContextObject();
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length != 1) {
- return;
- }
-
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
+ DataType dataType = ((DataTypeContext) context).getSelectedDataType();
DataTypeManager dtm = dataType.getDataTypeManager();
ArchiveManager archiveManager = plugin.getArchiveManager();
SourceArchive sourceArchive = dataType.getSourceArchive();
+ Component component = context.getSourceComponent();
if (!dtm.isUpdatable()) {
- DataTypeUtils.showUnmodifiableArchiveErrorMessage(gTree, "Revert Failed", dtm);
+ DataTypeUtils.showUnmodifiableArchiveErrorMessage(component, "Revert Failed", dtm);
return;
}
- DataTypeManager sourceDTM = archiveManager.getDataTypeManager(sourceArchive);
- if (sourceDTM == null) {
- Msg.showInfo(getClass(), gTree, "Revert Failed",
+
+ DataTypeManager sourceDtm = archiveManager.getDataTypeManager(sourceArchive);
+ if (sourceDtm == null) {
+ Msg.showInfo(getClass(), component, "Revert Failed",
"Source Archive not open: " + sourceArchive.getName());
return;
}
+
plugin.revert(dataType);
// Source archive data type manager was already checked for null above.
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/UpdateSingleDataTypeAction.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/UpdateSingleDataTypeAction.java
index 9d112e1fed..f23793f5a3 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/UpdateSingleDataTypeAction.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/actions/associate/UpdateSingleDataTypeAction.java
@@ -16,17 +16,13 @@
package ghidra.app.plugin.core.datamgr.actions.associate;
import javax.swing.Icon;
-import javax.swing.tree.TreePath;
import docking.ActionContext;
import docking.action.DockingAction;
import docking.action.MenuData;
import docking.widgets.OptionDialog;
-import docking.widgets.tree.GTree;
-import docking.widgets.tree.GTreeNode;
import generic.theme.GIcon;
import ghidra.app.plugin.core.datamgr.*;
-import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
import ghidra.program.model.data.*;
import resources.MultiIcon;
@@ -50,26 +46,17 @@ public class UpdateSingleDataTypeAction extends DockingAction {
@Override
public boolean isEnabledForContext(ActionContext context) {
- if (!(context instanceof DataTypesActionContext)) {
+ if (!(context instanceof DataTypeContext dtContext)) {
return false;
}
- Object contextObject = context.getContextObject();
- GTree gTree = (GTree) contextObject;
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length != 1) {
+ DataType dt = dtContext.getSelectedDataType();
+ if (dt == null) {
return false;
}
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- if (!(node instanceof DataTypeNode)) {
- return false;
- }
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
ArchiveManager archiveManager = plugin.getArchiveManager();
- DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dataType);
-
+ DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dt);
switch (syncStatus) {
case UNKNOWN:
return false;
@@ -86,37 +73,32 @@ public class UpdateSingleDataTypeAction extends DockingAction {
@Override
public void actionPerformed(ActionContext context) {
- GTree gTree = (GTree) context.getContextObject();
- TreePath[] selectionPaths = gTree.getSelectionPaths();
- if (selectionPaths == null || selectionPaths.length != 1) {
- return;
- }
+ DataTypeContext dtContext = (DataTypeContext) context;
+ DataType dt = dtContext.getSelectedDataType();
- GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();
- if (!(node instanceof DataTypeNode)) {
- return;
- }
- DataTypeNode dataTypeNode = (DataTypeNode) node;
- DataType dataType = dataTypeNode.getDataType();
- DataTypeManager dtm = dataType.getDataTypeManager();
+ DataTypeManager dtm = dt.getDataTypeManager();
ArchiveManager archiveManager = plugin.getArchiveManager();
- SourceArchive sourceArchive = dataType.getSourceArchive();
- DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dataType);
+ SourceArchive sourceArchive = dt.getSourceArchive();
+ DataTypeSyncState syncStatus = DataTypeSynchronizer.getSyncStatus(archiveManager, dt);
if (syncStatus == DataTypeSyncState.CONFLICT) {
- int result = OptionDialog.showOptionDialog(gTree, "Lose Local Changes?",
- "This data type has local changes that will be\n" +
- "overwritten if you update this data type",
- "Continue?", OptionDialog.WARNING_MESSAGE);
+ int result =
+ OptionDialog.showOptionDialog(context.getSourceComponent(), "Lose Local Changes?",
+ "This data type has local changes that will be\n" +
+ "overwritten if you update this data type",
+ "Continue?", OptionDialog.WARNING_MESSAGE);
if (result == OptionDialog.CANCEL_OPTION) {
return;
}
}
+
if (!dtm.isUpdatable()) {
- DataTypeUtils.showUnmodifiableArchiveErrorMessage(gTree, "Update Failed", dtm);
+ DataTypeUtils.showUnmodifiableArchiveErrorMessage(context.getSourceComponent(),
+ "Update Failed", dtm);
return;
}
- plugin.update(dataType);
+
+ plugin.update(dt);
DataTypeManager sourceDTM = archiveManager.getDataTypeManager(sourceArchive);
if (sourceDTM != null) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeArchiveGTree.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeArchiveGTree.java
index 003186537e..e07f3cef53 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeArchiveGTree.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeArchiveGTree.java
@@ -56,10 +56,10 @@ public class DataTypeArchiveGTree extends GTree {
private MyFolderListener folderListener;
private DataTypeTreeExpansionListener cleanupListener = new DataTypeTreeExpansionListener();
- public DataTypeArchiveGTree(DataTypeManagerPlugin dataTypeManagerPlugin) {
- super(new ArchiveRootNode(dataTypeManagerPlugin.getArchiveManager()));
+ public DataTypeArchiveGTree(DataTypeManagerPlugin plugin) {
+ super(new ArchiveRootNode(plugin.getArchiveManager()));
- this.plugin = dataTypeManagerPlugin;
+ this.plugin = plugin;
setDragNDropHandler(new DataTypeDragNDropHandler(plugin, this));
DataTypeTreeRenderer renderer = new DataTypeTreeRenderer();
@@ -83,6 +83,10 @@ public class DataTypeArchiveGTree extends GTree {
initializeKeyEvents();
}
+ public DataTypesProvider getProvider() {
+ return plugin.getProvider();
+ }
+
private void initializeKeyEvents() {
// remove Java's default bindings for Copy/Paste on this tree, as they cause conflicts
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeDragNDropHandler.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeDragNDropHandler.java
index a0057fbf71..3f66b50f24 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeDragNDropHandler.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeDragNDropHandler.java
@@ -27,23 +27,24 @@ import docking.widgets.tree.GTreeNode;
import docking.widgets.tree.support.GTreeDragNDropHandler;
import generic.jar.ResourceFile;
import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
-import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask;
-import ghidra.app.plugin.core.datamgr.util.DataTypeTreeCopyMoveTask.ActionType;
+import ghidra.app.plugin.core.datamgr.util.DataTypesCopyMoveTask;
+import ghidra.app.plugin.core.datamgr.util.DataTypesCopyMoveTask.ActionType;
import ghidra.program.database.dtarchive.FileDtArchiveDB;
import ghidra.program.model.data.*;
+import ghidra.program.model.dtarchive.DataTypeStore;
import ghidra.util.Msg;
-import ghidra.util.task.Task;
public class DataTypeDragNDropHandler implements GTreeDragNDropHandler {
- private static DataFlavor localDataTypeTreeFlavor = createLocalTreeNodeFlavor();
- public static DataFlavor[] allSupportedFlavors =
- { DataTypeTransferable.localDataTypeFlavor, localDataTypeTreeFlavor };
+ /** A list of GTree nodes from the Data Type tree */
+ private static DataFlavor localDataTypeTreeFlavor = createLocalTreeNodeFlavor();
- public static DataFlavor[] builtinFlavors =
+ private static DataFlavor[] allSupportedFlavors =
+ { DataTypeTransferable.localDataTypeFlavor, localDataTypeTreeFlavor,
+ DataTypeTransferable.localDataTypeListFlavor };
+ private static DataFlavor[] builtinFlavors =
{ DataTypeTransferable.localBuiltinDataTypeFlavor, localDataTypeTreeFlavor };
-
- public static DataFlavor[] restrictedFlavors = { localDataTypeTreeFlavor };
+ private static DataFlavor[] restrictedFlavors = { localDataTypeTreeFlavor };
private final GTree tree;
@@ -51,15 +52,9 @@ public class DataTypeDragNDropHandler implements GTreeDragNDropHandler {
// create a data flavor that is an List of GTreeNodes
private static DataFlavor createLocalTreeNodeFlavor() {
- try {
- return new GenericDataFlavor(
- DataFlavor.javaJVMLocalObjectMimeType + "; class=java.util.List",
- "Local list of Drag/Drop DataType Tree objects");
- }
- catch (Exception e) {
- Msg.showError(DataTypeDragNDropHandler.class, null, null, null, e);
- }
- return null;
+ return new GenericDataFlavor(
+ DataFlavor.javaJVMLocalObjectMimeType + "; class=java.util.List",
+ "Local list of Drag/Drop DataType Tree objects");
}
public DataTypeDragNDropHandler(DataTypeManagerPlugin plugin, GTree tree) {
@@ -68,28 +63,58 @@ public class DataTypeDragNDropHandler implements GTreeDragNDropHandler {
}
@Override
- @SuppressWarnings("unchecked") // old API call
+ @SuppressWarnings("unchecked") // getTransferData(); old API call
public void drop(GTreeNode destinationNode, Transferable transferable, int dropAction) {
+
try {
- List<GTreeNode> list =
- (List<GTreeNode>) transferable.getTransferData(localDataTypeTreeFlavor);
- if (list.contains(destinationNode)) { // don't allow drop on dragged nodes.
+ if (transferable.isDataFlavorSupported(localDataTypeTreeFlavor)) {
+ List<GTreeNode> nodes =
+ (List<GTreeNode>) transferable.getTransferData(localDataTypeTreeFlavor);
+ dropDtNodes(destinationNode, nodes, dropAction);
return;
}
- CategoryNode updatedDestinationNode = getDropTargetNode(destinationNode);
- ActionType actionType =
- dropAction == DnDConstants.ACTION_COPY ? ActionType.COPY : ActionType.MOVE;
- Task task = new DataTypeTreeCopyMoveTask(updatedDestinationNode, list, actionType,
- (DataTypeArchiveGTree) tree, plugin.getConflictHandler());
- plugin.getTool().execute(task, 250);
+ if (transferable.isDataFlavorSupported(DataTypeTransferable.localDataTypeListFlavor)) {
+ List<DataType> types = (List<DataType>) transferable.getTransferData(
+ DataTypeTransferable.localDataTypeListFlavor);
+ dropTypes(destinationNode, types, dropAction);
+ return;
+ }
+
+ Msg.error(this, "Unable to perform drop operation");
}
- catch (UnsupportedFlavorException e) {
+ catch (IOException | UnsupportedFlavorException e) {
Msg.error(this, "Unable to perform drop operation", e);
}
- catch (IOException e) {
- Msg.error(this, "Unable to perform drop operation", e);
+ }
+
+ private void dropTypes(GTreeNode destinationNode, List<DataType> types, int dropAction) {
+
+ CategoryNode updatedDestinationNode = getDropTargetNode(destinationNode);
+ Category destination = updatedDestinationNode.getCategory();
+ DataTypeManager dtm = destination.getDataTypeManager();
+ DataTypeStore dataStore = dtm.getDataStore();
+ ActionType actionType =
+ dropAction == DnDConstants.ACTION_COPY ? ActionType.COPY : ActionType.MOVE;
+ DataTypesCopyMoveTask task =
+ new DataTypesCopyMoveTask(plugin, dataStore, destination, types, List.of(), actionType);
+
+ plugin.getTool().execute(task, 250);
+ }
+
+ private void dropDtNodes(GTreeNode destinationNode, List<GTreeNode> nodes, int dropAction) {
+ if (nodes.contains(destinationNode)) { // don't allow drop on dragged nodes.
+ return;
}
+
+ CategoryNode updatedDestinationNode = getDropTargetNode(destinationNode);
+ Category destination = updatedDestinationNode.getCategory();
+ ActionType actionType =
+ dropAction == DnDConstants.ACTION_COPY ? ActionType.COPY : ActionType.MOVE;
+ DataTypesCopyMoveTask task =
+ DataTypesCopyMoveTask.forNodes(plugin, tree, destination, nodes, actionType);
+
+ plugin.getTool().execute(task, 250);
}
private CategoryNode getDropTargetNode(GTreeNode node) {
@@ -192,11 +217,6 @@ public class DataTypeDragNDropHandler implements GTreeDragNDropHandler {
return false;
}
- // can only drop/paste nodes from other dataType trees
- if (!containsFlavor(flavors, localDataTypeTreeFlavor)) {
- return false;
- }
-
// destination node must belong to either a modifiable archive or a program archive.
// i.e. it must be writable.
DataTypeStoreNode archiveNode = ((DataTypeTreeNode) destinationNode).getArchiveNode();
@@ -204,6 +224,16 @@ public class DataTypeDragNDropHandler implements GTreeDragNDropHandler {
return false;
}
+ // dropping from a data types table
+ if (containsFlavor(flavors, DataTypeTransferable.localDataTypeListFlavor)) {
+ return true;
+ }
+
+ // drop/paste nodes from other dataType trees
+ if (!containsFlavor(flavors, localDataTypeTreeFlavor)) {
+ return false;
+ }
+
return true;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeTableContext.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeTableContext.java
new file mode 100644
index 0000000000..d76ed0b9c2
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypeTableContext.java
@@ -0,0 +1,51 @@
+/* ###
+ * 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.datamgr.tree;
+
+import java.util.Collections;
+import java.util.List;
+
+import docking.DefaultActionContext;
+import ghidra.app.plugin.core.datamgr.DataTypeContext;
+import ghidra.program.model.data.DataType;
+
+public class DataTypeTableContext extends DefaultActionContext implements DataTypeContext {
+
+ private List<DataType> selectedTypes;
+
+ DataTypeTableContext(DataTypesTableProvider provider, List<DataType> selectedTypes) {
+ super(provider, provider.getTable());
+ this.selectedTypes = selectedTypes;
+ }
+
+ @Override
+ public DataType getSelectedDataType() {
+ if (selectedTypes.size() == 1) {
+ return selectedTypes.get(0);
+ }
+ return null;
+ }
+
+ @Override
+ public List<DataType> getSelectedDataTypes() {
+ return Collections.unmodifiableList(selectedTypes);
+ }
+
+ @Override
+ public boolean hasSelectedDataTypes() {
+ return !selectedTypes.isEmpty();
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypesTableProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypesTableProvider.java
new file mode 100644
index 0000000000..d3bcf23353
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DataTypesTableProvider.java
@@ -0,0 +1,1134 @@
+/* ###
+ * 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.datamgr.tree;
+
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.awt.dnd.DnDConstants;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.io.IOException;
+import java.util.*;
+import java.util.List;
+
+import javax.help.UnsupportedOperationException;
+import javax.swing.*;
+
+import docking.*;
+import docking.action.*;
+import docking.action.builder.ActionBuilder;
+import docking.action.builder.ToggleActionBuilder;
+import docking.dnd.GTableDragProvider;
+import docking.widgets.table.*;
+import docking.widgets.table.threaded.ThreadedTableModel;
+import docking.widgets.table.threaded.ThreadedTableModelListener;
+import generic.theme.GIcon;
+import ghidra.app.nav.DecoratorPanel;
+import ghidra.app.plugin.core.datamgr.*;
+import ghidra.app.plugin.core.datamgr.actions.*;
+import ghidra.app.plugin.core.datamgr.actions.associate.*;
+import ghidra.app.plugin.core.datamgr.archive.InvalidArchive;
+import ghidra.app.plugin.core.datamgr.util.DataTypeUtils;
+import ghidra.docking.settings.Settings;
+import ghidra.framework.options.PreferenceState;
+import ghidra.framework.plugintool.PluginTool;
+import ghidra.framework.plugintool.ServiceProvider;
+import ghidra.program.model.data.*;
+import ghidra.program.model.data.Composite;
+import ghidra.program.model.data.Enum;
+import ghidra.program.model.dtarchive.DataTypeStore;
+import ghidra.program.model.dtarchive.PersistentDataTypeArchive;
+import ghidra.program.model.listing.Program;
+import ghidra.util.*;
+import ghidra.util.datastruct.Accumulator;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.table.GhidraTableFilterPanel;
+import ghidra.util.table.GhidraThreadedTablePanel;
+import ghidra.util.table.column.AbstractGColumnRenderer;
+import ghidra.util.table.column.GColumnRenderer;
+import ghidra.util.table.field.AbstractProgramBasedDynamicTableColumn;
+import ghidra.util.task.TaskMonitor;
+import resources.Icons;
+
+/**
+ * A component provider that shows a table of data types. For a tree of data types, see the
+ * {@link DataTypesProvider}.
+ */
+public class DataTypesTableProvider extends ComponentProvider {
+
+ private static final String FILTER_STATE_PREF_KEY =
+ DataTypesTableProvider.class.getSimpleName() + ".DtFilterState";
+
+ private static final String SHOW_ONLY_PROGRAM_TYPES_KEY = "SHOW_ONLY_PROGRAM_TYPES";
+
+ private DataTypeManagerPlugin plugin;
+ private JComponent component;
+ private DataTypesModel model;
+ private GTable table;
+ private GhidraTableFilterPanel<DataType> filterPanel;
+ private DtFilterState filterState = new DtFilterState();
+
+ private DtTableArchiveListener archiveListener;
+ private DataTypeManagerChangeListener dtmListener;
+ private Program program;
+
+ private ToggleDockingAction showOnlyProgramTypesAction;
+
+ public DataTypesTableProvider(DataTypeManagerPlugin plugin) {
+ this(plugin, getDtFilterState(plugin), plugin.getCurrentProgram(), true);
+ }
+
+ private DataTypesTableProvider(DataTypeManagerPlugin plugin, DtFilterState filterState,
+ Program program, boolean isConnected) {
+
+ super(plugin.getTool(), "Data Types Table", plugin.getName());
+ this.plugin = plugin;
+ this.filterState = filterState;
+ this.program = program;
+
+ if (!isConnected) {
+ setTransient();
+ }
+
+ createActions();
+
+ build();
+
+ setDefaultWindowPosition(WindowPosition.WINDOW);
+ setHelpLocation(new HelpLocation("DataTypeManagerPlugin", "Data_Types_Table"));
+
+ addToTool();
+
+ new DtTableDragProvider(table, model);
+
+ updateTitle();
+
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ archiveListener = new DtTableArchiveListener();
+ archiveManager.addArchiveManagerListener(archiveListener);
+
+ dtmListener = new DtTableDtmChangeListener();
+ plugin.addDataTypeManagerChangeListener(dtmListener);
+
+ if (!isConnected) {
+ plugin.addDisconnectedTableProvider(this);
+ }
+ }
+
+ private static DtFilterState getDtFilterState(DataTypeManagerPlugin plugin) {
+
+ PreferenceState preferenceState = getPreferenceState(plugin);
+ if (preferenceState != null) {
+ DtFilterState filterState = new DtFilterState();
+ filterState.restore(preferenceState);
+ return filterState;
+ }
+
+ // use the tree's current filter state as a default
+ return plugin.getTreeFilterState();
+ }
+
+ private static PreferenceState getPreferenceState(DataTypeManagerPlugin plugin) {
+ PluginTool tool = plugin.getTool();
+ DockingWindowManager dwm = tool.getWindowManager();
+ return dwm.getPreferenceState(FILTER_STATE_PREF_KEY);
+ }
+
+ private void saveDtFilterState() {
+ PluginTool tool = plugin.getTool();
+ DockingWindowManager dwm = tool.getWindowManager();
+ PreferenceState preferenceState = new PreferenceState();
+ filterState.save(preferenceState);
+
+ preferenceState.putBoolean(SHOW_ONLY_PROGRAM_TYPES_KEY,
+ showOnlyProgramTypesAction.isSelected());
+
+ dwm.putPreferenceState(FILTER_STATE_PREF_KEY, preferenceState);
+ }
+
+ public void programActivated(Program newProgram) {
+ if (isTransient()) {
+ throw new UnsupportedOperationException("Cannot set program on snapshot table");
+ }
+ this.program = newProgram;
+ updateTitle();
+ }
+
+ public Program getProgram() {
+ return program;
+ }
+
+ @Override
+ public void closeComponent() {
+
+ // we are transient, so cleanup when closed
+ if (isTransient()) {
+ dispose();
+ }
+ else {
+ model.clear();
+ }
+
+ super.closeComponent();
+ }
+
+ @Override
+ public void componentShown() {
+ if (!isTransient()) {
+ model.reload();
+ }
+ }
+
+ private void dispose() {
+
+ if (isTransient()) {
+ plugin.removeDisconnectedTableProvider(this);
+ }
+
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ archiveManager.removeArchiveManagerListener(archiveListener);
+ plugin.removeDataTypeManagerChangeListener(dtmListener);
+
+ // save the type filter and the table filter
+ saveDtFilterState();
+ filterPanel.dispose();
+ }
+
+ @Override
+ public JComponent getComponent() {
+ return component;
+ }
+
+ public GTable getTable() {
+ return table;
+ }
+
+ public ThreadedTableModel<DataType, Object> getTableModel() {
+ return model;
+ }
+
+ @Override
+ public ActionContext getActionContext(MouseEvent event) {
+ List<DataType> types = filterPanel.getSelectedItems();
+ return new DataTypeTableContext(this, types);
+ }
+
+ private void updateTitle() {
+ String title = getName();
+ if (isTransient()) {
+ title = "[" + title + "]";
+ setTabText(title);
+ }
+
+ setTitle(title);
+ updateSubTitle();
+ }
+
+ private void updateSubTitle() {
+ String programText = "";
+ if (program != null) {
+ programText = " - " + program.getName();
+ }
+ setSubTitle(filterPanel.getRowCount() + " types" + programText);
+ }
+
+ private void build() {
+
+ JPanel panel = new JPanel(new BorderLayout());
+
+ model = new DataTypesModel(plugin.getTool());
+ GhidraThreadedTablePanel<DataType> tablePanel =
+ new GhidraThreadedTablePanel<>(model, 250);
+ table = tablePanel.getTable();
+ table.setPreferredScrollableViewportSize(new Dimension(800, 400));
+
+ filterPanel = new GhidraTableFilterPanel<>(table, model);
+
+ String namePrefix = "Data Types";
+ table.setAccessibleNamePrefix(namePrefix);
+ filterPanel.setAccessibleNamePrefix(namePrefix);
+
+ model.addThreadedTableModelListener(new ThreadedTableModelListener() {
+
+ @Override
+ public void loadingStarted() {
+ // stub
+ }
+
+ @Override
+ public void loadingFinished(boolean wasCancelled) {
+ updateSubTitle();
+ }
+
+ @Override
+ public void loadPending() {
+ // stub
+ }
+ });
+
+ table.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ if (e.getClickCount() != 2) {
+ return;
+ }
+
+ DataType dt = filterPanel.getSelectedItem();
+ if (dt != null) {
+ plugin.edit(dt);
+ }
+ }
+ });
+
+ panel.add(tablePanel, BorderLayout.CENTER);
+ panel.add(filterPanel, BorderLayout.SOUTH);
+
+ component = new DecoratorPanel(panel, !isTransient());
+ }
+
+ private void setFilterState(DtFilterState filterState) {
+ this.filterState = filterState;
+ model.reload();
+ }
+
+ private void createActions() {
+
+ //
+ // Toolbar actions
+ //
+ addLocalAction(new DtTableFilterAction(plugin));
+
+ // Clone
+ new ActionBuilder("Data Types Table Snapshot", plugin.getName())
+ .toolBarIcon(new GIcon("icon.provider.clone"))
+ .onAction(this::clone)
+ .buildAndInstallLocal(this);
+
+ // program types filter
+ showOnlyProgramTypesAction =
+ new ToggleActionBuilder("Program Types Filter", plugin.getName())
+ .toolBarIcon(new GIcon("icon.plugin.datatypes.archive.program.closed"))
+ .toolBarGroup("filters")
+ .selected(false)
+ .onAction(c -> reload())
+ .buildAndInstallLocal(this);
+
+ PreferenceState preferenceState = getPreferenceState(plugin);
+ if (preferenceState != null) {
+ boolean onlyProgram = preferenceState.getBoolean(SHOW_ONLY_PROGRAM_TYPES_KEY, false);
+ showOnlyProgramTypesAction.setSelected(onlyProgram);
+ }
+
+ // Show in Tree / Select in Tree (select all items)
+ new ActionBuilder("Select Data Types in Tree", plugin.getName())
+ .popupMenuPath("Select in Tree")
+ .popupMenuGroup("ZVeryLast")
+ .enabledWhen(a -> table.getSelectedRowCount() > 0)
+ .onAction(a -> {
+ List<DataType> types = filterPanel.getSelectedItems();
+ plugin.setDataTypeSelected(types);
+ })
+ .buildAndInstallLocal(this);
+
+ //
+ // Popup Actions
+ //
+ // Edit group
+ addLocalAction(new EditAction(plugin));
+ addLocalAction(new CompareDataTypesAction(plugin));
+ addLocalAction(new ReplaceDataTypeAction(plugin));
+
+ // ZVeryLast group
+ addLocalAction(new FindReferencesToDataTypeAction(plugin)); // DataType
+
+ // Synchronize
+ addLocalAction(new AssociateDataTypeAction(plugin));
+ addLocalAction(new CommitSingleDataTypeAction(plugin));
+ addLocalAction(new UpdateSingleDataTypeAction(plugin));
+ addLocalAction(new RevertDataTypeAction(plugin));
+ addLocalAction(new DisassociateDataTypeAction(plugin));
+
+ }
+
+ private void clone(ActionContext context) {
+ DtFilterState newFilterState = filterState.copy();
+ DataTypesTableProvider newProvider =
+ new DataTypesTableProvider(plugin, newFilterState, program, false);
+
+ filterPanel.transferSettings(newProvider.filterPanel);
+
+ newProvider.showOnlyProgramTypesAction.setSelected(showOnlyProgramTypesAction.isSelected());
+
+ newProvider.setVisible(true);
+ }
+
+ private void reload() {
+ // Add a listener to restore the selected types after the table has been reloaded
+ List<DataType> types = filterPanel.getSelectedItems();
+ model.addInitialLoadListener(c -> {
+ List<DataType> updatedTypes = getUpdatedTypes(types);
+ filterPanel.setSelectedItems(updatedTypes);
+ table.scrollToSelectedRow();
+ });
+
+ model.reload();
+ }
+
+ /**
+ * Uses the given types to find the equivalent type after a reload operation.
+ * @param types the old types
+ * @return the equivalent new types
+ */
+ private List<DataType> getUpdatedTypes(List<DataType> types) {
+
+ List<DataType> newTypes = new ArrayList<>();
+ for (DataType dt : types) {
+ DataTypeManager dtm = dt.getDataTypeManager();
+ DataType newType = dtm.resolve(dt, DataTypeConflictHandler.KEEP_HANDLER);
+ newTypes.add(newType);
+ }
+
+ return newTypes;
+ }
+
+//=================================================================================================
+// Inner Classes
+//=================================================================================================
+
+ private class DtTableDragProvider extends GTableDragProvider<DataType> {
+
+ public DtTableDragProvider(GTable table, RowObjectTableModel<DataType> model) {
+ super(table, model);
+ }
+
+ @Override
+ protected int getDragActions() {
+ return DnDConstants.ACTION_COPY_OR_MOVE;
+ }
+
+ @Override
+ protected Transferable createDragTransferable(List<DataType> items) {
+ return new DataTypeTableTransferable(items);
+ }
+
+ private class DataTypeTableTransferable implements Transferable {
+
+ private static final DataFlavor[] FLAVORS = new DataFlavor[] {
+ DataTypeTransferable.localDataTypeFlavor,
+ DataTypeTransferable.localDataTypeListFlavor
+ };
+
+ private List<DataType> types;
+
+ DataTypeTableTransferable(List<DataType> types) {
+ this.types = types;
+ }
+
+ @Override
+ public DataFlavor[] getTransferDataFlavors() {
+ return FLAVORS;
+ }
+
+ @Override
+ public boolean isDataFlavorSupported(DataFlavor flavor) {
+ for (DataFlavor f : FLAVORS) {
+ if (f.equals(flavor)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Object getTransferData(DataFlavor flavor)
+ throws UnsupportedFlavorException, IOException {
+
+ if (flavor.equals(DataTypeTransferable.localDataTypeFlavor)) {
+ return types.get(0);
+ }
+ else if (flavor.equals(DataTypeTransferable.localDataTypeListFlavor)) {
+ return Collections.unmodifiableList(types);
+ }
+
+ throw new UnsupportedFlavorException(flavor);
+ }
+ }
+ }
+
+ private class DtTableFilterAction extends DockingAction {
+
+ public DtTableFilterAction(DataTypeManagerPlugin plugin) {
+ super("Show Filter", plugin.getName());
+ setToolBarData(new ToolBarData(Icons.CONFIGURE_FILTER_ICON, "filters"));
+ setDescription("Shows the Data Types filter");
+ }
+
+ @Override
+ public boolean isEnabledForContext(ActionContext context) {
+ ComponentProvider provider = context.getComponentProvider();
+ return provider == DataTypesTableProvider.this;
+ }
+
+ @Override
+ public void actionPerformed(ActionContext context) {
+ DtFilterState currentFilterState = filterState;
+ DtFilterDialog dialog = new DtFilterDialog(currentFilterState);
+ plugin.getTool().showDialog(dialog, getComponent());
+
+ if (dialog.isCancelled()) {
+ return;
+ }
+
+ DtFilterState newFilterState = dialog.getFilterState();
+ if (currentFilterState.equals(newFilterState)) {
+ return;
+ }
+
+ setFilterState(newFilterState);
+ }
+
+ }
+
+ private class DtTableArchiveListener implements ArchiveManagerListener {
+
+ @Override
+ public void archiveOpened(PersistentDataTypeArchive archive) {
+ reload();
+ }
+
+ @Override
+ public void archiveClosed(PersistentDataTypeArchive archive) {
+ reload();
+ }
+
+ @Override
+ public void programOpened(Program p) {
+ reload();
+ }
+
+ @Override
+ public void programClosed(Program p) {
+ reload();
+ }
+
+ @Override
+ public void invalidArchiveAdded(InvalidArchive invalidArchive) {
+ // stub
+ }
+
+ @Override
+ public void invalidArchiveRemoved(InvalidArchive invalidArchive) {
+ // stub
+ }
+
+ @Override
+ public void stateChanged(DataTypeStore dataTypeStore) {
+ table.repaint();
+ }
+ }
+
+ private class DtTableDtmChangeListener implements DataTypeManagerChangeListener {
+ @Override
+ public void sourceArchiveChanged(DataTypeManager dataTypeManager,
+ SourceArchive sourceArchive) {
+ table.repaint();
+ }
+
+ @Override
+ public void sourceArchiveAdded(DataTypeManager dataTypeManager,
+ SourceArchive sourceArchive) {
+ reload();
+ }
+
+ @Override
+ public void restored(DataTypeManager dataTypeManager) {
+ reload();
+ }
+
+ @Override
+ public void programArchitectureChanged(DataTypeManager dataTypeManager) {
+ // stub
+ }
+
+ @Override
+ public void favoritesChanged(DataTypeManager dtm, DataTypePath path,
+ boolean isFavorite) {
+ // stub
+ }
+
+ @Override
+ public void dataTypeReplaced(DataTypeManager dtm, DataTypePath oldPath,
+ DataTypePath newPath, DataType newDataType) {
+ table.repaint();
+ }
+
+ @Override
+ public void dataTypeRenamed(DataTypeManager dtm, DataTypePath oldPath,
+ DataTypePath newPath) {
+ table.repaint();
+ }
+
+ @Override
+ public void dataTypeRemoved(DataTypeManager dtm, DataTypePath path) {
+ DataType dt = dtm.getDataType(path);
+ model.removeObject(dt);
+ }
+
+ @Override
+ public void dataTypeMoved(DataTypeManager dtm, DataTypePath oldPath,
+ DataTypePath newPath) {
+ table.repaint();
+ }
+
+ @Override
+ public void dataTypeChanged(DataTypeManager dtm, DataTypePath path) {
+ table.repaint();
+ }
+
+ @Override
+ public void dataTypeAdded(DataTypeManager dtm, DataTypePath path) {
+ DataType dt = dtm.getDataType(path);
+ model.addObject(dt);
+ }
+
+ @Override
+ public void categoryRenamed(DataTypeManager dtm, CategoryPath oldPath,
+ CategoryPath newPath) {
+ // stub
+ }
+
+ @Override
+ public void categoryRemoved(DataTypeManager dtm, CategoryPath path) {
+ // stub
+ }
+
+ @Override
+ public void categoryMoved(DataTypeManager dtm, CategoryPath oldPath,
+ CategoryPath newPath) {
+ table.repaint();
+ }
+
+ @Override
+ public void categoryAdded(DataTypeManager dtm, CategoryPath path) {
+ // stub
+ }
+ }
+
+ private class DataTypesModel extends ThreadedTableModel<DataType, Object> {
+
+ protected DataTypesModel(ServiceProvider serviceProvider) {
+ super("Data Types", serviceProvider);
+ }
+
+ public void clear() {
+ // this will work if this provider is not visible when doLoad() is called
+ model.reload();
+ }
+
+ @Override
+ public void addObject(DataType dt) {
+ if (filterState.passesFilters(dt)) {
+ super.addObject(dt);
+ }
+ }
+
+ @Override
+ protected void doLoad(Accumulator<DataType> accumulator, TaskMonitor monitor)
+ throws CancelledException {
+
+ if (!isVisible()) {
+ return;
+ }
+
+ if (program == null) {
+ return; // the tool is initializing
+ }
+
+ ProgramBasedDataTypeManager programDtm = program.getDataTypeManager();
+ loadTypes(programDtm, accumulator, monitor);
+
+ if (showOnlyProgramTypesAction.isSelected()) {
+ return;
+ }
+
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ List<PersistentDataTypeArchive> archives = archiveManager.getOpenArchives();
+ for (PersistentDataTypeArchive archive : archives) {
+ DataTypeManager dtm = archive.getDataTypeManager();
+ if (dtm instanceof ProgramBasedDataTypeManager) {
+ continue;
+ }
+
+ loadTypes(dtm, accumulator, monitor);
+ }
+ }
+
+ private void loadTypes(DataTypeManager dtm, Accumulator<DataType> accumulator,
+ TaskMonitor monitor) throws CancelledException {
+
+ Iterator<DataType> it = dtm.getAllDataTypes();
+ while (it.hasNext()) {
+ monitor.checkCancelled();
+
+ DataType dt = it.next();
+ if (filterState.passesFilters(dt)) {
+ accumulator.add(dt);
+ }
+ }
+ }
+
+ @Override
+ protected TableColumnDescriptor<DataType> createTableColumnDescriptor() {
+
+ TableColumnDescriptor<DataType> descriptor = new TableColumnDescriptor<>();
+
+ descriptor.addVisibleColumn(new TypeColumn());
+ descriptor.addVisibleColumn(new NameColumn());
+ descriptor.addVisibleColumn(new LengthColumn());
+ descriptor.addVisibleColumn(new CategoryPathColumn());
+ descriptor.addVisibleColumn(new ArchiveColumn());
+ descriptor.addVisibleColumn(new SyncColumn());
+
+ descriptor.addHiddenColumn(new LastChangedColumn());
+ descriptor.addHiddenColumn(new CommentColumn());
+ descriptor.addHiddenColumn(new PackingColumn());
+ descriptor.addHiddenColumn(new AlignmentColumn());
+ descriptor.addHiddenColumn(new AlignmentLengthColumn());
+ descriptor.addHiddenColumn(new SourceColumn());
+
+ return descriptor;
+ }
+
+ @Override
+ public Program getDataSource() {
+ return null;
+ }
+
+ private class NameColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, String> {
+
+ @Override
+ public String getColumnName() {
+ return "Name";
+ }
+
+ @Override
+ public String getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ return rowObject.getName();
+ }
+ }
+
+ private class LengthColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, Integer> {
+
+ @Override
+ public String getColumnName() {
+ return "Length";
+ }
+
+ @Override
+ public int getColumnPreferredWidth() {
+ return 40;
+ }
+
+ @Override
+ public Integer getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ int len = rowObject.getLength();
+ if (len < 0) {
+ return null;
+ }
+ return len;
+ }
+ }
+
+ private class CategoryPathColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, String> {
+
+ @Override
+ public String getColumnName() {
+ return "Path";
+ }
+
+ @Override
+ public String getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ return rowObject.getCategoryPath().toString();
+ }
+ }
+
+ private class LastChangedColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, Date> {
+
+ private DateRenderer renderer = new DateRenderer();
+
+ @Override
+ public String getColumnName() {
+ return "Modified";
+ }
+
+ @Override
+ public Date getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ long time = rowObject.getLastChangeTime();
+ if (time == 0) {
+ return null;
+ }
+ return new Date(time);
+ }
+
+ @Override
+ public GColumnRenderer<Date> getColumnRenderer() {
+ return renderer;
+ }
+
+ private class DateRenderer extends AbstractGColumnRenderer<Date> {
+ @Override
+ public Component getTableCellRendererComponent(GTableCellRenderingData data) {
+
+ JLabel label = (JLabel) super.getTableCellRendererComponent(data);
+ Date date = (Date) data.getValue();
+ if (date == null) {
+ return label;
+ }
+
+ String formatted = DateUtils.formatDate(date);
+ label.setText(formatted);
+ return label;
+ }
+
+ @Override
+ public ColumnConstraintFilterMode getColumnConstraintFilterMode() {
+ // not sure about this: it could be USE_COLUMN_CONSTRAINTS_ONLY, but then the text
+ // filter would not match the formatted date. This allows for both.
+ return ColumnConstraintFilterMode.ALLOW_ALL_FILTERS;
+ }
+
+ @Override
+ public String getFilterString(Date t, Settings settings) {
+ String formatted = DateUtils.formatDate(t);
+ return formatted;
+ }
+ }
+ }
+
+ private class SourceColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, String> {
+
+ @Override
+ public String getColumnName() {
+ return "Source";
+ }
+
+ @Override
+ public String getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ SourceArchive source = rowObject.getSourceArchive();
+ if (source != null) {
+ return source.getName();
+ }
+ return null;
+ }
+
+ }
+
+ private class TypeColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, MyIconWrapper> {
+
+ // use a renderer to get filtering by icon text (e.g., Function, Structure, etc)
+ private IconRenderer renderer = new IconRenderer();
+
+ @Override
+ public String getColumnName() {
+ return "Icon";
+ }
+
+ @Override
+ public int getColumnPreferredWidth() {
+ return 30;
+ }
+
+ @Override
+ public MyIconWrapper getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+
+ Icon icon = DataTypeUtils.getIconForDataType(rowObject, false);
+ String description = DataTypeUtils.getIconTextForDataType(rowObject);
+
+ if (description == null) {
+ // Assume a primitive type; not sure of the best text for this. This text
+ // allows the user to filter on this column.
+ description = "Built-in";
+ }
+
+ return new MyIconWrapper(icon, description);
+ }
+
+ @Override
+ public GColumnRenderer<MyIconWrapper> getColumnRenderer() {
+ return renderer;
+ }
+
+ private class IconRenderer extends AbstractGColumnRenderer<MyIconWrapper> {
+
+ @Override
+ public Component getTableCellRendererComponent(GTableCellRenderingData data) {
+
+ MyIconWrapper iconWrapper = (MyIconWrapper) data.getValue();
+ Icon icon = iconWrapper.icon();
+
+ JLabel label = (JLabel) super.getTableCellRendererComponent(data);
+ label.setText("");
+ label.setIcon(icon);
+ label.setToolTipText(iconWrapper.desription());
+ return label;
+ }
+
+ @Override
+ protected String getAccessibleCellValue(GTableCellRenderingData data, String text) {
+ MyIconWrapper iconWrapper = (MyIconWrapper) data.getValue();
+ return iconWrapper.desription();
+ }
+
+ @Override
+ public String getFilterString(MyIconWrapper t, Settings settings) {
+ return t.desription();
+ }
+
+ }
+ }
+
+ private record MyIconWrapper(Icon icon, String desription) {}
+
+ private class ArchiveColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, String> {
+
+ @Override
+ public String getColumnName() {
+ return "Archive";
+ }
+
+ @Override
+ public String getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ return rowObject.getDataTypeManager().getName();
+ }
+ }
+
+ private class CommentColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, String> {
+
+ @Override
+ public String getColumnName() {
+ return "Comment";
+ }
+
+ @Override
+ public String getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+
+ if (rowObject instanceof Structure s) {
+ return s.getDescription();
+ }
+ else if (rowObject instanceof FunctionDefinition fd) {
+ return fd.getComment();
+ }
+ else if (rowObject instanceof Enum e) {
+ return e.getDescription();
+ }
+
+ return null;
+ }
+ }
+
+ private class PackingColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, Integer> {
+
+ @Override
+ public String getColumnName() {
+ return "Packing";
+ }
+
+ @Override
+ public Integer getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ if (rowObject instanceof Composite c) {
+ if (c.hasExplicitPackingValue()) {
+ return c.getExplicitPackingValue();
+ }
+ }
+ return null;
+ }
+ }
+
+ private class AlignmentColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, Integer> {
+
+ @Override
+ public String getColumnName() {
+ return "Alignment";
+ }
+
+ @Override
+ public Integer getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ if (rowObject instanceof Composite c) {
+ return c.getAlignment();
+ }
+ return null;
+ }
+ }
+
+ private class AlignmentLengthColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, Integer> {
+
+ @Override
+ public String getColumnName() {
+ return "Aligned Length";
+ }
+
+ @Override
+ public Integer getValue(DataType rowObject, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+ int len = rowObject.getAlignedLength();
+ if (len < 0) {
+ return null;
+ }
+ return len;
+ }
+
+ }
+
+ private class SyncColumn
+ extends AbstractProgramBasedDynamicTableColumn<DataType, DataTypeSyncState> {
+
+ // Note: these also live in the DataTypeArchiveGTree
+ private static Icon LOCAL_DELTA_ICON =
+ new GIcon("icon.plugin.datatypes.tree.change.local");
+ private static Icon SOURCE_DELTA_ICON =
+ new GIcon("icon.plugin.datatypes.tree.change.source");
+ private static Icon CONFLICT_ICON = new GIcon("icon.plugin.datatypes.tree.conflict");
+ private static Icon MISSING_ICON = new GIcon("icon.plugin.datatypes.tree.missing");
+
+ private SyncRenderer renderer = new SyncRenderer();
+
+ @Override
+ public String getColumnName() {
+ return "Sync";
+ }
+
+ @Override
+ public String getColumnDescription() {
+ return "The sync status for 'associated' types";
+ }
+
+ @Override
+ public int getColumnPreferredWidth() {
+ return 30;
+ }
+
+ @Override
+ public GColumnRenderer<DataTypeSyncState> getColumnRenderer() {
+ return renderer;
+ }
+
+ @Override
+ public DataTypeSyncState getValue(DataType dt, Settings settings, Program data,
+ ServiceProvider sp) throws IllegalArgumentException {
+
+ SourceArchive sourceArchive = dt.getSourceArchive();
+ if (!hasOtherSourceArchive(dt, sourceArchive)) {
+ return null;
+ }
+
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ DataTypeSyncState status = DataTypeSynchronizer.getSyncStatus(archiveManager, dt);
+ return status;
+ }
+
+ private boolean hasOtherSourceArchive(DataType dataType, SourceArchive sourceArchive) {
+ if (sourceArchive == null) {
+ return false;
+ }
+
+ if (sourceArchive.getArchiveType().isBuiltIn()) {
+ return false;
+ }
+
+ UniversalID localID = dataType.getDataTypeManager().getUniversalID();
+ return !sourceArchive.getSourceArchiveID().equals(localID);
+ }
+
+ private class SyncRenderer extends AbstractGColumnRenderer<DataTypeSyncState> {
+
+ @Override
+ public Component getTableCellRendererComponent(GTableCellRenderingData data) {
+
+ JLabel label = (JLabel) super.getTableCellRendererComponent(data);
+ label.setText("");
+ label.setHorizontalAlignment(SwingConstants.CENTER);
+
+ Object value = data.getValue();
+ DataTypeSyncState status = (DataTypeSyncState) value;
+ StatusDecoration decoration = getStatusDecoration(status);
+ if (decoration != null) {
+ label.setIcon(decoration.icon());
+ label.setToolTipText(decoration.description());
+ }
+ else {
+ label.setIcon(null);
+ label.setToolTipText(null);
+ }
+
+ return label;
+ }
+
+ private StatusDecoration getStatusDecoration(DataTypeSyncState state) {
+ if (state == null) {
+ return null;
+ }
+ switch (state) {
+ case CONFLICT:
+ return new StatusDecoration(CONFLICT_ICON,
+ "Type conflicts with source archive");
+ case UPDATE:
+ return new StatusDecoration(SOURCE_DELTA_ICON,
+ "Type updated in source archive");
+ case COMMIT:
+ return new StatusDecoration(LOCAL_DELTA_ICON,
+ "Changes to be commited to source archive");
+ case ORPHAN:
+ return new StatusDecoration(MISSING_ICON,
+ "Orphaned from source archive");
+ case UNKNOWN:
+ case IN_SYNC:
+ default:
+ return null;
+ }
+ }
+
+ @Override
+ public String getFilterString(DataTypeSyncState t, Settings settings) {
+ return t.toString();
+ }
+
+ private record StatusDecoration(Icon icon, String description) {}
+ }
+ }
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DtFilterState.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DtFilterState.java
index 9d627c9273..dcaa3e38bb 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DtFilterState.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/tree/DtFilterState.java
@@ -157,7 +157,7 @@ public class DtFilterState {
// built-in base "pointer" data type ("pointer" does not have a target type).
// Returning 'true' here allows this data type to bypass the filter just like
// builtin int/float types will at the bottom of this method.
- return true;
+ return passes(otherFilter, dt);
}
return passes(pointersFilter, dt);
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataDropOnBrowserHandler.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataDropOnBrowserHandler.java
index 2fb377a75d..74e19829f9 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataDropOnBrowserHandler.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataDropOnBrowserHandler.java
@@ -26,14 +26,13 @@ import ghidra.program.model.data.DataType;
import ghidra.program.model.data.DataTypeTransferable;
/**
- * Handles datatype drops in the codebrowser. Installed by the dataTypeManagerPlugin
- *
+ * Handles datatype drops in the Listing. Installed by the DataTypeManagerPlugin.
*/
-public class DataDropOnBrowserHandler implements ProgramDropProvider {
-
+public class DataDropOnBrowserHandler implements ProgramDropProvider {
+
private static final DataFlavor[] ACCEPTABLE_FLAVORS = new DataFlavor[] {
- DataTypeTransferable.localDataTypeFlavor,
- DataTypeTransferable.localBuiltinDataTypeFlavor
+ DataTypeTransferable.localDataTypeFlavor,
+ DataTypeTransferable.localBuiltinDataTypeFlavor
};
private DataService curService;
private final DataTypeManagerPlugin plugin;
@@ -41,48 +40,46 @@ public class DataDropOnBrowserHandler implements ProgramDropProvider {
public DataDropOnBrowserHandler(DataTypeManagerPlugin plugin) {
this.plugin = plugin;
}
-
+
@Override
public int getPriority() {
return 20;
}
-
+
@Override
public DataFlavor[] getDataFlavors() {
return ACCEPTABLE_FLAVORS;
}
- /**
- * @see ghidra.app.util.ProgramDropProvider#isDropOk(java.lang.Object, java.awt.dnd.DropTargetDragEvent)
- */
@Override
public boolean isDropOk(Object contextObj, DropTargetDragEvent evt) {
curService = null;
if (!evt.isDataFlavorSupported(DataTypeTransferable.localDataTypeFlavor) &&
- !evt.isDataFlavorSupported(DataTypeTransferable.localBuiltinDataTypeFlavor) )
+ !evt.isDataFlavorSupported(DataTypeTransferable.localBuiltinDataTypeFlavor)) {
return false;
+ }
- if (contextObj != null && contextObj instanceof ListingActionContext) {
- ListingActionContext pl = (ListingActionContext)contextObj;
- DataService[] services = plugin.getTool().getServices(DataService.class);
- for (int i=0; i<services.length; i++) {
+ if (contextObj != null && contextObj instanceof ListingActionContext) {
+ ListingActionContext pl = (ListingActionContext) contextObj;
+ DataService[] services = plugin.getTool().getServices(DataService.class);
+ for (int i = 0; i < services.length; i++) {
if (services[i].isCreateDataAllowed(pl)) {
curService = services[i];
return true;
}
}
}
-
+
return false;
}
@Override
public void add(Object contextObj, Object data, DataFlavor flavor) {
if (curService != null) {
- DataType dt = (DataType)data;
+ DataType dt = (DataType) data;
curService.createData(dt, (ListingActionContext) contextObj, true, true);
}
}
-
+
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java
index 8a02d5b13b..9f0d87e313 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeUtils.java
@@ -257,6 +257,22 @@ public class DataTypeUtils {
return defaultIcon;
}
+ /**
+ * {@return descriptive text for the given data type's icon}
+ * @param dataType the data type
+ */
+ public static String getIconTextForDataType(DataType dataType) {
+ loadImages();
+
+ for (DataTypeIconWrapper element : dataTypeIconWrappers) {
+ Icon icon = element.getIcon(dataType, false);
+ if (icon != null) {
+ return element.getDescription(dataType);
+ }
+ }
+ return null;
+ }
+
/**
* Returns an icon that adds highlighting to the provided icon.
*
@@ -532,6 +548,10 @@ class DataTypeIconWrapper {
this.disabledIcon = disabledIcon;
}
+ public String getDescription(DataType dataType) {
+ return dataTypeClass.getSimpleName();
+ }
+
Icon getIcon(DataType dataType, boolean disabled) {
if (dataTypeClass.isInstance(dataType)) {
if (disabled) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeTreeCopyMoveTask.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypesCopyMoveTask.java
similarity index 59%
rename from Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeTreeCopyMoveTask.java
rename to Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypesCopyMoveTask.java
index 8c95a3b93f..2a02686f0a 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypeTreeCopyMoveTask.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/datamgr/util/DataTypesCopyMoveTask.java
@@ -18,11 +18,13 @@ package ghidra.app.plugin.core.datamgr.util;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import docking.widgets.OptionDialog;
-import docking.widgets.tree.GTreeNode;
-import docking.widgets.tree.GTreeState;
-import ghidra.app.plugin.core.datamgr.tree.*;
+import docking.widgets.tree.*;
+import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
+import ghidra.app.plugin.core.datamgr.tree.CategoryNode;
+import ghidra.app.plugin.core.datamgr.tree.DataTypeNode;
import ghidra.program.model.data.*;
import ghidra.program.model.dtarchive.DataTypeStore;
import ghidra.program.model.listing.Program;
@@ -33,9 +35,10 @@ import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;
/**
- * Task for copying and moving data type nodes within the Data Types tree.
+ * Task for copying or moving data types and categories between archives in a Data Type Manager
+ * tree.
*/
-public class DataTypeTreeCopyMoveTask extends Task {
+public class DataTypesCopyMoveTask extends Task {
// If the total number of nodes is small, we won't need to collapse the tree before deleting
// the nodes to avoid excess tree events. This number is very arbitrary. This number is
@@ -48,51 +51,88 @@ public class DataTypeTreeCopyMoveTask extends Task {
COPY, MOVE
}
- private DataTypeArchiveGTree gTree;
+ private GTree tree;
+ private DataTypeStore sourceStore;
+ private DataTypeStore destinationStore;
private Category destinationCategory;
- private List<GTreeNode> copyMoveNodes;
- private DataTypeStore sourceDataTypeStore;
- private DataTypeStore destinationDataTypeStore;
- private boolean promptToAssociateTypes = true;
- private ActionType actionType;
+ private List<DataType> types;
+ private List<Category> categories;
+ private int count;
private DataTypeConflictHandler conflictHandler;
+
+ private ActionType actionType;
+ private boolean promptToAssociateTypes = true;
+
private List<String> errors = new ArrayList<>();
- // for testing
- DataTypeTreeCopyMoveTask() {
- super("Drag/Drop", true, true, true);
+ /**
+ * Constructor method for creating a task from category and data type nodes. This is used when
+ * using drag-n-drop.
+ *
+ * @param plugin the plugin
+ * @param tree the primary provider's tree or a snapshot
+ * @param destination the destination category
+ * @param nodes the nodes being dropped
+ * @param actionType the action type
+ * @return the new task
+ */
+ public static DataTypesCopyMoveTask forNodes(DataTypeManagerPlugin plugin, GTree tree,
+ Category destination, List<GTreeNode> nodes, ActionType actionType) {
+
+ List<Category> categories = new ArrayList<>();
+ List<DataType> types = new ArrayList<>();
+ convertNodes(nodes, categories, types);
+
+ DataTypesCopyMoveTask task =
+ new DataTypesCopyMoveTask(plugin, destination, types, categories, actionType);
+ task.tree = tree;
+ return task;
}
- public DataTypeTreeCopyMoveTask(CategoryNode destinationNode, List<GTreeNode> droppedNodeList,
- ActionType actionType, DataTypeArchiveGTree gTree,
- DataTypeConflictHandler conflictHandler) {
- this(findDataStore(destinationNode), destinationNode.getCategory(), droppedNodeList,
- actionType, gTree, conflictHandler);
+ private static void convertNodes(List<GTreeNode> nodes, List<Category> categories,
+ List<DataType> types) {
+
+ for (GTreeNode node : nodes) {
+ if (node instanceof CategoryNode catNode) {
+ categories.add(catNode.getCategory());
+ }
+ else if (node instanceof DataTypeNode dtNode) {
+ types.add(dtNode.getDataType());
+ }
+ }
}
- public DataTypeTreeCopyMoveTask(DataTypeStore destination, Category destinationCategory,
- List<GTreeNode> droppedNodeList, ActionType actionType, DataTypeArchiveGTree gTree,
- DataTypeConflictHandler conflictHandler) {
- super("Drag/Drop", true, true, true);
+ private DataTypesCopyMoveTask(DataTypeManagerPlugin plugin, Category destinationCategory,
+ List<DataType> types, List<Category> categories, ActionType actionType) {
+
+ super("Drag/Drop Data Types", true, true, true);
this.destinationCategory = destinationCategory;
- this.copyMoveNodes = droppedNodeList;
+ this.types = types == null ? List.of() : types;
+ this.categories = categories == null ? List.of() : categories;
this.actionType = actionType;
- this.gTree = gTree;
- this.conflictHandler = conflictHandler;
- this.destinationDataTypeStore = destination;
+ this.tree = plugin.getProvider().getGTree();
+ this.conflictHandler = plugin.getConflictHandler();
- GTreeNode firstNode = copyMoveNodes.get(0);
- this.sourceDataTypeStore = findDataStore(firstNode);
+ DataTypeManager destDtm = destinationCategory.getDataTypeManager();
+ this.destinationStore = destDtm.getDataStore();
+
+ this.count = types.size() + categories.size();
}
- private static DataTypeStore findDataStore(GTreeNode node) {
- while (node != null) {
- if (node instanceof DataTypeStoreNode archiveNode) {
- return archiveNode.getDataTypeStore();
- }
- node = node.getParent();
- }
- return null;
+ public DataTypesCopyMoveTask(DataTypeManagerPlugin plugin, DataTypeStore destinationArchive,
+ Category destinationCategory, List<DataType> types, List<Category> categories,
+ ActionType actionType) {
+
+ super("Drag/Drop Data Types", true, true, true);
+ this.destinationCategory = destinationCategory;
+ this.types = types == null ? List.of() : types;
+ this.categories = categories == null ? List.of() : categories;
+ this.actionType = actionType;
+ this.tree = plugin.getProvider().getGTree();
+ this.conflictHandler = plugin.getConflictHandler();
+ this.destinationStore = destinationArchive;
+
+ this.count = this.types.size() + this.categories.size();
}
/**
@@ -110,12 +150,7 @@ public class DataTypeTreeCopyMoveTask extends Task {
@Override
public void run(TaskMonitor monitor) throws CancelledException {
- int nodeCount = copyMoveNodes.size();
- filterRedundantNodes();
-
- if (checkForDifferentSourceArchives()) {
- return;
- }
+ filterRedundantTypes();
//
// Note: we collapse the node before performing this work because there is a
@@ -125,9 +160,12 @@ public class DataTypeTreeCopyMoveTask extends Task {
// the tree is not invalidating/validating its cache as a result of these
// events.
//
- GTreeState treeState = gTree.getTreeState();
+ GTreeState treeState = tree.getTreeState();
try {
- if (nodeCount > NODE_COUNT_FOR_COLLAPSING_TREE) {
+
+ sourceStore = getSourceStore(monitor);
+
+ if (count > NODE_COUNT_FOR_COLLAPSING_TREE) {
collapseArchives();
}
@@ -150,12 +188,51 @@ public class DataTypeTreeCopyMoveTask extends Task {
return; // nothing to report
}
finally {
- gTree.restoreTreeState(treeState);
+ tree.restoreTreeState(treeState);
}
reportErrors();
}
+ private DataTypeStore getSourceStore(TaskMonitor monitor) throws CancelledException {
+
+ DataTypeStore firstStore = null;
+
+ for (Category category : categories) {
+ monitor.checkCancelled();
+ DataTypeManager dtm = category.getDataTypeManager();
+ DataTypeStore archive = dtm.getDataStore();
+ if (firstStore == null) {
+ firstStore = archive;
+ continue;
+ }
+
+ if (firstStore != archive) {
+ Msg.showError(this, tree, "Copy Failed",
+ "All data types must be from the same archive!");
+ throw new CancelledException();
+ }
+ }
+
+ for (DataType dt : types) {
+ monitor.checkCancelled();
+ DataTypeManager dtm = dt.getDataTypeManager();
+ DataTypeStore archive = dtm.getDataStore();
+ if (firstStore == null) {
+ firstStore = archive;
+ continue;
+ }
+
+ if (firstStore != archive) {
+ Msg.showError(this, tree, "Copy Failed",
+ "All data types must be from the same archive!");
+ throw new CancelledException();
+ }
+ }
+
+ return firstStore;
+ }
+
private void reportErrors() {
if (errors.isEmpty()) {
return;
@@ -172,46 +249,29 @@ public class DataTypeTreeCopyMoveTask extends Task {
}
}
- Msg.showError(this, gTree, "Encountered Errors Copying/Moving", message);
+ Msg.showError(this, tree, "Encountered Errors Copying/Moving", message);
}
- private boolean checkForDifferentSourceArchives() {
-
- for (GTreeNode node : copyMoveNodes) {
- if (sourceDataTypeStore != findDataStore(node)) {
- Msg.showError(this, gTree, "Copy Failed",
- "All data types must be from the same archive!");
- return true;
- }
- }
-
- return false;
- }
-
- private void doCopy(TaskMonitor monitor) {
- DataTypeManager dtm = destinationDataTypeStore.getDataTypeManager();
- int txId = dtm.startTransaction("Copy/Move Category/DataType");
- try {
+ private void doCopy(TaskMonitor monitor) throws CancelledException {
+ DataTypeManager dtm = destinationStore.getDataTypeManager();
+ dtm.withTransaction("Copy/Move Category/DataType", () -> {
copyOrMoveNodesToCategory(monitor);
- }
- finally {
- dtm.endTransaction(txId, true);
- }
+ });
}
private boolean needToCreateAssociation() {
// copying from the program archive into another archive
- return sourceDataTypeStore != destinationDataTypeStore &&
- !(destinationDataTypeStore instanceof Program) &&
- (sourceDataTypeStore instanceof Program);
+ return sourceStore != destinationStore &&
+ !(destinationStore instanceof Program) &&
+ (sourceStore instanceof Program);
}
private void collapseArchives() {
- GTreeNode root = gTree.getModelRoot();
+ GTreeNode root = tree.getModelRoot();
List<GTreeNode> children = root.getChildren();
for (GTreeNode archive : children) {
- gTree.collapseAll(archive);
+ tree.collapseAll(archive);
}
}
@@ -221,31 +281,23 @@ public class DataTypeTreeCopyMoveTask extends Task {
return;
}
- monitor.initialize(copyMoveNodes.size());
+ monitor.initialize(count);
- SourceArchive destination =
- destinationDataTypeStore.getDataTypeManager().getLocalSourceArchive();
- DataTypeManager dtm = sourceDataTypeStore.getDataTypeManager();
- int txId = dtm.startTransaction("Associate Data Types");
- try {
- for (GTreeNode node : copyMoveNodes) {
- monitor.checkCancelled();
-
- if (node instanceof DataTypeNode) {
- DataType dt = ((DataTypeNode) node).getDataType();
- associateDataType(dt, dtm, destination);
- }
- else if (node instanceof CategoryNode) {
- Category cat = ((CategoryNode) node).getCategory();
- associateDataTypes(cat, dtm, destination);
- }
-
- monitor.incrementProgress(1);
+ DataTypeManager destionationDtm = destinationStore.getDataTypeManager();
+ SourceArchive destination = destionationDtm.getLocalSourceArchive();
+ DataTypeManager sourceDtm = sourceStore.getDataTypeManager();
+ sourceDtm.withTransaction("Associate Data Types", () -> {
+
+ for (Category cat : categories) {
+ associateDataTypes(cat, sourceDtm, destination);
+ monitor.increment();
}
- }
- finally {
- dtm.endTransaction(txId, true);
- }
+
+ for (DataType dt : types) {
+ associateDataType(dt, sourceDtm, destination);
+ monitor.increment();
+ }
+ });
}
private boolean promptToAssociateTypes(TaskMonitor monitor) throws CancelledException {
@@ -269,23 +321,20 @@ public class DataTypeTreeCopyMoveTask extends Task {
private boolean containsUnassociatedTypes(TaskMonitor monitor) throws CancelledException {
monitor.setMessage("Checking for types to associate");
- monitor.initialize(copyMoveNodes.size());
- for (GTreeNode node : copyMoveNodes) {
- monitor.checkCancelled();
+ monitor.initialize(count);
- if (node instanceof DataTypeNode) {
- DataType dt = ((DataTypeNode) node).getDataType();
- if (isLocal(dt)) {
- return true; // local means it is not associated
- }
- }
- else if (node instanceof CategoryNode) {
- if (containsUnassociatedTypes(((CategoryNode) node).getCategory(), monitor)) {
- return true;
- }
+ for (Category cat : categories) {
+ if (containsUnassociatedTypes(cat, monitor)) {
+ return true;
}
+ monitor.increment();
+ }
- monitor.incrementProgress(1);
+ for (DataType dt : types) {
+ if (isLocal(dt)) {
+ return true;
+ }
+ monitor.increment();
}
return false;
@@ -294,16 +343,16 @@ public class DataTypeTreeCopyMoveTask extends Task {
private boolean containsUnassociatedTypes(Category cat, TaskMonitor monitor)
throws CancelledException {
- DataType[] types = cat.getDataTypes();
- for (DataType dt : types) {
+ DataType[] catTypes = cat.getDataTypes();
+ for (DataType dt : catTypes) {
monitor.checkCancelled();
if (isLocal(dt)) {
return true; // local means it is not associated
}
}
- Category[] categories = cat.getCategories();
- for (Category child : categories) {
+ Category[] subCats = cat.getCategories();
+ for (Category child : subCats) {
monitor.checkCancelled();
if (containsUnassociatedTypes(child, monitor)) {
return true;
@@ -329,45 +378,45 @@ public class DataTypeTreeCopyMoveTask extends Task {
associateDataType(dataType, dtm, destination);
}
- Category[] categories = cat.getCategories();
- for (Category category : categories) {
+ Category[] subCats = cat.getCategories();
+ for (Category category : subCats) {
associateDataTypes(category, dtm, destination);
}
}
- private void copyOrMoveNodesToCategory(TaskMonitor monitor) {
+ private void copyOrMoveNodesToCategory(TaskMonitor monitor) throws CancelledException {
monitor.setMessage("Drag/Drop Categories/Data Types");
- monitor.initialize(copyMoveNodes.size());
+ monitor.initialize(count);
Category toCategory = destinationCategory;
- for (GTreeNode node : copyMoveNodes) {
- if (monitor.isCancelled()) {
- break;
- }
- monitor.setMessage("Adding " + node.getName());
+ for (Category cat : categories) {
+ monitor.setMessage("Adding " + cat.getName());
// COPY is only allowed action if the source and destination archives are different.
- if (actionType == ActionType.COPY || sourceDataTypeStore != destinationDataTypeStore) {
- copyNode(toCategory, node, monitor);
+ if (actionType == ActionType.COPY || sourceStore != destinationStore) {
+ copyCategory(toCategory, cat, monitor);
}
else {
- moveNode(toCategory, node, monitor);
+ moveCategory(toCategory, cat, monitor);
}
- monitor.incrementProgress(1);
+ monitor.increment();
}
- }
- private void copyNode(Category toCategory, GTreeNode node, TaskMonitor monitor) {
- if (node instanceof DataTypeNode) {
- DataType nodeDt = ((DataTypeNode) node).getDataType();
- copyDataType(toCategory, nodeDt);
- }
- else if (node instanceof CategoryNode) {
- Category category = ((CategoryNode) node).getCategory();
- copyCategory(toCategory, category, monitor);
+ for (DataType dt : types) {
+ monitor.setMessage("Adding " + dt.getName());
+
+ // COPY is only allowed action if the source and destination archives are different.
+ if (actionType == ActionType.COPY || sourceStore != destinationStore) {
+ copyDataType(toCategory, dt);
+ }
+ else {
+ moveDataType(toCategory, dt);
+ }
+
+ monitor.increment();
}
}
@@ -412,7 +461,7 @@ public class DataTypeTreeCopyMoveTask extends Task {
}
}
- String getBaseName(String dtName) {
+ static String getBaseName(String dtName) {
// format: Copy_of_foobar
// Copy_2_of_foobar
@@ -426,7 +475,7 @@ public class DataTypeTreeCopyMoveTask extends Task {
return baseName;
}
- String getNextCopyName(Category toCategory, String baseName) {
+ static String getNextCopyName(Category toCategory, String baseName) {
String format = "Copy_%d_of_" + baseName;
for (int i = 1; i < 100; i++) {
@@ -440,20 +489,8 @@ public class DataTypeTreeCopyMoveTask extends Task {
return String.format(format, System.currentTimeMillis());
}
- private void moveNode(Category toCategory, GTreeNode node, TaskMonitor monitor) {
- if (node instanceof DataTypeNode) {
- DataType dataType = ((DataTypeNode) node).getDataType();
- moveDataType(toCategory, dataType);
- }
- else if (node instanceof CategoryNode) {
- Category category = ((CategoryNode) node).getCategory();
- moveCategory(toCategory, category, monitor);
- }
- }
-
private void moveCategory(Category toCategory, Category category, TaskMonitor monitor) {
- if (category.getParent() == toCategory) { // moving to same place
- return;
+ if (category.getParent() == toCategory) { // // moving to same place return;
}
try {
CategoryPath path = toCategory.getCategoryPath();
@@ -512,35 +549,56 @@ public class DataTypeTreeCopyMoveTask extends Task {
}
private int askToAssociateDataTypes() {
- return OptionDialog.showYesNoCancelDialog(gTree, "Associate Data Types?",
+ return OptionDialog.showYesNoCancelDialog(tree, "Associate Data Types?",
"Do you want to associate local data types with the target archive?");
}
// filters out nodes with categories in their path
- private void filterRedundantNodes() {
+ private void filterRedundantTypes() {
- Set<GTreeNode> nodeSet = new HashSet<>(copyMoveNodes);
- List<GTreeNode> filteredList = new ArrayList<>();
+ Set<Category> set = new HashSet<>();
+ set.addAll(categories);
- for (GTreeNode node : nodeSet) {
- if (!containsAncestor(nodeSet, node)) {
- filteredList.add(node);
- }
- }
+ List<Category> filteredCats =
+ categories.stream()
+ .filter(c -> !containsAncestor(set, c))
+ .collect(Collectors.toList());
+
+ List<DataType> filteredTypes =
+ types.stream()
+ .filter(dt -> !containsAncestor(set, dt))
+ .collect(Collectors.toList());
+
+ categories = filteredCats;
+ types = filteredTypes;
+ }
- copyMoveNodes = filteredList;
+ private Category getCategory(DataType dt) {
+ CategoryPath path = dt.getCategoryPath();
+ DataTypeManager dtm = dt.getDataTypeManager();
+ return dtm.getCategory(path);
}
- private boolean containsAncestor(Set<GTreeNode> nodeSet, GTreeNode node) {
- GTreeNode parent = node.getParent();
+ private boolean containsAncestor(Set<Category> set, Category cat) {
+
+ Category parent = cat.getParent();
if (parent == null) {
return false;
}
+ if (set.contains(parent)) {
+ return true;
+ }
- if (nodeSet.contains(parent)) {
+ return containsAncestor(set, parent);
+ }
+
+ private boolean containsAncestor(Set<Category> set, DataType dt) {
+ Category parent = getCategory(dt);
+ if (set.contains(parent)) {
return true;
}
- return containsAncestor(nodeSet, parent);
+ return containsAncestor(set, parent);
}
+
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/html/CompositeDataTypeHTMLRepresentation.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/html/CompositeDataTypeHTMLRepresentation.java
index fe7c7aafd8..b4c51c191a 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/html/CompositeDataTypeHTMLRepresentation.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/html/CompositeDataTypeHTMLRepresentation.java
@@ -4,9 +4,9 @@
* 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.
@@ -200,14 +200,19 @@ public class CompositeDataTypeHTMLRepresentation extends HTMLDataTypeRepresentat
TT_CLOSE,
BR);
+ String coloredFooterText = wrapStringInColor(footerText.getText(),
+ footerText.getTextColor());
+ String coloredAlignmentValue = wrapStringInColor(alignmentValueText.getText(),
+ alignmentValueText.getTextColor());
+
append(fullHtml, truncatedHtml, lineCount++,
INDENT_OPEN,
LENGTH_PREFIX,
- footerText.getText(), // length
+ coloredFooterText, // length
HTML_SPACE,
HTML_SPACE,
ALIGNMENT_PREFIX,
- alignmentValueText.getText(),
+ coloredAlignmentValue, // alignment value number
INDENT_CLOSE);
append(fullHtml, truncatedHtml, lineCount++,
@@ -381,11 +386,16 @@ public class CompositeDataTypeHTMLRepresentation extends HTMLDataTypeRepresentat
List<ValidatableLine> header = copyLines(headerContent);
List<ValidatableLine> body = copyLines(bodyContent);
TextLine name = new TextLine(displayName.getText());
+ TextLine footer = new TextLine(footerText.getText());
+ TextLine alignmentValue = new TextLine(alignmentValueText.getText());
List<ValidatableLine> alignment = copyLines(alignmentText);
List<ValidatableLine> otherHeader = copyLines(compositeRepresentation.headerContent);
List<ValidatableLine> otherBody = copyLines(compositeRepresentation.bodyContent);
TextLine otherName = new TextLine(compositeRepresentation.displayName.getText());
+ TextLine otherFooter = new TextLine(compositeRepresentation.footerText.getText());
+ TextLine otherAlignmentValue =
+ new TextLine(compositeRepresentation.alignmentValueText.getText());
List<ValidatableLine> otherAlignment = copyLines(compositeRepresentation.alignmentText);
DataTypeDiff headerDiff =
@@ -395,16 +405,18 @@ public class CompositeDataTypeHTMLRepresentation extends HTMLDataTypeRepresentat
DataTypeDiffBuilder.diffBody(getDiffInput(body), getDiffInput(otherBody));
diffTextLine(name, otherName);
+ diffTextLine(footer, otherFooter); // size text
+ diffTextLine(alignmentValue, otherAlignmentValue); // alignment number value
diffAlignment(alignment, otherAlignment);
List<String> noWarnings = Collections.emptyList();
return new HTMLDataTypeRepresentation[] {
new CompositeDataTypeHTMLRepresentation(noWarnings, headerDiff.getLeftLines(),
- bodyDiff.getLeftLines(), alignment, footerText, name, alignmentValueText),
+ bodyDiff.getLeftLines(), alignment, footer, name, alignmentValue),
new CompositeDataTypeHTMLRepresentation(noWarnings, headerDiff.getRightLines(),
- bodyDiff.getRightLines(), otherAlignment, compositeRepresentation.footerText,
- otherName, compositeRepresentation.alignmentValueText), };
+ bodyDiff.getRightLines(), otherAlignment, otherFooter,
+ otherName, otherAlignmentValue) };
}
protected void diffAlignment(List<ValidatableLine> myLines, List<ValidatableLine> otherLines) {
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeCopyMoveDragTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeCopyMoveDragTest.java
index edb9df96c7..44129b5553 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeCopyMoveDragTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeCopyMoveDragTest.java
@@ -23,20 +23,25 @@ import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextField;
+import javax.swing.tree.TreePath;
import org.junit.*;
+import docking.ActionContext;
+import docking.DialogComponentProvider;
import docking.action.DockingActionIf;
import docking.menu.ActionState;
import docking.widgets.tree.GTreeNode;
import docking.widgets.tree.support.GTreeDragNDropHandler;
import docking.widgets.tree.support.GTreeNodeTransferable;
-import ghidra.app.context.ProgramActionContext;
+import generic.jar.ResourceFile;
import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin;
import ghidra.app.plugin.core.datamgr.actions.ConflictHandlerModesAction;
import ghidra.app.plugin.core.datamgr.tree.*;
import ghidra.app.services.ProgramManager;
+import ghidra.app.services.Upgrade;
import ghidra.app.util.datatype.DataTypeSelectionDialog;
+import ghidra.framework.Application;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.database.ProgramDB;
@@ -46,6 +51,7 @@ import ghidra.test.AbstractGhidraHeadedIntegrationTest;
import ghidra.test.TestEnv;
import ghidra.util.InvalidNameException;
import ghidra.util.exception.DuplicateNameException;
+import ghidra.util.task.TaskMonitor;
/**
* Tests copy/paste/drag/drop operations
@@ -60,7 +66,6 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
private DataTypesProvider provider;
private DockingActionIf pasteAction;
private ConflictHandlerModesAction conflictHandlerModesAction;
- private ProgramActionContext treeContext;
private DataTypeArchiveGTree tree;
private ArchiveRootNode archiveRootNode;
private DataTypeStoreNode programNode;
@@ -94,7 +99,6 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
tool.showComponentProvider(provider, true);
pasteAction = getAction(plugin, "Paste");
- treeContext = new DataTypesActionContext(provider, program, tree, null);
}
private ProgramDB buildProgram() throws Exception {
@@ -118,6 +122,14 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
builder.addCategory(path);
path = new CategoryPath(path, "Category2");
builder.addCategory(path);
+
+ // Category1/Category2/Cat2Struct
+ StructureDataType cat2Struct = new StructureDataType("Cat2Struct", 0);
+ cat2Struct.add(new WordDataType());
+ cat2Struct.setCategoryPath(path);
+ builder.addDataType(cat2Struct);
+
+ // Category1/Category2/Category3/IntStruct
path = new CategoryPath(path, "Category3");
builder.addCategory(path);
StructureDataType dt = new StructureDataType("IntStruct", 0);
@@ -556,24 +568,31 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
selectNode(miscStructureNode);
DockingActionIf copyAction = getAction(plugin, "Copy");
+ ActionContext treeContext = getContext();
assertTrue(copyAction.isEnabledForContext(treeContext));
assertFalse(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(copyAction, tree);
selectNode(miscNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
GTreeNode newNode = miscNode.getChild("Copy_1_of_" + dtName);
assertNotNull(newNode);
selectNode(miscNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
newNode = miscNode.getChild("Copy_2_of_" + dtName);
assertNotNull(newNode);
}
+ private ActionContext getContext() {
+ return runSwing(() -> provider.getActionContext(null));
+ }
+
@Test
public void testCopyPasteToDataType_SameType() throws Exception {
@@ -586,18 +605,21 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
selectNode(miscStructureNode);
DockingActionIf copyAction = getAction(plugin, "Copy");
+ ActionContext treeContext = getContext();
assertTrue(copyAction.isEnabledForContext(treeContext));
assertFalse(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(copyAction, tree);
selectNode(miscStructureNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
GTreeNode newNode = miscNode.getChild("Copy_1_of_" + dtName);
assertNotNull(newNode);
selectNode(miscStructureNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
@@ -618,6 +640,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
selectNode(miscStructureNode);
DockingActionIf copyAction = getAction(plugin, "Copy");
+ ActionContext treeContext = getContext();
assertTrue(copyAction.isEnabledForContext(treeContext));
assertFalse(pasteAction.isEnabledForContext(treeContext));
@@ -625,6 +648,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
DataTypeNode miscUnionNode = (DataTypeNode) miscNode.getChild("ArrayUnion");
selectNode(miscUnionNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
@@ -649,6 +673,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
selectNode(intStructureNode);
DockingActionIf copyAction = getAction(plugin, "Copy");
+ ActionContext treeContext = getContext();
assertTrue(copyAction.isEnabledForContext(treeContext));
assertFalse(pasteAction.isEnabledForContext(treeContext));
@@ -659,6 +684,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
expandNode(miscNode);
DataTypeNode miscUnionNode = (DataTypeNode) miscNode.getChild(existingDtName);
selectNode(miscUnionNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
@@ -680,6 +706,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
selectNode(intStructureNode);
DockingActionIf copyAction = getAction(plugin, "Copy");
+ ActionContext treeContext = getContext();
assertTrue(copyAction.isEnabledForContext(treeContext));
assertFalse(pasteAction.isEnabledForContext(treeContext));
@@ -688,6 +715,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
String dtName = "ArrayStruct";
DataTypeNode miscStructureNode = (DataTypeNode) miscNode.getChild(dtName);
selectNode(miscStructureNode);
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
@@ -710,6 +738,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
selectNodes(miscStructureNode, miscUnionNode);
DockingActionIf copyAction = getAction(plugin, "Copy");
+ ActionContext treeContext = getContext();
assertTrue(copyAction.isEnabledForContext(treeContext));
assertFalse(pasteAction.isEnabledForContext(treeContext));
@@ -718,7 +747,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
DataTypeNode intStructureNode =
(DataTypeNode) getNotepadNode("Category1/Category2/Category3/IntStruct");
selectNode(intStructureNode);
-
+ treeContext = getContext();
assertTrue(pasteAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(pasteAction, tree);
@@ -739,7 +768,8 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
DataTypeNode miscStructureNode = (DataTypeNode) miscNode.getChild(originalDtName);
selectNode(miscStructureNode);
- DockingActionIf replaceAction = getAction(plugin, "Replace");
+ DockingActionIf replaceAction = getLocalAction(provider, "Replace");
+ ActionContext treeContext = getContext();
assertTrue(replaceAction.isEnabledForContext(treeContext));
DataTypeTestUtils.performAction(replaceAction, tree, false);
@@ -750,10 +780,257 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
assertNotNull(updatedNode);
}
+ @Test
+ public void testDragCopy_Category_to_Category() throws Exception {
+
+ // Category1/Category2/Category3/NewFunStruct
+ // Drag Category3
+ String structName = "NewFunStruct";
+ DataTypeNode structureNode = createAndSelectStructure(structName);
+ CategoryNode category3Node = (CategoryNode) structureNode.getParent();
+
+ // drag/move NewFunStruct to MISC/NewFunStruct
+ CategoryNode miscNode = (CategoryNode) programNode.getChild("MISC");
+
+ copyDragNodeToNode(category3Node, miscNode);
+
+ //@formatter:off
+ assertNewNodes(
+ miscNode,
+ category3Node.getName() + "/" + structName
+ );
+ //@formatter:on
+ }
+
+ @Test
+ public void testDragMove_Category_to_Category() throws Exception {
+
+ // Category1/Category2/Category3/NewFunStruct
+ // Drag Category3
+ String structName = "NewFunStruct";
+ DataTypeNode structureNode = createAndSelectStructure(structName);
+ CategoryNode category3Node = (CategoryNode) structureNode.getParent();
+
+ // drag/move NewFunStruct to MISC/NewFunStruct
+ CategoryNode miscNode = (CategoryNode) programNode.getChild("MISC");
+
+ moveDragNodeToNode(category3Node, miscNode);
+
+ //@formatter:off
+ assertNewNodes(
+ miscNode,
+ category3Node.getName() + "/" + structName
+ );
+ //@formatter:on
+
+ CategoryNode oldCat3 = getCat3();
+ assertNull(oldCat3);
+ }
+
+ @Test
+ public void testDragCopy_Caterogy_to_Category_WithChildTypesSelected() throws Exception {
+
+ // Category1/Category2/Category3/NewFunStruct
+ // Drag Category3
+ String structName = "NewFunStruct";
+ DataTypeNode structureNode = createAndSelectStructure(structName);
+ CategoryNode category3Node = (CategoryNode) structureNode.getParent();
+
+ // drag/move NewFunStruct to MISC/NewFunStruct
+ CategoryNode miscNode = (CategoryNode) programNode.getChild("MISC");
+
+ List<GTreeNode> draggedNodes = List.of(category3Node, structureNode);
+ copyDragNodeToNode(draggedNodes, miscNode);
+
+ //@formatter:off
+ assertNewNodes(
+ miscNode,
+ category3Node.getName() + "/" + structName
+ );
+ //@formatter:on
+ }
+
+ @Test
+ public void testDragCopy_Caterogy_to_Category_WithNonChildTypesSelected() throws Exception {
+
+ //
+ // test both category copy and dt copy in same request
+ //
+
+ // Category1/Category2/Cat2Struct
+ DataTypeNode cat2Struct = getCat2Struct();
+
+ // Category1/Category2/Category3/NewFunStruct
+ // Drag Category3
+ String funStructName = "NewFunStruct";
+ DataTypeNode structureNode = createAndSelectStructure(funStructName);
+ CategoryNode category3Node = (CategoryNode) structureNode.getParent();
+
+ CategoryNode miscNode = (CategoryNode) programNode.getChild("MISC");
+
+ // Selected
+ // Category1/Category2/Cat2Struct
+ // Category1/Category2/Category3/
+ List<GTreeNode> draggedNodes = List.of(category3Node, cat2Struct);
+ copyDragNodeToNode(draggedNodes, miscNode);
+
+ // Copied
+ // MISC/Cat2Struct
+ // MISC/Category3/NewFunStruct
+ //@formatter:off
+ assertNewNodes(
+ miscNode,
+ category3Node.getName() + "/" + funStructName,
+ "Cat2Struct");
+ //@formatter:on
+ }
+
+ @Test
+ public void testDragCopy_DataType_to_Category_Associate() throws Exception {
+
+ ArchiveNode clibNode = openArchive("generic_clib.gdt");
+ expandNode(clibNode);
+
+ // Category1/Category2/Cat2Struct
+ DataTypeNode cat2Struct = getCat2Struct();
+
+ // arbitrarily picked a node; this may change as we update the archive
+ // _G_config.h
+
+ GTreeNode configFolder = clibNode.getChild("_G_config.h");
+ expandNode(configFolder);
+
+ copyDragNodeToNode(cat2Struct, configFolder, true);
+
+ //@formatter:off
+ assertNewNodes(
+ configFolder,
+ cat2Struct.getName()
+ );
+ //@formatter:on
+ }
+
+ @Test
+ public void testDragCopy_Category_to_Category_Associate() throws Exception {
+
+ ArchiveNode clibNode = openArchive("generic_clib.gdt");
+ expandNode(clibNode);
+
+ // Category1/Category2/Cat2Struct
+ DataTypeNode cat2Struct = getCat2Struct();
+
+ // arbitrarily picked a node; this may change as we update the archive
+ // _G_config.h
+
+ GTreeNode configFolder = clibNode.getChild("_G_config.h");
+ expandNode(configFolder);
+
+ CategoryNode category2 = (CategoryNode) cat2Struct.getParent();
+ copyDragNodeToNode(category2, configFolder, true);
+
+ //@formatter:off
+ assertNewNodes(
+ configFolder,
+ category2.getName(),
+ category2.getName() + "/Category3",
+ category2.getName() + '/' + cat2Struct.getName()
+ );
+ //@formatter:on
+ }
+
+ @Test
+ public void testDragCopy_DataType_to_Category_Associate_Cancel() throws Exception {
+
+ ArchiveNode clibNode = openArchive("generic_clib.gdt");
+ expandNode(clibNode);
+
+ // Category1/Category2/Cat2Struct
+ DataTypeNode cat2Struct = getCat2Struct();
+
+ // arbitrarily picked a node; this may change as we update the archive
+ // _G_config.h
+
+ GTreeNode configFolder = clibNode.getChild("_G_config.h");
+ expandNode(configFolder);
+
+ copyDragNodeToNode_Cancel(cat2Struct, configFolder, true);
+
+ //@formatter:off
+ assertNoNewNodes(
+ configFolder,
+ cat2Struct.getName()
+ );
+ //@formatter:on
+ }
+
+ // More paths we could test:
+ // 1) test mixed archives throws cancelled exception
+ // 2) test copy already associated type
+ // 3) task.setPromptToAssociateTypes(false)
+
//==================================================================================================
// Private Methods
//==================================================================================================
+ private ArchiveNode openArchive(String archiveName) throws Exception {
+ ResourceFile clibGdt = Application.getModuleDataFile("typeinfo/generic/" + archiveName);
+
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ archiveManager.openFileArchive(clibGdt, true, Upgrade.YES, false, TaskMonitor.DUMMY);
+ waitForTree();
+
+ GTreeNode rootNode = tree.getViewRoot();
+ if (archiveName.endsWith(".gdt")) {
+ archiveName = archiveName.substring(0, archiveName.length() - 4);
+ }
+ return (ArchiveNode) rootNode.getChild(archiveName);
+ }
+
+ private void assertNewNodes(GTreeNode parent, String... newNames) {
+
+ tree.expandTree(parent);
+ waitForTree();
+
+ // name may be of the form: grandparent/parent/nodeName
+ for (String name : newNames) {
+ String[] path = toPath(parent, name);
+ GTreeNode newNode = getNode(tree, path);
+ assertNotNull("Unable to find new node '%s/%s".formatted(parent.getName(), name),
+ newNode);
+ }
+ }
+
+ private void assertNoNewNodes(GTreeNode parent, String... newNames) {
+
+ tree.expandTree(parent);
+ waitForTree();
+
+ // name may be of the form: grandparent/parent/nodeName
+ for (String name : newNames) {
+ GTreeNode child = parent.getChild(name);
+ assertNull("Node should not have been copied '%s/%s".formatted(parent.getName(), name),
+ child);
+ }
+ }
+
+ private String[] toPath(GTreeNode parent, String path) {
+
+ List<String> allParts = new ArrayList<>();
+ TreePath treePath = parent.getTreePath();
+ Object[] objectPath = treePath.getPath();
+ for (Object object : objectPath) {
+ GTreeNode node = (GTreeNode) object;
+ allParts.add(node.getName());
+ }
+
+ String[] parts = path.split("/");
+ for (String part : parts) {
+ allParts.add(part);
+ }
+
+ return allParts.toArray(String[]::new);
+ }
+
private void chooseDataType(String dtName) {
DataTypeSelectionDialog chooser = waitForDialogComponent(DataTypeSelectionDialog.class);
@@ -783,16 +1060,31 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
waitForProgram();
}
+ private DataTypeNode getCat2Struct() {
+
+ // Category1/Category2/Cat2Struct
+ CategoryNode category1Node = (CategoryNode) programNode.getChild("Category1");
+ expandNode(category1Node);
+ CategoryNode category2Node = (CategoryNode) category1Node.getChild("Category2");
+ expandNode(category2Node);
+ return (DataTypeNode) category2Node.getChild("Cat2Struct");
+ }
+
+ private CategoryNode getCat3() {
+ CategoryNode category1Node = (CategoryNode) programNode.getChild("Category1");
+ expandNode(category1Node);
+ CategoryNode category2Node = (CategoryNode) category1Node.getChild("Category2");
+ expandNode(category2Node);
+ return (CategoryNode) category2Node.getChild("Category3");
+ }
+
/**
* In the program, rename Category1/Category2/Category3/IntStruct to <structureName>
*/
private DataTypeNode createAndSelectStructure(String structureName)
throws InvalidNameException, DuplicateNameException, Exception {
- CategoryNode category1Node = (CategoryNode) programNode.getChild("Category1");
- expandNode(category1Node);
- CategoryNode category2Node = (CategoryNode) category1Node.getChild("Category2");
- expandNode(category2Node);
- CategoryNode category3Node = (CategoryNode) category2Node.getChild("Category3");
+
+ CategoryNode category3Node = getCat3();
expandNode(category3Node);
DataTypeNode structureNode = (DataTypeNode) category3Node.getChild("IntStruct");
Structure structure = (Structure) structureNode.getDataType();
@@ -832,7 +1124,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
return miscNode;
}
- private void moveDragNodeToNode(GTreeNode fromNode, final GTreeNode toNode) {
+ private void moveDragNodeToNode(GTreeNode fromNode, GTreeNode toNode) {
final GTreeDragNDropHandler dragNDropHandler = tree.getDragNDropHandler();
List<GTreeNode> dropList = new ArrayList<>();
dropList.add(fromNode);
@@ -843,11 +1135,52 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
waitForTasks();
}
- private void copyDragNodeToNode(GTreeNode fromNode, final GTreeNode toNode) throws Exception {
+ private void copyDragNodeToNode(GTreeNode fromNode, GTreeNode toNode) throws Exception {
+ copyDragNodeToNode(fromNode, toNode, BATCH_MODE);
+ }
+
+ private void copyDragNodeToNode(GTreeNode fromNode, GTreeNode toNode, boolean promptToAssociate)
+ throws Exception {
final GTreeDragNDropHandler dragNDropHandler = tree.getDragNDropHandler();
List<GTreeNode> dropList = new ArrayList<>();
dropList.add(fromNode);
Transferable transferable = new GTreeNodeTransferable(dragNDropHandler, dropList);
+ runSwing(() -> dragNDropHandler.drop(toNode, transferable, DnDConstants.ACTION_COPY),
+ false);
+
+ if (promptToAssociate) {
+ DialogComponentProvider dialog = waitForDialogComponent("Associate Data Types?");
+ pressButtonByText(dialog, "Yes");
+ }
+ else {
+ waitForTasks();
+ }
+ }
+
+ private void copyDragNodeToNode_Cancel(GTreeNode fromNode, GTreeNode toNode,
+ boolean promptToAssociate) throws Exception {
+ final GTreeDragNDropHandler dragNDropHandler = tree.getDragNDropHandler();
+ List<GTreeNode> dropList = new ArrayList<>();
+ dropList.add(fromNode);
+ Transferable transferable = new GTreeNodeTransferable(dragNDropHandler, dropList);
+ runSwing(() -> dragNDropHandler.drop(toNode, transferable, DnDConstants.ACTION_COPY),
+ false);
+
+ DialogComponentProvider dialog = waitForDialogComponent("Associate Data Types?");
+ pressButtonByText(dialog, "Cancel");
+ waitForTasks();
+ }
+
+ private void copyDragNodeToNode(List<GTreeNode> draggedNodes, GTreeNode toNode)
+ throws Exception {
+
+ expandNode(toNode);
+
+ GTreeNode[] array = draggedNodes.toArray(GTreeNode[]::new);
+ selectNodes(array);
+
+ GTreeDragNDropHandler dragNDropHandler = tree.getDragNDropHandler();
+ Transferable transferable = new GTreeNodeTransferable(dragNDropHandler, draggedNodes);
runSwing(() -> dragNDropHandler.drop(toNode, transferable, DnDConstants.ACTION_COPY),
false);
waitForTasks();
@@ -856,6 +1189,7 @@ public class DataTypeCopyMoveDragTest extends AbstractGhidraHeadedIntegrationTes
//==================================================================================================
// Private Helper Methods
//==================================================================================================
+
private void expandNode(GTreeNode node) {
tree.expandPath(node);
waitForTree();
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPluginTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPluginTest.java
index 1143f8b9fc..0b8bebffd5 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPluginTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeManagerPluginTest.java
@@ -65,6 +65,7 @@ import ghidra.program.model.data.Enum;
import ghidra.program.model.dtarchive.DataTypeStore;
import ghidra.program.model.listing.Program;
import ghidra.test.*;
+import ghidra.util.Msg;
import util.CollectionUtils;
import utilities.util.FileUtilities;
@@ -1042,7 +1043,7 @@ public class DataTypeManagerPluginTest extends AbstractGhidraHeadedIntegrationTe
assertType("TypeDefToMyStruct", true);
// press the filter button
- DockingActionIf action = getAction(plugin, "Show Filter");
+ DockingActionIf action = getLocalAction(provider, "Show Filter");
performAction(action, provider, false);
DtFilterDialog dialog = waitForDialogComponent(DtFilterDialog.class);
@@ -1071,7 +1072,7 @@ public class DataTypeManagerPluginTest extends AbstractGhidraHeadedIntegrationTe
assertType("TypeDefToMyStruct", true);
// press the filter button
- DockingActionIf action = getAction(plugin, "Show Filter");
+ DockingActionIf action = getLocalAction(provider, "Show Filter");
performAction(action, provider, false);
DtFilterDialog dialog = waitForDialogComponent(DtFilterDialog.class);
@@ -1349,7 +1350,7 @@ public class DataTypeManagerPluginTest extends AbstractGhidraHeadedIntegrationTe
expandNode(programNode);
GTreeNode child = programNode.getChild(name);
selectNode(child);
- final DockingActionIf action = getAction(plugin, "Edit");
+ final DockingActionIf action = getLocalAction(provider, "Edit");
assertTrue(action.isEnabledForContext(treeContext));
performAction(action, treeContext, false);
@@ -1526,8 +1527,8 @@ public class DataTypeManagerPluginTest extends AbstractGhidraHeadedIntegrationTe
}
DataTypeNode dtNode = (DataTypeNode) node;
DataType dt = dtNode.getDataType();
- if (dt instanceof Structure) {
- map.put(dt.getName(), (Structure) dt);
+ if (dt instanceof Structure struct) {
+ map.put(dt.getName(), struct);
}
}
@@ -1559,7 +1560,7 @@ public class DataTypeManagerPluginTest extends AbstractGhidraHeadedIntegrationTe
private void disablePointerFilter() {
// press the filter button
- DockingActionIf action = getAction(plugin, "Show Filter");
+ DockingActionIf action = getLocalAction(provider, "Show Filter");
performAction(action, provider, false);
DtFilterDialog dialog = waitForDialogComponent(DtFilterDialog.class);
@@ -1668,7 +1669,7 @@ public class DataTypeManagerPluginTest extends AbstractGhidraHeadedIntegrationTe
}
}
catch (FileNotFoundException e) {
- System.err.println("Unable to delete test dir?: " + e.getMessage());
+ Msg.error(this, "Unable to delete test dir?: " + e);
}
}
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeTestUtils.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeTestUtils.java
index b31afe10da..4dbf9cc26f 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeTestUtils.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypeTestUtils.java
@@ -18,8 +18,6 @@ package ghidra.app.plugin.core.datamgr;
import java.io.File;
import java.io.IOException;
-import javax.swing.SwingUtilities;
-
import docking.ActionContext;
import docking.action.DockingActionIf;
import docking.widgets.tree.GTree;
@@ -34,6 +32,7 @@ import ghidra.program.model.data.Category;
import ghidra.program.model.data.DataTypeManager;
import ghidra.program.model.dtarchive.*;
import ghidra.program.model.listing.Program;
+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;
import ghidra.util.Msg;
import ghidra.util.Swing;
import ghidra.util.task.TaskMonitor;
@@ -222,13 +221,14 @@ public class DataTypeTestUtils {
public static void performAction(DockingActionIf action, Program program, GTree tree,
boolean wait) {
+ DataTypeArchiveGTree dtTree = (DataTypeArchiveGTree) tree;
+ DataTypesProvider provider = dtTree.getProvider();
AbstractGuiTest.runSwing(() -> {
- ActionContext context =
- new DataTypesActionContext(null, program, (DataTypeArchiveGTree) tree, null, true);
+ ActionContext context = provider.getActionContext(null);
action.actionPerformed(context);
}, wait);
- if (!SwingUtilities.isEventDispatchThread()) {
+ if (!Swing.isSwingThread()) {
AbstractGuiTest.waitForSwing();
}
}
@@ -238,26 +238,23 @@ public class DataTypeTestUtils {
}
public static void performAction(DockingActionIf action, GTree tree, boolean wait) {
+ DataTypeArchiveGTree dtTree = (DataTypeArchiveGTree) tree;
+ DataTypesProvider provider = dtTree.getProvider();
AbstractGuiTest.runSwing(() -> {
- ActionContext context =
- new DataTypesActionContext(null, null, (DataTypeArchiveGTree) tree, null, true);
+ ActionContext context = provider.getActionContext(null);
action.actionPerformed(context);
}, wait);
- if (!SwingUtilities.isEventDispatchThread()) {
+ if (!Swing.isSwingThread()) {
AbstractGuiTest.waitForSwing();
}
}
public static void createCategory(Category parent, String categoryName) throws Exception {
DataTypeManager dtm = parent.getDataTypeManager();
- int id = dtm.startTransaction("create category");
- try {
+ AbstractGhidraHeadlessIntegrationTest.tx(dtm, () -> {
parent.createCategory(categoryName);
- }
- finally {
- dtm.endTransaction(id, true);
- }
+ });
}
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypesTableTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypesTableTest.java
new file mode 100644
index 0000000000..5273be950d
--- /dev/null
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/DataTypesTableTest.java
@@ -0,0 +1,477 @@
+/* ###
+ * 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.datamgr;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import javax.swing.tree.TreePath;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import docking.action.DockingActionIf;
+import docking.widgets.table.GTable;
+import docking.widgets.table.threaded.ThreadedTableModel;
+import docking.widgets.tree.GTree;
+import docking.widgets.tree.GTreeNode;
+import generic.jar.ResourceFile;
+import ghidra.app.plugin.core.compositeeditor.StructureEditorProvider;
+import ghidra.app.plugin.core.datamgr.tree.*;
+import ghidra.app.plugin.core.programtree.ProgramTreePlugin;
+import ghidra.app.services.Upgrade;
+import ghidra.framework.Application;
+import ghidra.framework.plugintool.PluginTool;
+import ghidra.program.database.ProgramBuilder;
+import ghidra.program.database.ProgramDB;
+import ghidra.program.model.data.*;
+import ghidra.program.model.dtarchive.DataTypeStore;
+import ghidra.program.model.listing.Program;
+import ghidra.test.AbstractGhidraHeadedIntegrationTest;
+import ghidra.test.TestEnv;
+import ghidra.util.task.TaskMonitor;
+
+public class DataTypesTableTest extends AbstractGhidraHeadedIntegrationTest {
+
+ private TestEnv env;
+ private PluginTool tool;
+ private ProgramBuilder builder;
+ private ProgramDB program;
+ private DataTypeManagerPlugin plugin;
+ private DataTypesTableProvider provider;
+
+ @Before
+ public void setUp() throws Exception {
+
+ env = new TestEnv();
+ program = buildProgram();
+ tool = env.launchDefaultTool(program);
+
+ plugin = env.getPlugin(DataTypeManagerPlugin.class);
+ provider = plugin.getTableProvider();
+
+ tool.showComponentProvider(provider, true);
+ waitForTable();
+
+ removeDistractingPlugins();
+ }
+
+ private void removeDistractingPlugins() {
+
+ // cleanup the display a bit
+ ProgramTreePlugin ptp = env.getPlugin(ProgramTreePlugin.class);
+ tool.removePlugins(List.of(ptp));
+ }
+
+ private ProgramDB buildProgram() throws Exception {
+ builder = new ProgramBuilder("Program1", ProgramBuilder._TOY, this);
+
+ builder.createMemory(".text", "0x1001000", 0x100);
+ CategoryPath miscPath = new CategoryPath("/MISC");
+ builder.addCategory(miscPath);
+ StructureDataType struct = new StructureDataType("ArrayStruct", 4);
+ struct.setCategoryPath(miscPath);
+ builder.addDataType(struct);
+ UnionDataType union = new UnionDataType("ArrayUnion");
+ union.setCategoryPath(miscPath);
+ union.add(new ByteDataType());
+ builder.addDataType(union);
+
+ CategoryPath cat1Path = new CategoryPath("/Category1");
+ builder.addCategory(cat1Path);
+ CategoryPath cat2Path = new CategoryPath(cat1Path, "Category2");
+ builder.addCategory(cat2Path);
+ CategoryPath cat4Path = new CategoryPath(cat2Path, "Category4");
+ builder.addCategory(cat4Path);
+ builder.addCategory(new CategoryPath(cat2Path, "Category5"));
+
+ CategoryPath cat3Path = new CategoryPath(cat2Path, "Category3");
+ builder.addCategory(cat3Path);
+ StructureDataType dt = new StructureDataType("IntStruct", 0);
+ dt.add(new WordDataType());
+ dt.setCategoryPath(cat3Path);
+ builder.addDataType(dt);
+
+ dt = new StructureDataType("CharStruct", 0);
+ dt.add(new CharDataType());
+ dt.setCategoryPath(cat4Path);
+ builder.addDataType(dt);
+
+ StructureDataType dllTable = new StructureDataType("DLL_Table", 0);
+ dllTable.add(new WordDataType());
+ builder.addDataType(dllTable);
+
+ StructureDataType myStruct = new StructureDataType("MyStruct", 0);
+ myStruct.add(new ByteDataType(), "struct_field_names", null);
+ myStruct.setCategoryPath(cat2Path);
+ builder.addDataType(myStruct);
+
+ TypedefDataType typeDefMyStruct = new TypedefDataType("TypeDefToMyStruct", myStruct);
+ builder.addDataType(typeDefMyStruct);
+
+ Pointer16DataType ptr16 = new Pointer16DataType(new CharDataType());
+ builder.addDataType(ptr16);
+ ArrayDataType charDt = new ArrayDataType(new CharDataType(), 10);
+ builder.addDataType(charDt);
+
+ return builder.getProgram();
+ }
+
+ private Program openSecondProgram() throws Exception {
+
+ ProgramBuilder pBuilder = new ProgramBuilder("Program1", ProgramBuilder._TOY, this);
+
+ pBuilder.createMemory(".text", "0x1001000", 0x100);
+ CategoryPath miscPath = new CategoryPath("/MISC2");
+ pBuilder.addCategory(miscPath);
+ StructureDataType struct = new StructureDataType("ArrayStruct2", 4);
+ struct.setCategoryPath(miscPath);
+ pBuilder.addDataType(struct);
+
+ ProgramDB program2 = pBuilder.getProgram();
+ env.open(program2);
+
+ return program2;
+ }
+
+ @Test
+ public void testFilter_DataTypes() {
+
+ assertStructures(provider, true);
+
+ toggleStructuresInFilter(provider, false);
+ assertStructures(provider, false);
+
+ //
+ // Test that creating a snapshot will transfer the data type filter settings
+ //
+ DataTypesTableProvider snapshot = createSnapshot(provider);
+ assertStructures(snapshot, false); // snapshot matches source provider
+
+ //
+ // Change filter in snapshot and check that the source provider differs from the snapshot
+ //
+ toggleStructuresInFilter(snapshot, true);
+ assertStructures(snapshot, true);
+ assertStructures(provider, false); // source provider unaffected
+
+ //
+ // Close the snapshot and create a new snapshot. Verify the filter for the new snapshot
+ // matches the provider.
+ //
+ closeProvider(snapshot);
+ snapshot = createSnapshot(provider);
+ assertStructures(snapshot, false); // snapshot matches source provider
+ }
+
+ @Test
+ public void testFilter_ProgramTypesOnly() throws Exception {
+
+ // add types from an archive other than the program
+ openArchive("generic_clib.gdt");
+
+ assertTypesFromMultipleDtStores(provider);
+
+ toggleProgramTypesOnly(provider, true);
+ assertTypesFromOnlyProgram(provider);
+
+ toggleProgramTypesOnly(provider, false);
+ assertTypesFromMultipleDtStores(provider);
+
+ //
+ // Create a snapshot with the filter on; verify the snapshot is showing only program types.
+ //
+ toggleProgramTypesOnly(provider, true);
+ DataTypesTableProvider snapshot = createSnapshot(provider);
+ assertTypesFromOnlyProgram(snapshot); // snapshot matches source provider
+
+ //
+ // Change filter in snapshot and check that the source provider differs from the snapshot
+ //
+ toggleProgramTypesOnly(snapshot, false);
+ assertTypesFromMultipleDtStores(snapshot);
+ assertTypesFromOnlyProgram(provider); // source provider is unchanged
+
+ //
+ // Close the snapshot and create a new snapshot. Verify the filter for the new snapshot
+ // matches the provider.
+ //
+ closeProvider(snapshot);
+ snapshot = createSnapshot(provider);
+ assertTypesFromOnlyProgram(snapshot); // snapshot matches source provider
+
+ }
+
+ @Test
+ public void testAction_SelectInTree() {
+
+ selectTypeInTable("MyStruct");
+
+ DockingActionIf action = getLocalAction(provider, "Select Data Types in Tree");
+ performAction(action);
+
+ assertTypeSelectedInTree("MyStruct");
+ }
+
+ @Test
+ public void testEdit_ViaDoubleClick() {
+
+ selectTypeInTable("MyStruct");
+
+ doubleClickSelectedRow();
+
+ assertEditingStructure("MyStruct");
+ }
+
+ @Test
+ public void testChangePrograms() throws Exception {
+
+ //
+ // Test that changing programs will update the connected provider's data types
+ //
+
+ // add types from an archive other than the program
+ openArchive("generic_clib.gdt");
+
+ String p1Name = program.getName();
+ String archiveName = "generic_clib";
+ assertTypesFromDtStores(provider, p1Name, archiveName);
+
+ //
+ // Create a snapshot and verify it is unaffected by program changes
+ //
+ DataTypesTableProvider snapshot = createSnapshot(provider);
+ assertTypesFromDtStores(snapshot, p1Name, archiveName); // same program as source
+
+ Program program2 = openSecondProgram();
+ String p2Name = program2.getName();
+ assertTypesFromDtStores(provider, p2Name, archiveName); // newly activated program
+ assertTypesFromDtStores(snapshot, p1Name, archiveName); // unchanged
+
+ closeProgram(program2);
+ assertTypesFromDtStores(provider, p1Name, archiveName);
+ assertTypesFromDtStores(snapshot, p1Name, archiveName); // unchanged
+ }
+
+//==================================================================================================
+// Private Methods
+//==================================================================================================
+
+ private void closeProgram(Program p) {
+ env.close(p);
+ }
+
+ private ArchiveNode openArchive(String archiveName) throws Exception {
+ ResourceFile clibGdt = Application.getModuleDataFile("typeinfo/generic/" + archiveName);
+
+ ArchiveManager archiveManager = plugin.getArchiveManager();
+ archiveManager.openFileArchive(clibGdt, true, Upgrade.YES, false, TaskMonitor.DUMMY);
+
+ DataTypesProvider treeProvider = plugin.getProvider();
+ GTree tree = treeProvider.getGTree();
+ waitForTree(tree);
+ waitForTable(provider);
+
+ GTreeNode rootNode = tree.getViewRoot();
+ if (archiveName.endsWith(".gdt")) {
+ archiveName = archiveName.substring(0, archiveName.length() - 4);
+ }
+ return (ArchiveNode) rootNode.getChild(archiveName);
+ }
+
+ private void toggleProgramTypesOnly(DataTypesTableProvider dttp, boolean programOnly) {
+ DockingActionIf programOnlyAction = getLocalAction(dttp, "Program Types Filter");
+ performAction(programOnlyAction);
+ waitForTable(dttp);
+ }
+
+ private void assertEditingStructure(String name) {
+ StructureEditorProvider editor = waitForComponentProvider(StructureEditorProvider.class);
+ DataTypePath dtPath = editor.getDtPath();
+ assertEquals(name, dtPath.getDataTypeName());
+ }
+
+ private void doubleClickSelectedRow() {
+ GTable table = provider.getTable();
+ int row = runSwing(() -> table.getSelectedRow());
+ int col = 0;
+ int clickCount = 2;
+ clickTableCell(table, row, col, clickCount);
+ }
+
+ private void assertTypesFromDtStores(DataTypesTableProvider dttp, String... names) {
+
+ Set<String> archiveNames = getArchivesFromTable(dttp);
+ assertEquals(names.length, archiveNames.size());
+
+ for (String expectedName : names) {
+ assertTrue(archiveNames.contains(expectedName));
+ }
+ }
+
+ private void assertTypesFromMultipleDtStores(DataTypesTableProvider dttp) {
+ Set<String> archiveNames = getArchivesFromTable(dttp);
+ assertTrue(archiveNames.size() > 1);
+ }
+
+ private void assertTypesFromOnlyProgram(DataTypesTableProvider dttp) {
+ Set<String> archiveNames = getArchivesFromTable(dttp);
+ assertEquals(1, archiveNames.size());
+ String name = archiveNames.iterator().next();
+ assertEquals(program.getName(), name);
+ }
+
+ private void assertTypeSelectedInTree(String name) {
+
+ DataTypesProvider treeProvider = plugin.getProvider();
+ GTree tree = treeProvider.getGTree();
+ waitForTree(tree);
+
+ TreePath[] paths = tree.getSelectionPaths();
+ assertEquals(1, paths.length);
+
+ DataTypeNode dtNode = (DataTypeNode) paths[0].getLastPathComponent();
+ DataType dt = dtNode.getDataType();
+ assertEquals(name, dt.getName());
+ }
+
+ private Set<String> getArchivesFromTable(DataTypesTableProvider dttp) {
+ Set<String> storeNames = new HashSet<>();
+ ThreadedTableModel<DataType, Object> model = dttp.getTableModel();
+ int n = model.getRowCount();
+ for (int i = 0; i < n; i++) {
+
+ DataType dt = model.getRowObject(i);
+ DataTypeManager dtm = dt.getDataTypeManager();
+ DataTypeStore dtStore = dtm.getDataStore();
+ String name = dtStore.getName();
+ storeNames.add(name);
+ }
+ return storeNames;
+ }
+
+ private void waitForTable() {
+ waitForTable(provider);
+ }
+
+ private void waitForTable(DataTypesTableProvider dttp) {
+ waitForTableModel(dttp.getTableModel());
+ }
+
+ private void assertStructures(DataTypesTableProvider dttp,
+ boolean structuresExpected) {
+ Map<String, Structure> structures = getStructures(dttp);
+ if (!structuresExpected) {
+ assertEquals(0, structures.size());
+ }
+ else {
+ assertTrue(structures.size() > 0);
+ }
+ }
+
+ private Map<String, Structure> getStructures(DataTypesTableProvider dttp) {
+
+ Map<String, Structure> map = new HashMap<>();
+ ThreadedTableModel<DataType, Object> model = dttp.getTableModel();
+ int n = model.getRowCount();
+ for (int i = 0; i < n; i++) {
+
+ DataType dt = model.getRowObject(i);
+ if (dt instanceof Structure struct) {
+ map.put(dt.getName(), struct);
+ }
+ }
+
+ return map;
+ }
+
+ private void assertType(DataTypesTableProvider dttp, String name,
+ boolean isShowing) {
+
+ DataType dt = getTypeFromTable(dttp, name);
+ if (isShowing) {
+ assertNotNull("Data type not found: '%s'", dt);
+ }
+ else {
+ assertNull(dt);
+ }
+ }
+
+ private DataType getTypeFromTable(DataTypesTableProvider dttp, String name) {
+ ThreadedTableModel<DataType, Object> model = dttp.getTableModel();
+ int n = model.getRowCount();
+ for (int i = 0; i < n; i++) {
+
+ DataType dt = model.getRowObject(i);
+ String dtName = dt.getName();
+ if (dtName.equals(name)) {
+ return dt;
+ }
+ }
+ return null;
+ }
+
+ private void selectTypeInTable(String name) {
+ int index = indexOfType(name);
+ GTable table = provider.getTable();
+ runSwing(() -> table.selectRow(index));
+ }
+
+ private int indexOfType(String name) {
+
+ ThreadedTableModel<DataType, Object> model = provider.getTableModel();
+ int n = model.getRowCount();
+ for (int i = 0; i < n; i++) {
+
+ DataType dt = model.getRowObject(i);
+ String dtName = dt.getName();
+ if (dtName.equals(name)) {
+ return i;
+ }
+ }
+
+ fail("Unable to find data type '%s' in the table".formatted(name));
+ return -1;
+ }
+
+ private void toggleStructuresInFilter(DataTypesTableProvider dttp, boolean showStructues) {
+ DtFilterDialog dialog = showDtFilter(dttp);
+ setToggleButtonSelected(dialog.getComponent(), "Structures", showStructues);
+ pressButtonByText(dialog, "OK");
+ waitForTable();
+ }
+
+ private DtFilterDialog showDtFilter(DataTypesTableProvider dttp) {
+ DockingActionIf action = getLocalAction(dttp, "Show Filter");
+ performAction(action, provider, false);
+ return waitForDialogComponent(DtFilterDialog.class);
+ }
+
+ private DataTypesTableProvider createSnapshot(DataTypesTableProvider dttp) {
+
+ DockingActionIf action = getLocalAction(dttp, "Data Types Table Snapshot");
+ performAction(action, false);
+
+ String name = dttp.getName();
+ String snapshotTitle = '[' + name + ']';
+ DataTypesTableProvider snapshot =
+ waitForComponentProvider(DataTypesTableProvider.class, snapshotTitle);
+ waitForTable(snapshot);
+ return snapshot;
+ }
+
+}
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/util/DataTypeCopyMoveDrag2Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/util/DataTypeCopyMoveDrag2Test.java
index 3c79c8a5d2..abde0aeb38 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/util/DataTypeCopyMoveDrag2Test.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/datamgr/util/DataTypeCopyMoveDrag2Test.java
@@ -4,9 +4,9 @@
* 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.
@@ -28,30 +28,28 @@ public class DataTypeCopyMoveDrag2Test extends AbstractGTest {
@Test
public void testGetBaseName() {
- DataTypeTreeCopyMoveTask task = new DataTypeTreeCopyMoveTask();
String name = "BaseName";
- assertEquals(name, task.getBaseName(name));
+ assertEquals(name, DataTypesCopyMoveTask.getBaseName(name));
String copyName = "Copy_of_" + name;
- assertEquals(name, task.getBaseName(copyName));
+ assertEquals(name, DataTypesCopyMoveTask.getBaseName(copyName));
copyName = "Copy_2_of_" + name;
- assertEquals(name, task.getBaseName(copyName));
+ assertEquals(name, DataTypesCopyMoveTask.getBaseName(copyName));
}
@Test
public void testGetNextCopyName() {
- DataTypeTreeCopyMoveTask task = new DataTypeTreeCopyMoveTask();
String name = "BaseName";
CountBasedStubCategory category = new CountBasedStubCategory("Category", 0);
- assertEquals("Copy_1_of_" + name, task.getNextCopyName(category, name));
+ assertEquals("Copy_1_of_" + name, DataTypesCopyMoveTask.getNextCopyName(category, name));
category = new CountBasedStubCategory("Category", 1);
- assertEquals("Copy_2_of_" + name, task.getNextCopyName(category, name));
+ assertEquals("Copy_2_of_" + name, DataTypesCopyMoveTask.getNextCopyName(category, name));
category = new CountBasedStubCategory("Category", 10);
- assertEquals("Copy_11_of_" + name, task.getNextCopyName(category, name));
+ assertEquals("Copy_11_of_" + name, DataTypesCopyMoveTask.getNextCopyName(category, name));
}
private class CountBasedStubCategory extends TestDoubleCategory {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/ComponentNode.java b/Ghidra/Framework/Docking/src/main/java/docking/ComponentNode.java
index d1540f8bb3..d8335e474e 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/ComponentNode.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/ComponentNode.java
@@ -589,7 +589,7 @@ class ComponentNode extends Node {
pane.setIconAt(index, icon);
String tabText = placeholder.getTabText();
- String fullTitle = placeholder.getTitle();
+ String fullTitle = placeholder.getFullTitle();
renderer.setTitle(tabText, fullTitle);
pane.setTitleAt(index, tabText);
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java b/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java
index 84db78106c..90845d9d69 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java
@@ -401,7 +401,9 @@ public abstract class ComponentProvider implements HelpDescriptor, ActionContext
}
/**
- * Convenience method to indicate if this provider is showing.
+ * Convenience method to indicate if this provider is in a tool window. This will return true
+ * even if the provider is hidden behind another provider, such as when in a tabbed pane and
+ * not the active tab.
* @return true if this provider is showing.
*/
public boolean isVisible() {
@@ -410,7 +412,9 @@ public abstract class ComponentProvider implements HelpDescriptor, ActionContext
/**
* Returns true if this provider is visible and is showing. See {@link Component#isShowing()}.
- * @return true if this provider is visible and is showing.
+ * Unlike {@link #isVisible()}, this method will return false if the component is hidden
+ * behind another component, such as when in a tabbed pane and not the active tab.
+ * @return true if this provider is visible and is showing.
*/
public boolean isShowing() {
return isVisible() && getComponent().isShowing();
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/dnd/DragDropTableSelectionMouseListener.java b/Ghidra/Framework/Docking/src/main/java/docking/dnd/DragDropTableSelectionMouseListener.java
index b570795864..4b9ca837ea 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/dnd/DragDropTableSelectionMouseListener.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/dnd/DragDropTableSelectionMouseListener.java
@@ -4,9 +4,9 @@
* 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.
@@ -113,12 +113,22 @@ public class DragDropTableSelectionMouseListener extends MouseAdapter {
int row = table.rowAtPoint(e.getPoint());
if (table.isRowSelected(row)) {
e.consume();
+
+ // By consuming the event, we have disabled Java's mechanism for focusing tables when
+ // they are clicked. Ensure focus changes.
+ checkForFocus();
return true;
}
return false;
}
+ private void checkForFocus() {
+ if (!table.hasFocus()) {
+ table.requestFocus();
+ }
+ }
+
private boolean isBasicLeftClick(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/dnd/GTableDragProvider.java b/Ghidra/Framework/Docking/src/main/java/docking/dnd/GTableDragProvider.java
index 618d9e0028..213c36cb19 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/dnd/GTableDragProvider.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/dnd/GTableDragProvider.java
@@ -4,9 +4,9 @@
* 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.
@@ -45,11 +45,15 @@ public abstract class GTableDragProvider<ROW_OBJECT>
// install table mouse selection fixing listener
new DragDropTableSelectionMouseListener(table);
- int actions = DnDConstants.ACTION_COPY;
+ int actions = getDragActions();
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(table, actions, this);
}
+ protected int getDragActions() {
+ return DnDConstants.ACTION_COPY;
+ }
+
/**
* Creates a transferable for dragging using the given selected row objects.
* @param items the selected row objects
@@ -77,20 +81,19 @@ public abstract class GTableDragProvider<ROW_OBJECT>
}
private void setCursor(int action, DragSourceContext dragSourceContext) {
- Cursor cursor = DragSource.DefaultCopyNoDrop;
- switch (action) {
- case DnDConstants.ACTION_COPY:
- cursor = DragSource.DefaultCopyDrop;
- break;
- case DnDConstants.ACTION_MOVE:
- cursor = DragSource.DefaultMoveDrop;
- break;
- case DnDConstants.ACTION_LINK:
- cursor = DragSource.DefaultLinkDrop;
- }
+ Cursor cursor = getCursor(action);
dragSourceContext.setCursor(cursor);
}
+ private Cursor getCursor(int action) {
+ return switch (action) {
+ case DnDConstants.ACTION_COPY -> DragSource.DefaultCopyDrop;
+ case DnDConstants.ACTION_MOVE -> DragSource.DefaultMoveDrop;
+ case DnDConstants.ACTION_LINK -> DragSource.DefaultLinkDrop;
+ default -> DragSource.DefaultCopyNoDrop;
+ };
+ }
+
@Override
public void dragOver(DragSourceDragEvent dsde) {
setCursor(dsde.getDropAction(), dsde.getDragSourceContext());
@@ -127,7 +130,7 @@ public abstract class GTableDragProvider<ROW_OBJECT>
}
try {
- dragEvent.startDrag(DragSource.DefaultMoveDrop, null, new Point(0, 0), transferable,
+ dragEvent.startDrag(DragSource.DefaultMoveNoDrop, null, new Point(0, 0), transferable,
this);
}
catch (InvalidDnDOperationException exc) {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/test/AbstractDockingTest.java b/Ghidra/Framework/Docking/src/main/java/docking/test/AbstractDockingTest.java
index 75c3714297..2e9b6c8551 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/test/AbstractDockingTest.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/test/AbstractDockingTest.java
@@ -712,15 +712,32 @@ public abstract class AbstractDockingTest extends AbstractGuiTest {
private static <T extends ComponentProvider> T getComponentProvider(
DockingWindowManager windowManager, Class<T> clazz) {
+ /*
+ // Note: this code doesn't really make sense anymore. If test pass, then delete this
+ // and getDetachedWindowProvider()
+
T detached = getDetachedWindowProvider(clazz, windowManager);
if (detached != null) {
return detached;
}
+ */
T t = windowManager.getComponentProvider(clazz);
return t;
}
+ private static <T extends ComponentProvider> T getComponentProvider(
+ DockingWindowManager windowManager, Class<T> clazz, String title) {
+
+ List<T> allProviders = windowManager.getComponentProviders(clazz);
+ for (T t : allProviders) {
+ if (t.getTitle().equals(title)) {
+ return t;
+ }
+ }
+ return null;
+ }
+
/**
* Searches for the first occurrence of a {@link ComponentProvider} that is an instance of
* the given <code>providerClass</code>. This method will repeat the search every
@@ -809,7 +826,7 @@ public abstract class AbstractDockingTest extends AbstractGuiTest {
int totalTime = 0;
while (totalTime <= DEFAULT_WAIT_TIMEOUT) {
- T t = getComponentProvider(windowManager, clazz);
+ T t = getComponentProvider(windowManager, clazz, title);
if (Objects.deepEquals(title, t.getTitle())) {
return t;
}
@@ -2125,14 +2142,15 @@ public abstract class AbstractDockingTest extends AbstractGuiTest {
if (!rootNode.getName().equals(rootName)) {
throw new RuntimeException(
"When selecting paths by name the first path element must be the " +
- "name of the root node - path: " + StringUtils.join(path, '.'));
+ "name of the root node '" + rootNode.getName() + "' - path: " +
+ StringUtils.join(path, '.'));
}
GTreeNode node = rootNode;
for (int i = 1; i < path.length; i++) {
GTreeNode child = node.getChild(path[i]);
if (child == null) {
throw new RuntimeException(
- "Can't find path " + StringUtils.join(path, '.') + " failed at " + path[i]);
+ "Can't find path " + StringUtils.join(path, '/') + " failed at " + path[i]);
}
node = child;
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/DropDownTextField.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/DropDownTextField.java
index 33480ace28..d8530611b0 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/DropDownTextField.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/DropDownTextField.java
@@ -974,6 +974,7 @@ public class DropDownTextField<T> extends JTextField implements GComponent {
//=================================================================================================
protected class DropDownList extends GList<T> {
+
@Override
public void setFont(Font f) {
super.setFont(f);
@@ -982,18 +983,18 @@ public class DropDownTextField<T> extends JTextField implements GComponent {
private void updateCellDimensions(Font font) {
- if (font == null || list == null) {
+ if (font == null) {
return; // UI is initializing
}
- FontMetrics fontMetrics = list.getFontMetrics(font);
+ FontMetrics fontMetrics = getFontMetrics(font);
int padding = 2; // top and bottom border height
int lineHeight = fontMetrics.getHeight() + padding;
int iconAndPaddingHeight = 16 + padding;
int cellHeight = Math.max(lineHeight, iconAndPaddingHeight);
- list.setFixedCellHeight(cellHeight);
- list.setFixedCellWidth(MIN_WIDTH - 20); // add some fudge for scrollbars
+ setFixedCellHeight(cellHeight);
+ setFixedCellWidth(MIN_WIDTH - 20); // add some fudge for scrollbars
}
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/tabbedpane/DockingTabRenderer.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/tabbedpane/DockingTabRenderer.java
index bd7cf212c5..143f108e41 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/tabbedpane/DockingTabRenderer.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/tabbedpane/DockingTabRenderer.java
@@ -126,8 +126,8 @@ public class DockingTabRenderer extends JPanel {
return title;
}
- public void installPopupMenu(JPopupMenu popupMenu) {
- this.popupMenu = popupMenu;
+ public void installPopupMenu(JPopupMenu menu) {
+ this.popupMenu = menu;
}
public void setIcon(Icon icon) {
@@ -135,7 +135,9 @@ public class DockingTabRenderer extends JPanel {
}
public void setTitle(String tabText, String fullTitle) {
- titleLabel.setText(getShortenedTitle(tabText));
+ String clippedTabText = getShortenedTitle(tabText);
+ titleLabel.setText(clippedTabText);
+
String trimmedTabText = tabText.trim();
String trimmedTitleText = fullTitle.trim();
if (trimmedTabText.equals(trimmedTitleText)) {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/DynamicColumnTableModel.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/DynamicColumnTableModel.java
index 74cef04688..e0df86de52 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/DynamicColumnTableModel.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/DynamicColumnTableModel.java
@@ -45,7 +45,7 @@ public interface DynamicColumnTableModel<ROW_TYPE>
* The preference key is used to save the column state of this configurable model. All models
* that share a preference key will share the same visible column state.
* The {@link GTableColumnModel} manages this state for the framework. The column model will
- * ask the table for its preference key, which will ask the model when not key has been set on
+ * ask the table for its preference key, which will ask the model when no key has been set on
* the table. In the case that no key is set in the table or the model, a key will be created
* based on the classname and default columns.
*
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/GTableFilterPanel.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/GTableFilterPanel.java
index e252f179c2..3e9afdc541 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/GTableFilterPanel.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/GTableFilterPanel.java
@@ -35,8 +35,7 @@ import docking.widgets.label.GDLabel;
import docking.widgets.table.columnfilter.ColumnBasedTableFilter;
import docking.widgets.table.columnfilter.ColumnFilterManager;
import ghidra.framework.options.PreferenceState;
-import ghidra.util.HelpLocation;
-import ghidra.util.Msg;
+import ghidra.util.*;
import ghidra.util.exception.AssertException;
import ghidra.util.task.SwingUpdateManager;
import help.HelpService;
@@ -93,7 +92,7 @@ import utility.function.Callback;
* <li>The {@link TableFilter} used by this class will be passed the empty string ("") when
* {@link TableFilter#acceptsRow(Object)} is called.</li>
* <li><b>You cannot rely on {@link JTable#getRowCount()} to access all of the table data,
- * since the data may be filtered.</b> To get a row count that is always all of the model's \
+ * since the data may be filtered.</b> To get a row count that is always all of the model's
* data, call {@link #getUnfilteredRowCount()}.</li>
* </ul>
*
@@ -551,6 +550,10 @@ public class GTableFilterPanel<ROW_OBJECT> extends JPanel {
return rowObjectFilterModel;
}
+ /**
+ * Disposes this filter panel and it's internal widgets. Clients that call this method do not
+ * have to call {@link GTable#dispose()}, as this call will do that for them.
+ */
public void dispose() {
DockingWindowManager dwm = DockingWindowManager.getInstance(this);
@@ -832,6 +835,26 @@ public class GTableFilterPanel<ROW_OBJECT> extends JPanel {
return uniquePreferenceKey;
}
+ /**
+ * Transfers this filter panel's settings to the other filter panel. This is useful when making
+ * snapshots of tables when the client wishes to apply the same filter settings to the new
+ * window. This will copy the current filter text, filter type settings and the column filter.
+ * @param other the other filter panel to receive this panel's settings
+ */
+ public void transferSettings(GTableFilterPanel<ROW_OBJECT> other) {
+
+ Swing.runLater(() -> {
+ PreferenceState state = createPreferenceState();
+ other.loadFromPreferenceState(state);
+
+ String filterText = getFilterText();
+ other.setFilterText(filterText);
+
+ ColumnBasedTableFilter<ROW_OBJECT> columnFilter = getColumnTableFilter();
+ other.setColumnTableFilter(columnFilter);
+ });
+ }
+
//==================================================================================================
// Inner Classes
//==================================================================================================
@@ -969,7 +992,7 @@ public class GTableFilterPanel<ROW_OBJECT> extends JPanel {
}
}
- return getInceptionInformationFromTheFirstClassThatIsNotUs();
+ return getInceptionInformationFromTheFirstClassThatIsNotUs() + extension;
}
private static String getInceptionInformationFromTheFirstClassThatIsNotUs() {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/RowObjectSelectionManager.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/RowObjectSelectionManager.java
index 07d1204cb7..be84cb1c31 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/RowObjectSelectionManager.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/RowObjectSelectionManager.java
@@ -4,9 +4,9 @@
* 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.
@@ -15,11 +15,10 @@
*/
package docking.widgets.table;
-import java.util.*;
-
import java.awt.Rectangle;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
+import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
@@ -316,6 +315,8 @@ public class RowObjectSelectionManager<T> extends DefaultListSelectionModel
}
int[] updatedViewRows = translateSavedObjectSelectionToRowIndexes();
+
+ trace("\ttranslated view rows: " + Arrays.toString(updatedViewRows));
selectRows(updatedViewRows);
});
}
@@ -369,6 +370,8 @@ public class RowObjectSelectionManager<T> extends DefaultListSelectionModel
// duplicate entries, which we have to keep at separate indices in order to restore selection
int rowCount = modelAdapter.getRowCount();
if (rowCount > ARTIFICIAL_ROW_COUNT_THRESHOLD) {
+ trace("\ttoo many rows to map %s > %s: ".formatted(rowCount,
+ ARTIFICIAL_ROW_COUNT_THRESHOLD));
return Collections.emptyMap();
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/SelectColumnsDialog.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/SelectColumnsDialog.java
index a826497dcd..7f3f364cbe 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/SelectColumnsDialog.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/SelectColumnsDialog.java
@@ -4,9 +4,9 @@
* 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.
@@ -81,7 +81,7 @@ public class SelectColumnsDialog extends DialogComponentProvider {
addOKButton();
addCancelButton();
- setHelpLocation(new HelpLocation("Tables/GhidraTableHeaders.html", "SelectColumns"));
+ setHelpLocation(new HelpLocation("Tables", "SelectColumns"));
}
private void initialize() {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/StringEqualsColumnConstraint.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/StringEqualsColumnConstraint.java
new file mode 100644
index 0000000000..a3e53d3b7f
--- /dev/null
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/StringEqualsColumnConstraint.java
@@ -0,0 +1,53 @@
+/* ###
+ * 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.table.constraint;
+
+import java.util.regex.Pattern;
+
+import ghidra.util.UserSearchUtils;
+
+/**
+ * String column constraint for matching column values if they equal the constraint value pattern.
+ */
+public class StringEqualsColumnConstraint extends StringColumnConstraint {
+
+ /**
+ * Constructor.
+ *
+ * @param patternString the string to use to create a "contains" pattern.
+ */
+ public StringEqualsColumnConstraint(String patternString) {
+ super(patternString);
+ }
+
+ @Override
+ public String getName() {
+ return "Equals";
+ }
+
+ @Override
+ public ColumnConstraint<String> copy(String newPatternString) {
+ return new StringEqualsColumnConstraint(newPatternString);
+ }
+
+ @Override
+ protected Pattern generateMatchesPattern(String patternString) {
+ // create a literal pattern that escapes regex characters
+ return UserSearchUtils.createPattern(patternString, false,
+ Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
+ }
+
+}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/StringNotEqualsColumnConstraint.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/StringNotEqualsColumnConstraint.java
new file mode 100644
index 0000000000..4aa8df9f69
--- /dev/null
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/StringNotEqualsColumnConstraint.java
@@ -0,0 +1,58 @@
+/* ###
+ * 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.table.constraint;
+
+import java.util.regex.Pattern;
+
+/**
+ * String column constraint for matching column values if they don't equal the constraint value pattern.
+ */
+public class StringNotEqualsColumnConstraint extends StringEqualsColumnConstraint {
+
+ /**
+ * Constructor.
+ *
+ * @param patternString the string to use to create a "contains" pattern.
+ */
+ public StringNotEqualsColumnConstraint(String patternString) {
+ super(patternString);
+ }
+
+ @Override
+ public String getName() {
+ return "Does Not Equal";
+ }
+
+ @Override
+ public String getGroup() {
+ return "z string";
+ }
+
+ @Override
+ public boolean accepts(String value, TableFilterContext context) {
+ return !super.accepts(value, context);
+ }
+
+ @Override
+ public ColumnConstraint<String> copy(String newPatternString) {
+ return new StringNotEqualsColumnConstraint(newPatternString);
+ }
+
+ @Override
+ protected Pattern generateFindsPattern() {
+ return Pattern.compile("(.*)");
+ }
+}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/provider/StringColumnConstraintProvider.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/provider/StringColumnConstraintProvider.java
index 5207ac248b..f73f057a54 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/provider/StringColumnConstraintProvider.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/provider/StringColumnConstraintProvider.java
@@ -4,9 +4,9 @@
* 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.
@@ -30,11 +30,13 @@ public class StringColumnConstraintProvider implements ColumnConstraintProvider
list.add(new StringContainsColumnConstraint(""));
list.add(new StringStartsWithColumnConstraint(""));
+ list.add(new StringEqualsColumnConstraint(""));
list.add(new StringMatchesColumnConstraint(""));
list.add(new StringNotMatchesColumnConstraint(""));
list.add(new StringNotContainsColumnConstraint(""));
list.add(new StringNotStartsWithColumnConstraint(""));
+ list.add(new StringNotEqualsColumnConstraint(""));
list.add(new StringEndsWithColumnConstraint(""));
list.add(new StringNotEndsWithColumnConstraint(""));
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/AutocompletingStringConstraintEditor.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/AutocompletingStringConstraintEditor.java
index eae64b5a46..80da0ab0f8 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/AutocompletingStringConstraintEditor.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/AutocompletingStringConstraintEditor.java
@@ -102,7 +102,7 @@ public class AutocompletingStringConstraintEditor extends DataLoadingConstraintE
@Override
public void columnDataLoadComplete() {
- // do nothing
+ autocompleter.loadComplete();
}
@Override
@@ -134,6 +134,7 @@ public class AutocompletingStringConstraintEditor extends DataLoadingConstraintE
private class AutocompleteDataModel implements DropDownTextFieldDataModel<String> {
private final Set<String> dataSet = new HashSet<>();
+ private final List<String> dataList = new ArrayList<>();
private StringColumnConstraint lastConstraint;
@Override
@@ -151,18 +152,24 @@ public class AutocompletingStringConstraintEditor extends DataLoadingConstraintE
lastConstraint = (StringColumnConstraint) currentConstraint
.parseConstraintValue(searchText, columnDataSource.getTableDataSource());
- // Use a Collator to support languages other than English.
- Collator collator = Collator.getInstance();
- collator.setStrength(Collator.SECONDARY);
-
// @formatter:off
- return dataSet.stream()
+ return dataList.stream()
.filter(k -> lastConstraint.accepts(k, null))
- .sorted( (k1, k2) -> collator.compare(k1, k2))
.collect(Collectors.toList());
// @formatter:on
}
+ public void loadComplete() {
+
+ dataList.addAll(dataSet);
+ dataSet.clear();
+
+ // Use a Collator to support languages other than English.
+ Collator collator = Collator.getInstance();
+ collator.setStrength(Collator.SECONDARY);
+ Collections.sort(dataList, (k1, k2) -> collator.compare(k1, k2));
+ }
+
private boolean isValidPatternString(String searchText) {
StringColumnConstraint stringConstraint = (StringColumnConstraint) currentConstraint;
return stringConstraint.isValidPatternString(searchText);
@@ -188,7 +195,7 @@ public class AutocompletingStringConstraintEditor extends DataLoadingConstraintE
return value;
}
- public void collect(String value) {
+ void collect(String value) {
if (value == null) {
return;
}
@@ -196,13 +203,12 @@ public class AutocompletingStringConstraintEditor extends DataLoadingConstraintE
}
public void loadCancelled() {
- // reset();
+ reset();
}
public void clear() {
dataSet.clear();
}
-
}
/**
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/DataLoadingConstraintEditor.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/DataLoadingConstraintEditor.java
index 845c7e96fb..cfc7d15166 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/DataLoadingConstraintEditor.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constrainteditor/DataLoadingConstraintEditor.java
@@ -339,12 +339,7 @@ public abstract class DataLoadingConstraintEditor<T> extends AbstractColumnConst
monitor.setMessage(
"Loading column data... (" + getElapsedTimeString(elapsed) + ")");
monitor.incrementProgress(1);
-
}
-// Keep until 2019
-// Msg.info(this, "Load of " + limit + " rows from '" + columnDataSource.getColumnName() +
-// "' took " + getElapsedTimeString(System.nanoTime() - start));
-
}
}
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/GTree.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/GTree.java
index 0b744f0e25..676fcab74a 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/GTree.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/GTree.java
@@ -529,6 +529,10 @@ public class GTree extends JPanel implements BusyListener {
tree.addSelectionPath(path);
}
+ public void addSelectedNode(GTreeNode node) {
+ addSelectionPath(node.getTreePath());
+ }
+
public void setSelectedNode(GTreeNode node) {
setSelectionPaths(new TreePath[] { node.getTreePath() });
}
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/internal/GTreeDragNDropAdapter.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/internal/GTreeDragNDropAdapter.java
index cbabf3aa9f..e374401178 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/internal/GTreeDragNDropAdapter.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/internal/GTreeDragNDropAdapter.java
@@ -5,9 +5,9 @@
* 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.
@@ -76,20 +76,19 @@ public class GTreeDragNDropAdapter
}
private void setCursor(int action, DragSourceContext dragSourceContext) {
- Cursor cursor = DragSource.DefaultCopyNoDrop;
- switch (action) {
- case DnDConstants.ACTION_COPY:
- cursor = DragSource.DefaultCopyDrop;
- break;
- case DnDConstants.ACTION_MOVE:
- cursor = DragSource.DefaultMoveDrop;
- break;
- case DnDConstants.ACTION_LINK:
- cursor = DragSource.DefaultLinkDrop;
- }
+ Cursor cursor = getCursor(action);
dragSourceContext.setCursor(cursor);
}
+ private Cursor getCursor(int action) {
+ return switch (action) {
+ case DnDConstants.ACTION_COPY -> DragSource.DefaultCopyDrop;
+ case DnDConstants.ACTION_MOVE -> DragSource.DefaultMoveDrop;
+ case DnDConstants.ACTION_LINK -> DragSource.DefaultLinkDrop;
+ default -> DragSource.DefaultCopyNoDrop;
+ };
+ }
+
@Override
public void dragOver(DragSourceDragEvent dsde) {
setCursor(dsde.getDropAction(), dsde.getDragSourceContext());
@@ -121,18 +120,19 @@ public class GTreeDragNDropAdapter
if (!tree.isPathSelected(path)) {
return;
}
+
+ int dragAction = dragEvent.getDragAction();
List<GTreeNode> selectedData = createSelectionList(tree.getSelectionPaths());
- if (!dragNDropHandler.isStartDragOk(selectedData, dragEvent.getDragAction())) {
+ if (!dragNDropHandler.isStartDragOk(selectedData, dragAction)) {
return;
}
Transferable transferable = new GTreeNodeTransferable(dragNDropHandler, selectedData);
Image image = getDragImage(selectedData);
-
+ Cursor cursor = getCursor(dragAction);
try {
- dragEvent.startDrag(DragSource.DefaultCopyNoDrop, image, new Point(-10, -30),
- transferable, this);
+ dragEvent.startDrag(cursor, image, new Point(-10, -30), transferable, this);
}
catch (InvalidDnDOperationException exc) {
Msg.debug(this, "Unable to initiate drag from tree", exc);
diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeTransferable.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeTransferable.java
index a15e5445ac..e68f2e02d4 100644
--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeTransferable.java
+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/DataTypeTransferable.java
@@ -4,9 +4,9 @@
* 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.
@@ -21,7 +21,6 @@ import java.util.Arrays;
import java.util.List;
import docking.dnd.GenericDataFlavor;
-import ghidra.util.Msg;
/**
* Defines data that is available for drag/drop and clipboard transfers.
@@ -29,31 +28,38 @@ import ghidra.util.Msg;
*/
public class DataTypeTransferable implements Transferable, ClipboardOwner {
- // Flavor for this Transferable
+ /**
+ * Used for drag/drop of a single data type
+ */
public static final DataFlavor localDataTypeFlavor = createLocalDataTypeFlavor();
+
+ /**
+ * Used for drag/drop of a single data type
+ */
public static final DataFlavor localBuiltinDataTypeFlavor = createLocalBuiltinDataTypeFlavor();
- // create a data flavor that is a tool button
+ /**
+ * Used for drag/drop of a multiple data types
+ */
+ public static final DataFlavor localDataTypeListFlavor = createLocalDataTypeListFlavor();
+
+ // create a data flavor for a single data type
private static DataFlavor createLocalDataTypeFlavor() {
- try {
- return new GenericDataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
- "; class=ghidra.program.model.data.DataTypeImpl", "Local data type object");
- }
- catch (Exception e) {
- Msg.showError(DataTypeTransferable.class, null, null, null, e);
- }
- return null;
+ return new GenericDataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
+ "; class=ghidra.program.model.data.DataType", "Local data type object");
}
+ // flavor for single built-in data type
private static DataFlavor createLocalBuiltinDataTypeFlavor() {
- try {
- return new GenericDataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
- "; class=ghidra.program.model.data.DataTypeImpl", "Local BuiltIn data type object");
- }
- catch (Exception e) {
- Msg.showError(DataTypeTransferable.class, null, null, null, e);
- }
- return null;
+ return new GenericDataFlavor(DataFlavor.javaJVMLocalObjectMimeType +
+ "; class=ghidra.program.model.data.DataType", "Local BuiltIn data type object");
+ }
+
+ // create a data flavor that is a List of data types
+ private static DataFlavor createLocalDataTypeListFlavor() {
+ return new GenericDataFlavor(
+ DataFlavor.javaJVMLocalObjectMimeType + "; class=java.util.List",
+ "Local list of Drag/Drop DataType objects");
}
private static DataFlavor[] flavors = { localDataTypeFlavor, localBuiltinDataTypeFlavor };
@@ -69,25 +75,16 @@ public class DataTypeTransferable implements Transferable, ClipboardOwner {
dataType = dt;
}
- /**
- * Return all data flavors that this class supports.
- */
@Override
public synchronized DataFlavor[] getTransferDataFlavors() {
return flavors;
}
- /**
- * Return whether the specifed data flavor is supported.
- */
@Override
public boolean isDataFlavorSupported(DataFlavor f) {
return flavorList.contains(f);
}
- /**
- * Return the transfer data with the given data flavor.
- */
@Override
public synchronized Object getTransferData(DataFlavor f) throws UnsupportedFlavorException,
IOException {
@@ -99,19 +96,14 @@ public class DataTypeTransferable implements Transferable, ClipboardOwner {
}
- /**
- * Get the string representation for this transferable.
- */
@Override
public String toString() {
return "DataTypeTransferable";
}
- /**
- * ClipboardOwner interface method.
- */
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
+ // stub
}
}
diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/ProgramBasedDataTypeManager.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/ProgramBasedDataTypeManager.java
index b15bf94397..09b0b7540e 100644
--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/ProgramBasedDataTypeManager.java
+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/ProgramBasedDataTypeManager.java
@@ -32,7 +32,7 @@ public interface ProgramBasedDataTypeManager extends DataTypeManager {
* Get the program instance associated with this datatype manager
* @return program instance associated with this datatype manager
*/
- Program getProgram();
+ public Program getProgram();
/**
* Determine if a settings change is permitted for the specified settingsDefinition.