Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-2950 fixing up GhidraComboBox and its clients to handle theme changes

ghidragon31696c40f9e6
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/bookmark/CreateBookmarkDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/bookmark/CreateBookmarkDialog.java
index 986bd75627..a2081c4208 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/bookmark/CreateBookmarkDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/bookmark/CreateBookmarkDialog.java
@@ -22,13 +22,11 @@
package ghidra.app.plugin.core.bookmark;
import java.awt.*;
-import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import docking.DialogComponentProvider;
-import docking.DockingUtils;
import docking.widgets.checkbox.GCheckBox;
import docking.widgets.combobox.GhidraComboBox;
import docking.widgets.label.GIconLabel;
@@ -36,6 +34,7 @@ import docking.widgets.label.GLabel;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.*;
import ghidra.util.HelpLocation;
+import ghidra.util.layout.PairLayout;
public class CreateBookmarkDialog extends DialogComponentProvider {
@@ -43,27 +42,26 @@ public class CreateBookmarkDialog extends DialogComponentProvider {
private Program program;
private Address address;
- private JTextField locationTextField;
- private JComboBox<String> categoryComboBox;
- private JTextField categoryTextField;
- private JTextField commentTextField;
+ private GhidraComboBox<String> categoryComboBox;
+ private JTextField descriptionTextField;
private JCheckBox selectionCB;
+ private boolean hasSelection;
CreateBookmarkDialog(BookmarkPlugin plugin, CodeUnit cu, boolean hasSelection) {
super(BookmarkType.NOTE + " Bookmark", true, true, true, false);
this.plugin = plugin;
+ this.hasSelection = hasSelection;
this.program = plugin.getCurrentProgram();
this.address = cu.getMinAddress();
- this.addWorkPanel(buildWorkPanel(hasSelection));
+ this.addWorkPanel(buildMainPanel());
this.addOKButton();
this.addCancelButton();
- this.populateDisplay(cu.getComment(CodeUnit.EOL_COMMENT));
+ initializeDescription(cu);
- commentTextField.selectAll();
- setFocusComponent(commentTextField);
+ setFocusComponent(categoryComboBox);
setHelpLocation(new HelpLocation("BookmarkPlugin", "CreateBookmarkDialog"));
}
@@ -78,9 +76,8 @@ public class CreateBookmarkDialog extends DialogComponentProvider {
@Override
protected void okCallback() {
- JTextField textField = (JTextField) categoryComboBox.getEditor().getEditorComponent();
- String cat = textField.getText();
- String com = commentTextField.getText();
+ String cat = categoryComboBox.getText();
+ String com = descriptionTextField.getText();
// Create user Note Bookmark
if (selectionCB.isSelected()) {
@@ -93,127 +90,65 @@ public class CreateBookmarkDialog extends DialogComponentProvider {
cancelCallback();
}
- private JPanel buildWorkPanel(boolean hasSelection) {
- KeyListener listener = new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.getKeyCode() == KeyEvent.VK_ENTER) {
- Object src = e.getSource();
- if (src == locationTextField) {
- categoryComboBox.requestFocus();
- categoryTextField.requestFocus();
- }
- else if (src == categoryComboBox || src == categoryTextField) {
- commentTextField.requestFocus();
- }
- else if (src == commentTextField) {
- okCallback();
- }
- }
- }
- };
-
- // Some items in the dialog change depending on whether we have multiple selection
- // ranges, so capture that information here.
- int ranges = 0;
- if (hasSelection) {
- ranges = plugin.getProgramSelection().getNumAddressRanges();
- }
+ private JPanel buildMainPanel() {
+ JPanel panel = new JPanel(new BorderLayout());
+ panel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 10));
+ panel.add(buildIconLabel(), BorderLayout.WEST);
+ panel.add(buildCentralPanel(), BorderLayout.CENTER);
+ panel.add(buildCheckboxPanel(), BorderLayout.SOUTH);
- locationTextField = new JTextField(50);
- locationTextField.setText(address.toString());
- if (hasSelection && ranges > 1) {
- locationTextField.setText(address.toString() + " (plus " + (ranges - 1) + " more)");
- }
- locationTextField.setCaretPosition(0);
- locationTextField.setEditable(false);
- DockingUtils.setTransparent(locationTextField);
- locationTextField.setMinimumSize(locationTextField.getPreferredSize());
- locationTextField.addKeyListener(listener);
+ return panel;
+ }
+
+ private JPanel buildCheckboxPanel() {
+ selectionCB = new GCheckBox("Bookmark Top of Each Selection", hasSelection);
+ selectionCB.setEnabled(getSelectionRangeCount() > 1);
+ JPanel panel = new JPanel();
+ panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
+ panel.add(selectionCB);
+ return panel;
+ }
+
+ private Component buildCentralPanel() {
+ JPanel panel = new JPanel(new PairLayout(3, 5));
categoryComboBox = new GhidraComboBox<>(getModel());
categoryComboBox.setEditable(true);
- categoryComboBox.addKeyListener(listener);
+ descriptionTextField = new JTextField(20);
- categoryTextField = (JTextField) categoryComboBox.getEditor().getEditorComponent();
- categoryTextField.addKeyListener(listener);
+ panel.add(new JLabel("Address: ", SwingConstants.RIGHT));
+ panel.add(new GLabel(buildLocationString()));
- commentTextField = new JTextField(20);
- commentTextField.addKeyListener(listener);
+ panel.add(new JLabel("Category: ", SwingConstants.RIGHT));
+ panel.add(categoryComboBox);
- selectionCB = new GCheckBox("Bookmark Top of Each Selection", hasSelection);
- selectionCB.setEnabled(false);
- if (hasSelection) {
- selectionCB.setEnabled(ranges > 1);
- }
+ panel.add(new JLabel("Description: ", SwingConstants.RIGHT));
+ panel.add(descriptionTextField);
- JPanel mainPanel = new JPanel(new GridBagLayout());
- GridBagConstraints gbc = new GridBagConstraints();
- gbc.insets = new Insets(5, 5, 0, 5);
-
- gbc.gridx = 1;
- gbc.gridy = 1;
- gbc.weightx = 0;
- gbc.weighty = 0;
- gbc.fill = GridBagConstraints.NONE;
- gbc.anchor = GridBagConstraints.EAST;
- mainPanel.add(new GLabel("Category: ", SwingConstants.RIGHT), gbc);
-
- gbc.gridx = 2;
- gbc.gridy = 1;
- gbc.weightx = 0;
- gbc.weighty = 0;
- gbc.fill = GridBagConstraints.HORIZONTAL;
- gbc.anchor = GridBagConstraints.WEST;
- mainPanel.add(categoryComboBox, gbc);
-
- gbc.gridx = 1;
- gbc.gridy = 0;
- gbc.weightx = 0;
- gbc.weighty = 0;
- gbc.fill = GridBagConstraints.NONE;
- gbc.anchor = GridBagConstraints.EAST;
- mainPanel.add(new GLabel("Address: ", SwingConstants.RIGHT), gbc);
-
- gbc.gridx = 2;
- gbc.gridy = 0;
- gbc.weightx = 0;
- gbc.weighty = 0;
- gbc.fill = GridBagConstraints.NONE;
- gbc.anchor = GridBagConstraints.WEST;
- mainPanel.add(locationTextField, gbc);
-
- gbc.gridx = 1;
- gbc.gridy = 2;
- gbc.weightx = 0;
- gbc.weighty = 0;
- gbc.fill = GridBagConstraints.NONE;
- gbc.anchor = GridBagConstraints.EAST;
- mainPanel.add(new GLabel("Description: ", SwingConstants.RIGHT), gbc);
-
- gbc.gridx = 2;
- gbc.gridy = 2;
- gbc.weightx = 1.0;
- gbc.weighty = 0;
- gbc.fill = GridBagConstraints.HORIZONTAL;
- gbc.anchor = GridBagConstraints.WEST;
- mainPanel.add(commentTextField, gbc);
+ return panel;
+ }
+ private String buildLocationString() {
+ int ranges = getSelectionRangeCount();
+ if (ranges > 1) {
+ return address.toString() + " (plus " + (ranges - 1) + " more)";
+ }
+ return address.toString();
+ }
+
+ private JLabel buildIconLabel() {
Icon icon = BookmarkNavigator.NOTE_ICON;
JLabel imageLabel = new GIconLabel(icon);
imageLabel.setPreferredSize(
new Dimension(icon.getIconWidth() + 20, icon.getIconHeight() + 20));
+ return imageLabel;
+ }
- JPanel selectionPanel = new JPanel();
- selectionPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
- selectionPanel.add(selectionCB);
-
- JPanel workPanel = new JPanel(new BorderLayout());
- workPanel.add(mainPanel, BorderLayout.CENTER);
- workPanel.add(imageLabel, BorderLayout.WEST);
- workPanel.add(selectionPanel, BorderLayout.SOUTH);
-
- return workPanel;
+ private int getSelectionRangeCount() {
+ if (hasSelection) {
+ return plugin.getProgramSelection().getNumAddressRanges();
+ }
+ return 0;
}
/**
@@ -230,24 +165,27 @@ public class CreateBookmarkDialog extends DialogComponentProvider {
return new DefaultComboBoxModel<>(array);
}
- private void populateDisplay(String defaultComment) {
-
- if (defaultComment == null) {
- defaultComment = "";
- }
- else {
- defaultComment = defaultComment.replace('\n', ' ');
- }
+ private void initializeDescription(CodeUnit codeUnit) {
+ String defaultComment = getEolComment(codeUnit);
BookmarkManager bmMgr = program.getBookmarkManager();
Bookmark[] bookmarks = bmMgr.getBookmarks(address, BookmarkType.NOTE);
if (bookmarks.length != 0) {
categoryComboBox.setSelectedItem(bookmarks[0].getCategory());
- commentTextField.setText(bookmarks[0].getComment());
+ descriptionTextField.setText(bookmarks[0].getComment());
}
else {
- commentTextField.setText(defaultComment);
+ descriptionTextField.setText(defaultComment);
+ }
+ descriptionTextField.setCaretPosition(0);
+ descriptionTextField.selectAll();
+ }
+
+ private String getEolComment(CodeUnit codeUnit) {
+ String comment = codeUnit.getComment(CodeUnit.EOL_COMMENT);
+ if (comment == null) {
+ return "";
}
- commentTextField.setCaretPosition(0);
+ return comment.replace('\n', ' ');
}
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldDialog.java
index 1fd8d87c95..d78110406e 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldDialog.java
@@ -19,7 +19,8 @@ import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import javax.swing.*;
+import javax.swing.BorderFactory;
+import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
@@ -30,12 +31,10 @@ import ghidra.program.model.data.DataTypeComponent;
import ghidra.program.model.listing.Program;
import ghidra.util.HelpLocation;
-
class RenameDataFieldDialog extends DialogComponentProvider {
- private JComboBox<?> recentChoices;
- private JTextField choiceTextField;
-
+ private GhidraComboBox<?> recentChoices;
+
private DataTypeComponent component;
private DataPlugin plugin;
private Program program;
@@ -54,18 +53,18 @@ class RenameDataFieldDialog extends DialogComponentProvider {
public void setDataComponent(Program program, DataTypeComponent component, String name) {
this.component = component;
this.program = program;
- choiceTextField.setText(name);
- choiceTextField.selectAll();
+ recentChoices.setText(name);
+ recentChoices.selectAll();
}
- @Override
- protected void okCallback() {
+ @Override
+ protected void okCallback() {
close();
-
- RenameDataFieldCmd cmd = new RenameDataFieldCmd(component, choiceTextField.getText());
+
+ RenameDataFieldCmd cmd = new RenameDataFieldCmd(component, recentChoices.getText());
plugin.getTool().execute(cmd, program);
program = null;
- }
+ }
@Override
protected void cancelCallback() {
@@ -73,30 +72,29 @@ class RenameDataFieldDialog extends DialogComponentProvider {
close();
}
- private JPanel create() {
+ private JPanel create() {
recentChoices = new GhidraComboBox<>();
- recentChoices.setEditable(true);
+ recentChoices.setEditable(true);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel topPanel = new JPanel(new BorderLayout());
-
+
Border border = BorderFactory.createTitledBorder("Data Field Name");
topPanel.setBorder(border);
-
+
mainPanel.add(topPanel, BorderLayout.NORTH);
topPanel.add(recentChoices, BorderLayout.NORTH);
- choiceTextField = (JTextField)recentChoices.getEditor().getEditorComponent();
- setFocusComponent(choiceTextField);
- choiceTextField.addActionListener(new ActionListener() {
+ setFocusComponent(recentChoices);
+ recentChoices.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okCallback();
}
- });
- mainPanel.setBorder(new EmptyBorder(5,5,5,5));
+ });
+ mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
return mainPanel;
- }
+ }
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchmem/MemSearchDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchmem/MemSearchDialog.java
index c35997745d..58a48bb5a8 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchmem/MemSearchDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchmem/MemSearchDialog.java
@@ -72,7 +72,6 @@ class MemSearchDialog extends DialogComponentProvider {
private JButton nextButton;
private JButton previousButton;
private JButton allButton;
- private JTextField valueField;
private GhidraComboBox<String> valueComboBox;
private List<String> history = new LinkedList<>();
private JLabel hexSeqField;
@@ -120,11 +119,11 @@ class MemSearchDialog extends DialogComponentProvider {
}
void setBytes(byte[] bytes) {
- if (valueField != null) {
- valueField.setText(null);
+ if (valueComboBox != null) {
+ valueComboBox.setText(null);
}
String convertBytesToString = NumericUtilities.convertBytesToString(bytes, " ");
- valueField.setText(convertBytesToString);
+ valueComboBox.setText(convertBytesToString);
}
void setAlignment(int alignment) {
@@ -132,7 +131,7 @@ class MemSearchDialog extends DialogComponentProvider {
}
public void setSearchText(String maskedString) {
- valueField.setText(maskedString);
+ valueComboBox.setText(maskedString);
updateDisplay();
}
@@ -196,7 +195,7 @@ class MemSearchDialog extends DialogComponentProvider {
@Override
protected void dismissCallback() {
- valueField.setText(null);
+ valueComboBox.setText(null);
hexSeqField.setText(null);
cancelCurrentTask();
close();
@@ -204,8 +203,8 @@ class MemSearchDialog extends DialogComponentProvider {
void show(ComponentProvider provider) {
clearStatusText();
- valueField.requestFocus();
- valueField.selectAll();
+ valueComboBox.requestFocus();
+ valueComboBox.selectAll();
PluginTool tool = plugin.getTool();
tool.showDialog(MemSearchDialog.this, provider);
}
@@ -256,7 +255,7 @@ class MemSearchDialog extends DialogComponentProvider {
if (plugin.searchOnce(new SearchInfo(searchData, 1,
searchSelectionRadioButton.isSelected(), forward, alignment, allBlocks.isSelected(),
createCodeUnitSearchInfo(), plugin.createTaskListener()))) {
- addToHistory(valueField.getText());
+ addToHistory(valueComboBox.getText());
setStatusText("Searching...");
isSearching = true;
updateSearchButtonEnablement();
@@ -284,7 +283,7 @@ class MemSearchDialog extends DialogComponentProvider {
if (plugin.searchAll(new SearchAllSearchInfo(searchData, plugin.getSearchLimit(),
searchSelectionRadioButton.isSelected(), true, alignment, allBlocks.isSelected(),
createCodeUnitSearchInfo()))) {
- addToHistory(valueField.getText());
+ addToHistory(valueComboBox.getText());
setStatusText("Searching...");
isSearching = true;
updateSearchButtonEnablement();
@@ -307,11 +306,9 @@ class MemSearchDialog extends DialogComponentProvider {
inputPanel.setLayout(new GridLayout(0, 1));
valueComboBox = new GhidraComboBox<>();
valueComboBox.setEditable(true);
-
- valueField = (JTextField) valueComboBox.getEditor().getEditorComponent();
- valueField.setToolTipText(currentFormat.getToolTip());
- valueField.setDocument(new RestrictedInputDocument());
- valueField.addActionListener(ev -> {
+ valueComboBox.setToolTipText(currentFormat.getToolTip());
+ valueComboBox.setDocument(new RestrictedInputDocument());
+ valueComboBox.addActionListener(ev -> {
if (nextButton.isEnabled()) {
nextPreviousCallback(true);
}
@@ -666,17 +663,17 @@ class MemSearchDialog extends DialogComponentProvider {
setEndianEnabled(currentFormat.usesEndieness());
updateSearchButtonEnablement();
- valueField.setToolTipText(currentFormat.getToolTip());
+ valueComboBox.setToolTipText(currentFormat.getToolTip());
}
private void updateSearchData() {
currentFormat.setEndieness(bigEndian.isSelected());
- SearchData inputData = currentFormat.getSearchData(valueField.getText());
- if (valueField.getText().trim().length() != 0 && inputData.isValidInputData()) {
+ SearchData inputData = currentFormat.getSearchData(valueComboBox.getText());
+ if (valueComboBox.getText().trim().length() != 0 && inputData.isValidInputData()) {
updateSearchData(inputData);
}
else {
- valueField.setText("");
+ valueComboBox.setText("");
updateSearchData(DEFAULT_SEARCH_DATA);
}
}
@@ -722,8 +719,8 @@ class MemSearchDialog extends DialogComponentProvider {
String match = handleHistoryMatch(currentText, proposedText);
if (match != null) {
super.insertString(offs, match.substring(beforeOffset.length()), a);
- valueField.setSelectionStart(proposedText.length());
- valueField.setSelectionEnd(match.length());
+ valueComboBox.setSelectionStart(proposedText.length());
+ valueComboBox.setSelectionEnd(match.length());
return;
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/SearchTextDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/SearchTextDialog.java
index 0ad06f641e..d015d6a7c8 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/SearchTextDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/SearchTextDialog.java
@@ -17,13 +17,11 @@ package ghidra.app.plugin.core.searchtext;
import java.awt.*;
import java.awt.event.*;
-import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.Border;
-import javax.swing.text.*;
import docking.*;
import docking.widgets.button.GRadioButton;
@@ -50,7 +48,6 @@ class SearchTextDialog extends DialogComponentProvider {
private JButton nextButton;
private JButton previousButton;
private JButton allButton;
- private JTextField valueField;
private GhidraComboBox<String> valueComboBox;
private List<String> history = new LinkedList<>();
private JRadioButton programDatabaseSearchRB;
@@ -77,10 +74,6 @@ class SearchTextDialog extends DialogComponentProvider {
private JRadioButton allBlocksButton;
- /**
- * Constructor
- * @param plugin
- */
SearchTextDialog(SearchTextPlugin plugin) {
super("Search Program Text", false, true, true, true);
setHelpLocation(new HelpLocation(HelpTopics.SEARCH, "Search_Text"));
@@ -101,7 +94,7 @@ class SearchTextDialog extends DialogComponentProvider {
allButton.setMnemonic('a');
allButton.addActionListener(ev -> {
searchAll();
- valueField.requestFocus();
+ valueComboBox.requestFocus();
});
this.addButton(allButton);
setUseSharedLocation(true);
@@ -115,8 +108,8 @@ class SearchTextDialog extends DialogComponentProvider {
public void show(ComponentProvider componentProvider) {
clearStatusText();
- valueField.requestFocus();
- valueField.selectAll();
+ valueComboBox.requestFocus();
+ valueComboBox.selectAll();
tool.showDialog(this, componentProvider);
isBusy = false;
updateSearchButtonsEnablement();
@@ -198,16 +191,14 @@ class SearchTextDialog extends DialogComponentProvider {
valueComboBox = new GhidraComboBox<>();
valueComboBox.setEditable(true);
- valueField = (JTextField) valueComboBox.getEditor().getEditorComponent();
- valueField.setColumns(20);
- valueField.setDocument(new AutoCompleteDocument());
- valueField.addActionListener(ev -> {
+ valueComboBox.setColumns(20);
+ valueComboBox.addActionListener(ev -> {
if (nextButton.isEnabled()) {
nextPrevious(true); // go forward
- valueField.requestFocus();
+ valueComboBox.requestFocus();
}
});
- valueField.addKeyListener(new KeyAdapter() {
+ valueComboBox.addEditorKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER) {
@@ -286,8 +277,8 @@ class SearchTextDialog extends DialogComponentProvider {
labelsCB.setToolTipText(HTMLUtilities.toHTML("Search in the Lable field"));
mnemonicsCB = new GCheckBox("Instruction Mnemonics");
- mnemonicsCB.setToolTipText(
- HTMLUtilities.toHTML("Search in the Instruction Mnemonic field"));
+ mnemonicsCB
+ .setToolTipText(HTMLUtilities.toHTML("Search in the Instruction Mnemonic field"));
operandsCB = new GCheckBox("Instruction Operands");
operandsCB.setToolTipText(HTMLUtilities.toHTML("Search in the Instruction Operand fields"));
@@ -407,10 +398,10 @@ class SearchTextDialog extends DialogComponentProvider {
loadedBlocksButton = new GRadioButton("Loaded Blocks", true);
allBlocksButton = new GRadioButton("All Blocks", false);
- loadedBlocksButton.setToolTipText(HTMLUtilities.toHTML(
- "Only searches memory blocks that are loaded in a running executable.\n " +
- "Ghidra now includes memory blocks for other data such as section headers.\n" +
- "This option exludes these OTHER (non loaded) blocks."));
+ loadedBlocksButton.setToolTipText(HTMLUtilities
+ .toHTML("Only searches memory blocks that are loaded in a running executable.\n " +
+ "Ghidra now includes memory blocks for other data such as section headers.\n" +
+ "This option exludes these OTHER (non loaded) blocks."));
allBlocksButton.setToolTipText(
"Searches all memory blocks including blocks that are not actually loaded in a running executable");
@@ -433,7 +424,7 @@ class SearchTextDialog extends DialogComponentProvider {
return;
}
- addToHistory(valueField.getText());
+ addToHistory(valueComboBox.getText());
plugin.next();
@@ -443,7 +434,7 @@ class SearchTextDialog extends DialogComponentProvider {
}
public SearchOptions getSearchOptions() {
- String value = valueField.getText();
+ String value = valueComboBox.getText();
value = StringUtilities.fixMultipleAsterisks(value);
if (searchAllRB.isSelected()) {
return new SearchOptions(value, caseSensitiveCB.isSelected(), forward,
@@ -461,7 +452,7 @@ class SearchTextDialog extends DialogComponentProvider {
* search option was selected.
*/
private boolean validate() {
- String value = valueField.getText();
+ String value = valueComboBox.getText();
if (value.length() == 0) {
setStatusText("Please enter a pattern to search for.");
return false;
@@ -492,7 +483,7 @@ class SearchTextDialog extends DialogComponentProvider {
private void searchAll() {
clearStatusText();
- addToHistory(valueField.getText());
+ addToHistory(valueComboBox.getText());
if (!validate()) {
return;
@@ -552,23 +543,6 @@ class SearchTextDialog extends DialogComponentProvider {
}
}
- private String matchHistory(String input) {
- if (input == null) {
- return null;
- }
-
- Iterator<String> itr = history.iterator();
- String ret = null;
- while (ret == null && itr.hasNext()) {
- String cur = itr.next();
- if (cur.startsWith(input)) {
- ret = cur;
- }
- }
-
- return ret;
- }
-
private void updateCombo() {
String[] list = new String[history.size()];
history.toArray(list);
@@ -586,7 +560,7 @@ class SearchTextDialog extends DialogComponentProvider {
}
public void setValueFieldText(String selectedText) {
- valueField.setText(selectedText);
+ valueComboBox.setText(selectedText);
}
public void setCurrentField(ProgramLocation textField, boolean isInstruction) {
@@ -622,35 +596,4 @@ class SearchTextDialog extends DialogComponentProvider {
dataOperandsCB.setSelected(true);
}
}
-
- public class AutoCompleteDocument extends DefaultStyledDocument {
-
- private String previousInput;
- private boolean automated = false;
-
- @Override
- public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
-
- super.insertString(offs, str, a);
- if (automated) {
- automated = false;
- }
- else {
- String input = valueField.getText();
- //If the text has changed
- if (!input.equals(previousInput)) {
- previousInput = input;
- String match = matchHistory(input);
- if (match != null && match.length() > input.length()) {
- automated = true;
- valueField.setText(match);
- valueField.setSelectionStart(input.length());
- valueField.setSelectionEnd(match.length());
- }
- }
- }
- }
-
- }
-
}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/AddEditDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/AddEditDialog.java
index c08a94aa18..614f696e60 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/AddEditDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/AddEditDialog.java
@@ -39,7 +39,6 @@ import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
import ghidra.util.HelpLocation;
import ghidra.util.Swing;
-import ghidra.util.exception.AssertException;
import ghidra.util.layout.VerticalLayout;
/**
@@ -49,8 +48,8 @@ public class AddEditDialog extends DialogComponentProvider {
private static final int MAX_RETENTION = 10;
private PluginTool tool;
private TitledBorder nameBorder;
- private JComboBox<String> labelNameChoices;
- private JComboBox<NamespaceWrapper> namespaceChoices;
+ private GhidraComboBox<String> labelNameChoices;
+ private GhidraComboBox<NamespaceWrapper> namespaceChoices;
private JCheckBox entryPointCheckBox;
private JCheckBox primaryCheckBox;
@@ -339,8 +338,7 @@ public class AddEditDialog extends DialogComponentProvider {
Namespace currentNamespace = program.getSymbolTable().getNamespace(addr);
// no symbol or not editing a function symbol
- if ((symbol == null) ||
- (symbol != null && symbol.getSymbolType() != SymbolType.FUNCTION)) {
+ if ((symbol == null) || (symbol != null && symbol.getSymbolType() != SymbolType.FUNCTION)) {
// walk the tree of namespaces and collect all of the items
for (; (currentNamespace != globalNamespace); currentNamespace =
currentNamespace.getParentNamespace()) {
@@ -377,8 +375,7 @@ public class AddEditDialog extends DialogComponentProvider {
*/
private void selectNamespace() {
if (symbol != null && symbol.getParentNamespace() != null) {
- namespaceChoices
- .setSelectedItem(new NamespaceWrapper(symbol.getParentNamespace()));
+ namespaceChoices.setSelectedItem(new NamespaceWrapper(symbol.getParentNamespace()));
return;
}
@@ -389,12 +386,12 @@ public class AddEditDialog extends DialogComponentProvider {
// functions and labels in functions will use the local namespace
if (functionSymbol != null) {
if (symbol != null && symbol.equals(functionSymbol)) {
- namespaceChoices.setSelectedItem(
- new NamespaceWrapper(functionSymbol.getParentNamespace()));
+ namespaceChoices
+ .setSelectedItem(new NamespaceWrapper(functionSymbol.getParentNamespace()));
}
else if (functionSymbol.getSource() == SourceType.DEFAULT) {
- namespaceChoices.setSelectedItem(
- new NamespaceWrapper(functionSymbol.getParentNamespace()));
+ namespaceChoices
+ .setSelectedItem(new NamespaceWrapper(functionSymbol.getParentNamespace()));
}
else { // there is a function at the current address
namespaceChoices.setSelectedItem(new NamespaceWrapper(localNamespace));
@@ -409,8 +406,8 @@ public class AddEditDialog extends DialogComponentProvider {
}
else { // not in a function
if (symbol != null) { // editing a label
- namespaceChoices.setSelectedItem(
- new NamespaceWrapper(symbol.getParentNamespace()));
+ namespaceChoices
+ .setSelectedItem(new NamespaceWrapper(symbol.getParentNamespace()));
}
else {
// use the global namespace and *not* the lowest-level namespace
@@ -473,8 +470,7 @@ public class AddEditDialog extends DialogComponentProvider {
if (s.getSymbolType() == SymbolType.FUNCTION) {
String title;
if (s.isExternal()) {
- ExternalLocation extLoc =
- program.getExternalManager().getExternalLocation(s);
+ ExternalLocation extLoc = program.getExternalManager().getExternalLocation(s);
Address fnAddr = extLoc.getAddress();
title = "Rename External Function";
if (fnAddr != null) {
@@ -597,12 +593,7 @@ public class AddEditDialog extends DialogComponentProvider {
}
private String getText() {
- Component comp = labelNameChoices.getEditor().getEditorComponent();
- if (comp instanceof JTextField) {
- JTextField textField = (JTextField) comp;
- return textField.getText().trim();
- }
- throw new AssertException("Using an uneditable JComboBox - this class must be updated.");
+ return labelNameChoices.getText();
}
public class NamespaceWrapper {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/navigation/GoToAddressLabelDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/navigation/GoToAddressLabelDialog.java
index b719261fb7..f85244722b 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/navigation/GoToAddressLabelDialog.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/navigation/GoToAddressLabelDialog.java
@@ -99,6 +99,9 @@ public class GoToAddressLabelDialog extends DialogComponentProvider implements G
/**
* Popup up the dialog in the center of the tool.
+ * @param nav the Navigatable
+ * @param addr the address
+ * @param tool the PluginTool
*/
public void show(Navigatable nav, Address addr, PluginTool tool) {
this.navigatable = nav;
@@ -156,9 +159,8 @@ public class GoToAddressLabelDialog extends DialogComponentProvider implements G
private void initializeContents() {
if (goToMemory) {
- JTextField field = (JTextField) comboBox.getEditor().getEditorComponent();
- field.selectAll();
- field.requestFocus();
+ comboBox.selectAll();
+ comboBox.requestFocus();
}
else {
comboBox.setSelectedItem(null);
@@ -167,6 +169,7 @@ public class GoToAddressLabelDialog extends DialogComponentProvider implements G
/**
* Builds the main panel for this dialog.
+ * @return the main panel for this dialog
*/
final protected JPanel buildMainPanel() {
@@ -181,9 +184,8 @@ public class GoToAddressLabelDialog extends DialogComponentProvider implements G
gbc.insets = new Insets(5, 5, 5, 5);
hyperlink = new HyperlinkComponent("<html>Enter an address, label, <a href=\"" +
- EXPRESSION_ANCHOR_NAME + "\">expression</a>, or " +
- "<a href=\"" + FILE_OFFSET_ANCHOR_NAME +
- "\">file offset</a>:");
+ EXPRESSION_ANCHOR_NAME + "\">expression</a>, or " + "<a href=\"" +
+ FILE_OFFSET_ANCHOR_NAME + "\">file offset</a>:");
HyperlinkListener hyperlinkListener = evt -> {
if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
@@ -375,12 +377,6 @@ public class GoToAddressLabelDialog extends DialogComponentProvider implements G
// JUnits
public void setText(String text) {
- try {
- Component comp = comboBox.getEditor().getEditorComponent();
- ((JTextField) comp).setText(text);
- }
- catch (Exception e) {
- throw new RuntimeException(e);
- }
+ comboBox.setText(text);
}
}
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/bookmark/BookmarkPluginTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/bookmark/BookmarkPluginTest.java
index 8ef5531737..addca1769d 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/bookmark/BookmarkPluginTest.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/bookmark/BookmarkPluginTest.java
@@ -404,7 +404,7 @@ public class BookmarkPluginTest extends AbstractGhidraHeadedIntegrationTest {
assertNotNull("Could not find the Create Bookmark dialog", d);
runSwing(() -> {
JTextField commentTextField =
- (JTextField) AbstractGenericTest.getInstanceField("commentTextField", d);
+ (JTextField) AbstractGenericTest.getInstanceField("descriptionTextField", d);
commentTextField.setText("My Comment");
JComboBox<?> categoryComboBox =
(JComboBox<?>) AbstractGenericTest.getInstanceField("categoryComboBox", d);
diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java
index 98f31f1ef3..e83ac866c7 100644
--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java
+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java
@@ -19,7 +19,8 @@ import static org.junit.Assert.*;
import java.awt.Component;
import java.awt.Container;
-import java.awt.event.*;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Random;
@@ -974,8 +975,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
}
private void searchOnce(JTextField tf) throws Exception {
- ActionListener listener = tf.getActionListeners()[0];
- runSwing(() -> listener.actionPerformed(null));
+ triggerEnter(tf);
}
private void searchBackOnce(SearchTextDialog dialog) throws Exception {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java b/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java
index 6604b66ddd..8573768bc2 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/ComponentProvider.java
@@ -383,6 +383,7 @@ public abstract class ComponentProvider implements HelpDescriptor, ActionContext
public void closeComponent() {
if (isTransient) {
removeFromTool();
+ Gui.removeThemeListener(themeListener);
}
else {
setVisible(false);
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/FindDialog.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/FindDialog.java
index 27e225abfb..52b8639c23 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/FindDialog.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/FindDialog.java
@@ -30,7 +30,6 @@ import docking.widgets.label.GLabel;
public class FindDialog extends DialogComponentProvider {
- private JTextField textField;
private GhidraComboBox<String> comboBox;
private FindDialogSearcher searcher;
@@ -74,11 +73,8 @@ public class FindDialog extends DialogComponentProvider {
comboBox.setEditable(true);
comboBox.addActionListener(e -> doSearch(true));
- ComboBoxEditor editor = comboBox.getEditor();
- textField = (JTextField) editor.getEditorComponent();
-
- textField.setColumns(20);
- textField.getDocument().addDocumentListener(new DocumentListener() {
+ comboBox.setColumns(20);
+ comboBox.addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
handleDocumentUpdate();
@@ -95,7 +91,7 @@ public class FindDialog extends DialogComponentProvider {
}
private void handleDocumentUpdate() {
- String text = textField.getText();
+ String text = comboBox.getText();
enableButtons(text.length() != 0);
}
});
@@ -104,7 +100,7 @@ public class FindDialog extends DialogComponentProvider {
// associate this label with a mnemonic key that activates the text field
findLabel.setDisplayedMnemonic(KeyEvent.VK_N);
- findLabel.setLabelFor(textField);
+ comboBox.associateLabel(findLabel);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel textPanel = new JPanel();
@@ -133,7 +129,7 @@ public class FindDialog extends DialogComponentProvider {
@Override
protected void dialogClosed() {
- textField.setText("");
+ comboBox.setText("");
}
public void next() {
@@ -152,7 +148,7 @@ public class FindDialog extends DialogComponentProvider {
clearStatusText();
boolean useRegex = regexRadioButton.isSelected();
- String searchText = textField.getText();
+ String searchText = comboBox.getText();
CursorPosition cursorPosition = searcher.getCursorPosition();
SearchLocation searchLocation =
@@ -216,7 +212,7 @@ public class FindDialog extends DialogComponentProvider {
String getText() {
if (isVisible()) {
- return textField.getText();
+ return comboBox.getText();
}
return null;
}
@@ -226,12 +222,12 @@ public class FindDialog extends DialogComponentProvider {
}
public void setSearchText(String text) {
- String searchText = text == null ? textField.getText() : text;
+ String searchText = text == null ? comboBox.getText() : text;
comboBox.setSelectedItem(searchText);
}
public String getSearchText() {
- return textField.getText();
+ return comboBox.getText();
}
public void setHistory(List<String> history) {
diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/combobox/GhidraComboBox.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/combobox/GhidraComboBox.java
index 2e86771b9e..703510cc3c 100644
--- a/Ghidra/Framework/Docking/src/main/java/docking/widgets/combobox/GhidraComboBox.java
+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/combobox/GhidraComboBox.java
@@ -15,18 +15,18 @@
*/
package docking.widgets.combobox;
-import java.awt.Component;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
+import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.ComboBoxUI;
-import javax.swing.text.*;
+import javax.swing.text.Document;
import docking.widgets.GComponent;
+import ghidra.util.Swing;
+import ghidra.util.exception.AssertException;
/**
* GhidraComboBox adds the following features:
@@ -59,12 +59,17 @@ import docking.widgets.GComponent;
* @param <E> the item type
*/
public class GhidraComboBox<E> extends JComboBox<E> implements GComponent {
- private List<ActionListener> listeners = new ArrayList<>();
+ private List<ActionListener> actionListeners = new ArrayList<>();
private List<DocumentListener> docListeners = new ArrayList<>();
+ private List<KeyListener> keyListeners = new ArrayList<>();
private boolean setSelectedFlag = false;
private boolean forwardEnter;
private Action defaultSystemEnterForwardingAction;
+ private Document document;
+ private PassThroughActionListener passThroughActionListener;
+ private PassThroughKeyListener passThroughKeyListener;
+ private PassThroughDocumentListener passThroughDocumentListener;
/**
* Default constructor.
@@ -100,42 +105,19 @@ public class GhidraComboBox<E> extends JComboBox<E> implements GComponent {
init();
}
- private void init() {
- setHTMLRenderingEnabled(false);
- if (getRenderer() instanceof JComponent) {
- GComponent.setHTMLRenderingFlag((JComponent) getRenderer(), false);
- }
- }
-
@Override
public void setUI(ComboBoxUI ui) {
super.setUI(ui);
- Object object = getEditor().getEditorComponent();
- if (object instanceof JTextField) {
- JTextField textField = (JTextField) object;
- textField.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- notifyActionListeners(e);
- }
- });
- textField.setDocument(new InterceptedInputDocument());
- textField.getDocument().addDocumentListener(new DocumentListener() {
- @Override
- public void removeUpdate(DocumentEvent e) {
- notifyRemove(e);
- }
+ // this gets called during construction and during theming changes. It always
+ // creates a new editor and any listeners or documents set on the current editor are
+ // lost. So to combat this, we install the pass through listeners here instead of
+ // in the init() method. We also reset the document if the client ever called the
+ // setDocument() method
- @Override
- public void insertUpdate(DocumentEvent e) {
- notifyInsert(e);
- }
+ installPassThroughListeners();
- @Override
- public void changedUpdate(DocumentEvent e) {
- notifyChanged(e);
- }
- });
+ if (document != null) {
+ setDocument(document);
}
// HACK ALERT: see setEnterKeyForwarding(boolean)
@@ -170,91 +152,79 @@ public class GhidraComboBox<E> extends JComboBox<E> implements GComponent {
this.forwardEnter = forwardEnter;
}
+ /**
+ * Returns the text in combobox's editor text component
+ * @return the text in combobox's editor text component
+ */
public String getText() {
- Component comp = getEditor().getEditorComponent();
- if (comp instanceof JTextField) {
- JTextField textField = (JTextField) comp;
- return textField.getText();
+ JTextField textField = getTextField();
+ return textField.getText();
+ }
+
+ /**
+ * Sets the text on the combobox's editor text component
+ * @param text the text to set
+ */
+ public void setText(String text) {
+ if (!isEditable) {
+ return;
}
- return null;
+ JTextField textField = getTextField();
+ textField.setText(text);
}
@Override
public void setSelectedItem(Object obj) {
setSelectedFlag = true;
super.setSelectedItem(obj);
- Component comp = getEditor().getEditorComponent();
- if (comp instanceof JTextField) {
- JTextField textField = (JTextField) comp;
- updateTextFieldTextForClearedSelection(textField, obj);
- textField.selectAll();
- }
+ JTextField textField = getTextField();
+ updateTextFieldTextForClearedSelection(textField, obj);
+ textField.selectAll();
setSelectedFlag = false;
}
/**
- * Sets the size of the text field editor used by this combo box, <b>if that is the type of
- * editor used</b>. By default the editor for combo boxes is a text field. This method is
- * a convenience for the user to set the number of columns on that text field, which updates
- * the preferred size of the combo box.
+ * Sets the size of the text field editor used by this combo box.
*
* @param columnCount The number of columns for the text field editor
* @see JTextField#setColumns(int)
*/
public void setColumnCount(int columnCount) {
- Component comp = getEditor().getEditorComponent();
- if (comp instanceof JTextField) {
- ((JTextField) comp).setColumns(columnCount);
- }
+ JTextField textField = getTextField();
+ textField.setColumns(columnCount);
}
/**
- * A fix for the following series of events:
- * <ol>
- * <li>The user selects an item</li>
- * <li>The user deletes the text</li>
- * <li>setSelectedItem(Object) method is called with the same item</li>
- * </ol>
+ * Selects the text in the text field editor usd by this combo box.
*
- * In that above series of steps, the text will still be empty, as the user deleted it *and*
- * the call to setSelectedItem(Object) had no effect because the base class assumed that the
- * item is already selected.
- *
- * <p>
- * This method exists to make sure, in that case, that the text of the field matches the
- * selected item.
+ * @see JTextField#selectAll()
*/
- private void updateTextFieldTextForClearedSelection(JTextField comboBoxTextField,
- Object selectedItem) {
- if (selectedItem == null) {
- return; // nothing to add to the text field
- }
-
- String text = comboBoxTextField.getText();
- String newText = selectedItem.toString();
- if (!text.equals(newText)) {
- comboBoxTextField.setText(newText);
- }
- }
-
public void selectAll() {
- Component comp = getEditor().getEditorComponent();
- if (comp instanceof JTextField) {
- JTextField textField = (JTextField) comp;
- textField.selectAll();
- }
+ JTextField textField = getTextField();
+ textField.selectAll();
}
+ /**
+ * Removes all the items from the combobox data model.
+ */
public void clearModel() {
DefaultComboBoxModel<E> model = (DefaultComboBoxModel<E>) getModel();
model.removeAllElements();
}
- public void addToModel(E obj) {
+ /**
+ * Adds the given item to the combobox's data model.
+ * @param item the item to add
+ */
+ public void addToModel(E item) {
DefaultComboBoxModel<E> model = (DefaultComboBoxModel<E>) getModel();
- model.addElement(obj);
+ model.addElement(item);
}
+ /**
+ * Adds all the given item to the combobox's data model.
+ * @param items the item to add
+ */
public void addToModel(Collection<E> items) {
DefaultComboBoxModel<E> model = (DefaultComboBoxModel<E>) getModel();
for (E e : items) {
@@ -262,55 +232,113 @@ public class GhidraComboBox<E> extends JComboBox<E> implements GComponent {
}
}
- public boolean containsItem(E obj) {
+ /**
+ * Returns true if the combobox contains the given item.
+ * @param item the item to check
+ * @return true if the combobox contains the given item.
+ */
+ public boolean containsItem(E item) {
DefaultComboBoxModel<E> model = (DefaultComboBoxModel<E>) getModel();
- return model.getIndexOf(obj) != -1;
+ return model.getIndexOf(item) != -1;
}
@Override
public void addActionListener(ActionListener l) {
- listeners.add(l);
+ actionListeners.add(l);
}
@Override
public void removeActionListener(ActionListener l) {
- listeners.remove(l);
+ actionListeners.remove(l);
}
+ /**
+ * Adds a KeyListener to the combobox's editor component.
+ * @param l the listener to add
+ */
+ public void addEditorKeyListener(KeyListener l) {
+ keyListeners.add(l);
+ }
+
+ /**
+ * Removes a KeyListener from the combobox's editor component.
+ * @param l the listener to remove
+ */
+ public void removeEditorKeyListener(KeyListener l) {
+ keyListeners.remove(l);
+ }
+
+ /**
+ * Sets document to be used by the combobox's editor component.
+ * @param document the document to be set
+ */
+ public void setDocument(Document document) {
+ this.document = document;
+ JTextField textField = getTextField();
+ textField.setDocument(document);
+ document.removeDocumentListener(passThroughDocumentListener);
+ document.addDocumentListener(passThroughDocumentListener);
+ }
+
+ /**
+ * Adds a document listener to the editor component's document.
+ * @param l the listener to add
+ */
public void addDocumentListener(DocumentListener l) {
docListeners.add(l);
}
+ /**
+ * Removes a document listener from the editor component's document
+ * @param l the listener to remove
+ */
public void removeDocumentListener(DocumentListener l) {
docListeners.remove(l);
}
- private void notifyActionListeners(ActionEvent e) {
- Iterator<ActionListener> iter = listeners.iterator();
- while (iter.hasNext()) {
- iter.next().actionPerformed(e);
- }
+ /**
+ * Sets the number of column's in the editor's component (JTextField).
+ * @param columns the number of columns to show
+ * @see JTextField#setColumns(int)
+ */
+ public void setColumns(int columns) {
+ JTextField textField = getTextField();
+ textField.setColumns(columns);
}
- private void notifyInsert(DocumentEvent e) {
- Iterator<DocumentListener> iter = docListeners.iterator();
- while (iter.hasNext()) {
- iter.next().insertUpdate(e);
- }
+ /**
+ * Convenience method for associating a label with the editor component.
+ * @param label the label to associate
+ */
+ public void associateLabel(JLabel label) {
+ JTextField textField = getTextField();
+ label.setLabelFor(textField);
}
- private void notifyChanged(DocumentEvent e) {
- Iterator<DocumentListener> iter = docListeners.iterator();
- while (iter.hasNext()) {
- iter.next().changedUpdate(e);
- }
+ /**
+ * Sets the selection start in the editor's text field.
+ * @param selectionStart the start of the selection
+ * @see JTextField#setSelectionStart(int)
+ */
+ public void setSelectionStart(int selectionStart) {
+ JTextField textField = getTextField();
+ textField.setSelectionStart(selectionStart);
}
- private void notifyRemove(DocumentEvent e) {
- Iterator<DocumentListener> iter = docListeners.iterator();
- while (iter.hasNext()) {
- iter.next().removeUpdate(e);
- }
+ /**
+ * Sets the selection end in the editor's text field.
+ * @param selectionEnd the end of the selection
+ * @see JTextField#setSelectionEnd(int)
+ */
+ public void setSelectionEnd(int selectionEnd) {
+ JTextField textField = getTextField();
+ textField.setSelectionEnd(selectionEnd);
+ }
+
+ @Override
+ public void requestFocus() {
+ JTextField textField = getTextField();
+ textField.requestFocus();
}
private String matchHistory(String input) {
@@ -331,36 +359,170 @@ public class GhidraComboBox<E> extends JComboBox<E> implements GComponent {
}
/**
- * Custom Document to perform matching of items as the user types
+ * A fix for the following series of events:
+ * <ol>
+ * <li>The user selects an item</li>
+ * <li>The user deletes the text</li>
+ * <li>setSelectedItem(Object) method is called with the same item</li>
+ * </ol>
+ *
+ * In that above series of steps, the text will still be empty, as the user deleted it *and*
+ * the call to setSelectedItem(Object) had no effect because the base class assumed that the
+ * item is already selected.
+ *
+ * <p>
+ * This method exists to make sure, in that case, that the text of the field matches the
+ * selected item.
*/
- public class InterceptedInputDocument extends DefaultStyledDocument {
+ private void updateTextFieldTextForClearedSelection(JTextField comboBoxTextField,
+ Object selectedItem) {
+ if (selectedItem == null) {
+ return; // nothing to add to the text field
+ }
- private boolean automated = false;
+ String text = comboBoxTextField.getText();
+ String newText = selectedItem.toString();
+ if (!text.equals(newText)) {
+ comboBoxTextField.setText(newText);
+ }
+ }
+
+ private void init() {
+ setHTMLRenderingEnabled(false);
+ if (getRenderer() instanceof JComponent) {
+ GComponent.setHTMLRenderingFlag((JComponent) getRenderer(), false);
+ }
+ // add our internal listener to with all the others that the pass through listener will call
+ addDocumentListener(new MatchingItemsDocumentListener());
+
+ }
+
+ private void installPassThroughListeners() {
+ JTextField textField = getTextField();
+
+ // this gets called during construction before our fields are initialized, so need to
+ // create them here
+ if (passThroughActionListener == null) {
+ passThroughActionListener = new PassThroughActionListener();
+ passThroughKeyListener = new PassThroughKeyListener();
+ passThroughDocumentListener = new PassThroughDocumentListener();
+ }
+ // make sure they are never in there more than once
+ textField.removeActionListener(passThroughActionListener);
+ textField.removeKeyListener(passThroughKeyListener);
+ textField.getDocument().removeDocumentListener(passThroughDocumentListener);
+
+ textField.addActionListener(passThroughActionListener);
+ textField.addKeyListener(passThroughKeyListener);
+ textField.getDocument().addDocumentListener(passThroughDocumentListener);
+ }
+
+ private JTextField getTextField() {
+ Object object = getEditor().getEditorComponent();
+ if (object instanceof JTextField textField) {
+ return textField;
+ }
+ throw new AssertException("Expected GhidraComboBox editor component to be a JTextField!");
+ }
+
+ /**
+ * Listener on the editor's JTextField that then calls any registered action
+ * listener on this combobox
+ */
+ private class PassThroughActionListener implements ActionListener {
- /**
- * Called before new user input is inserted into the entry text field. The super method is
- * called if the input is accepted.
- */
@Override
- public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
+ public void actionPerformed(ActionEvent e) {
+ for (ActionListener listener : actionListeners) {
+ listener.actionPerformed(e);
+ }
+ }
+ }
- super.insertString(offs, str, a);
+ /**
+ * Listener on the editor's JTextField that then calls any registered editor key
+ * listener on this combobox
+ */
+ private class PassThroughKeyListener implements KeyListener {
- if (automated) {
- automated = false;
+ @Override
+ public void keyTyped(KeyEvent e) {
+ for (KeyListener listener : keyListeners) {
+ listener.keyTyped(e);
}
- else {
- JTextField textField = (JTextField) getEditor().getEditorComponent();
+ }
- String input = textField.getText();
- String match = matchHistory(input);
- if (match != null && match.length() > input.length()) {
- automated = true;
+ @Override
+ public void keyPressed(KeyEvent e) {
+ for (KeyListener listener : keyListeners) {
+ listener.keyPressed(e);
+ }
+ }
+
+ @Override
+ public void keyReleased(KeyEvent e) {
+ for (KeyListener listener : keyListeners) {
+ listener.keyReleased(e);
+ }
+ }
+ }
+
+ /**
+ * Listener on the editor's JTextField's document that then calls any registered document
+ * listener on this combobox
+ */
+ private class PassThroughDocumentListener implements DocumentListener {
+ @Override
+ public void insertUpdate(DocumentEvent e) {
+ for (DocumentListener listener : docListeners) {
+ listener.insertUpdate(e);
+ }
+ }
+
+ @Override
+ public void removeUpdate(DocumentEvent e) {
+ for (DocumentListener listener : docListeners) {
+ listener.removeUpdate(e);
+ }
+ }
+
+ @Override
+ public void changedUpdate(DocumentEvent e) {
+ for (DocumentListener listener : docListeners) {
+ listener.changedUpdate(e);
+ }
+ }
+ }
+
+ /**
+ * Listener to perform matching of items as the user types
+ */
+ private class MatchingItemsDocumentListener implements DocumentListener {
+
+ @Override
+ public void insertUpdate(DocumentEvent e) {
+ JTextField textField = getTextField();
+ String input = textField.getText();
+ String match = matchHistory(input);
+ if (match != null && match.length() > input.length()) {
+ // Not allowed to modify textField while in the document listener call.
+ Swing.runLater(() -> {
textField.setText(match);
textField.setSelectionStart(input.length());
textField.setSelectionEnd(match.length());
- }
+ });
}
}
+
+ @Override
+ public void removeUpdate(DocumentEvent e) {
+ // do nothing
+ }
+
+ @Override
+ public void changedUpdate(DocumentEvent e) {
+ // do nothing
+ }
}
+
}