Ghidra is a software reverse engineering (SRE) framework
GP-3575 refactoring SaveState to extends a new GProperties class for more general use properties to an XML or JSon file.
ghidragonc7d261604187
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/StoredAnalyzerTimes.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/StoredAnalyzerTimes.javaindex 69f78d7338..667d462133 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/StoredAnalyzerTimes.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/StoredAnalyzerTimes.java@@ -36,22 +36,22 @@ public class StoredAnalyzerTimes implements CustomOption {private String[] names;@Override- public void readState(SaveState saveState) {+ public void readState(GProperties properties) {taskTimes.clear();- for (String taskName : saveState.getNames()) {+ for (String taskName : properties.getNames()) {if (CustomOption.CUSTOM_OPTION_CLASS_NAME_KEY.equals(taskName)) {continue; // skip this reserved key}- taskTimes.put(taskName, saveState.getLong(taskName, 0));+ taskTimes.put(taskName, properties.getLong(taskName, 0));}names = null;totalTime = null;}@Override- public void writeState(SaveState saveState) {+ public void writeState(GProperties properties) {for (String taskName : taskTimes.keySet()) {- saveState.putLong(taskName, taskTimes.get(taskName));+ properties.putLong(taskName, taskTimes.get(taskName));}}@@ -164,7 +164,7 @@ public class StoredAnalyzerTimes implements CustomOption {public static StoredAnalyzerTimes getStoredAnalyzerTimes(Program program) {Options options = program.getOptions(OPTIONS_LIST);StoredAnalyzerTimes times = (StoredAnalyzerTimes) options- .getCustomOption(StoredAnalyzerTimes.OPTION_NAME, new StoredAnalyzerTimes());+ .getCustomOption(StoredAnalyzerTimes.OPTION_NAME, new StoredAnalyzerTimes());return times.clone();}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/AddressFieldOptionsWrappedOption.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/AddressFieldOptionsWrappedOption.javaindex 6f61e05ae2..bfcc047f8b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/AddressFieldOptionsWrappedOption.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/AddressFieldOptionsWrappedOption.java@@ -1,6 +1,5 @@/* ###* 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.@@ -17,7 +16,7 @@package ghidra.app.util.viewer.field;import ghidra.framework.options.CustomOption;-import ghidra.framework.options.SaveState;+import ghidra.framework.options.GProperties;/*** An option class that allows the user to edit a related group of options pertaining to@@ -108,18 +107,18 @@ public class AddressFieldOptionsWrappedOption implements CustomOption {// Persistence//==================================================================================================@Override- public void readState(SaveState saveState) {- padWithZeros = saveState.getBoolean(PAD_WITH_ZEROS, padWithZeros);- minHexDigits = saveState.getInt(MIN_HEXL_DIGITS, minHexDigits);- rightJustify = saveState.getBoolean(RIGHT_JUSTIFY, rightJustify);- showBlockName = saveState.getBoolean(SHOW_BLOCK_NAME, showBlockName);+ public void readState(GProperties properties) {+ padWithZeros = properties.getBoolean(PAD_WITH_ZEROS, padWithZeros);+ minHexDigits = properties.getInt(MIN_HEXL_DIGITS, minHexDigits);+ rightJustify = properties.getBoolean(RIGHT_JUSTIFY, rightJustify);+ showBlockName = properties.getBoolean(SHOW_BLOCK_NAME, showBlockName);}@Override- public void writeState(SaveState saveState) {- saveState.putBoolean(PAD_WITH_ZEROS, padWithZeros);- saveState.putInt(MIN_HEXL_DIGITS, minHexDigits);- saveState.putBoolean(RIGHT_JUSTIFY, rightJustify);- saveState.putBoolean(SHOW_BLOCK_NAME, showBlockName);+ public void writeState(GProperties properties) {+ properties.putBoolean(PAD_WITH_ZEROS, padWithZeros);+ properties.putInt(MIN_HEXL_DIGITS, minHexDigits);+ properties.putBoolean(RIGHT_JUSTIFY, rightJustify);+ properties.putBoolean(SHOW_BLOCK_NAME, showBlockName);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ArrayElementWrappedOption.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ArrayElementWrappedOption.javaindex e573b5cd85..c51cbb52dd 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ArrayElementWrappedOption.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/ArrayElementWrappedOption.java@@ -1,6 +1,5 @@/* ###* 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.@@ -17,7 +16,7 @@package ghidra.app.util.viewer.field;import ghidra.framework.options.CustomOption;-import ghidra.framework.options.SaveState;+import ghidra.framework.options.GProperties;public class ArrayElementWrappedOption implements CustomOption {private static final String SHOW_MULTI_ELEMENTS_PER_LINE = "showMultiArrayElementsPerLine";@@ -56,16 +55,16 @@ public class ArrayElementWrappedOption implements CustomOption {// Persistence//==================================================================================================@Override- public void readState(SaveState saveState) {+ public void readState(GProperties properties) {showMultipleArrayElementPerLine =- saveState.getBoolean(SHOW_MULTI_ELEMENTS_PER_LINE, DEFAULT_SHOW_MULTI);- arrayElementsPerLine = saveState.getInt(ELEMENTS_PER_LINE, DEFAULT_ELEMENTS_PER_LINE);+ properties.getBoolean(SHOW_MULTI_ELEMENTS_PER_LINE, DEFAULT_SHOW_MULTI);+ arrayElementsPerLine = properties.getInt(ELEMENTS_PER_LINE, DEFAULT_ELEMENTS_PER_LINE);}@Override- public void writeState(SaveState saveState) {- saveState.putBoolean(SHOW_MULTI_ELEMENTS_PER_LINE, showMultipleArrayElementPerLine);- saveState.putInt(ELEMENTS_PER_LINE, arrayElementsPerLine);+ public void writeState(GProperties properties) {+ properties.putBoolean(SHOW_MULTI_ELEMENTS_PER_LINE, showMultipleArrayElementPerLine);+ properties.putInt(ELEMENTS_PER_LINE, arrayElementsPerLine);}public boolean showMultipleArrayElementPerLine() {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/FileOffsetFieldOptionsWrappedOption.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/FileOffsetFieldOptionsWrappedOption.javaindex a07580e5d9..517edbc34e 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/FileOffsetFieldOptionsWrappedOption.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/FileOffsetFieldOptionsWrappedOption.java@@ -16,7 +16,7 @@package ghidra.app.util.viewer.field;import ghidra.framework.options.CustomOption;-import ghidra.framework.options.SaveState;+import ghidra.framework.options.GProperties;/*** An option class that allows the user to edit a related group of options pertaining to@@ -102,14 +102,14 @@ public class FileOffsetFieldOptionsWrappedOption implements CustomOption {//Persistence//==================================================================================================@Override- public void readState(SaveState saveState) {- showFilename = saveState.getBoolean(SHOW_FILENAME, showFilename);- useHex = saveState.getBoolean(USE_HEX, useHex);+ public void readState(GProperties properties) {+ showFilename = properties.getBoolean(SHOW_FILENAME, showFilename);+ useHex = properties.getBoolean(USE_HEX, useHex);}@Override- public void writeState(SaveState saveState) {- saveState.putBoolean(SHOW_FILENAME, showFilename);- saveState.putBoolean(USE_HEX, useHex);+ public void writeState(GProperties properties) {+ properties.putBoolean(SHOW_FILENAME, showFilename);+ properties.putBoolean(USE_HEX, useHex);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/NamespaceWrappedOption.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/NamespaceWrappedOption.javaindex 4ccaa4e97a..3d5eda2083 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/NamespaceWrappedOption.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/NamespaceWrappedOption.java@@ -16,7 +16,7 @@package ghidra.app.util.viewer.field;import ghidra.framework.options.CustomOption;-import ghidra.framework.options.SaveState;+import ghidra.framework.options.GProperties;/*** An option class that allows the user to edit a related group of options pertaining to@@ -120,23 +120,23 @@ public class NamespaceWrappedOption implements CustomOption {// Persistence//==================================================================================================@Override- public void readState(SaveState saveState) {- showLocalNamespace = saveState.getBoolean(SHOW_LOCAL_NAMESPACE, showLocalNamespace);+ public void readState(GProperties properties) {+ showLocalNamespace = properties.getBoolean(SHOW_LOCAL_NAMESPACE, showLocalNamespace);showNonLocalNamespace =- saveState.getBoolean(SHOW_NON_LOCAL_NAMESPACE, showNonLocalNamespace);+ properties.getBoolean(SHOW_NON_LOCAL_NAMESPACE, showNonLocalNamespace);useLocalPrefixOverride =- saveState.getBoolean(USE_LOCAL_PREFIX_OVERRIDE, useLocalPrefixOverride);- localPrefixText = saveState.getString(LOCAL_PREFIX, localPrefixText);+ properties.getBoolean(USE_LOCAL_PREFIX_OVERRIDE, useLocalPrefixOverride);+ localPrefixText = properties.getString(LOCAL_PREFIX, localPrefixText);showLibraryInNamespace =- saveState.getBoolean(SHOW_LIBRARY_IN_NAMESPACE, DEFAULT_SHOW_LIBRARY_IN_NAMESPACE);+ properties.getBoolean(SHOW_LIBRARY_IN_NAMESPACE, DEFAULT_SHOW_LIBRARY_IN_NAMESPACE);}@Override- public void writeState(SaveState saveState) {- saveState.putBoolean(SHOW_LOCAL_NAMESPACE, showLocalNamespace);- saveState.putBoolean(SHOW_NON_LOCAL_NAMESPACE, showNonLocalNamespace);- saveState.putBoolean(USE_LOCAL_PREFIX_OVERRIDE, useLocalPrefixOverride);- saveState.putString(LOCAL_PREFIX, localPrefixText);- saveState.putBoolean(SHOW_LIBRARY_IN_NAMESPACE, showLibraryInNamespace);+ public void writeState(GProperties properties) {+ properties.putBoolean(SHOW_LOCAL_NAMESPACE, showLocalNamespace);+ properties.putBoolean(SHOW_NON_LOCAL_NAMESPACE, showNonLocalNamespace);+ properties.putBoolean(USE_LOCAL_PREFIX_OVERRIDE, useLocalPrefixOverride);+ properties.putString(LOCAL_PREFIX, localPrefixText);+ properties.putBoolean(SHOW_LIBRARY_IN_NAMESPACE, showLibraryInNamespace);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/util/ManualViewerCommandWrappedOption.java b/Ghidra/Features/Base/src/main/java/ghidra/util/ManualViewerCommandWrappedOption.javaindex 9da9feac8f..2c1db880cd 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/util/ManualViewerCommandWrappedOption.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/util/ManualViewerCommandWrappedOption.java@@ -18,7 +18,7 @@ package ghidra.util;import ghidra.framework.OperatingSystem;import ghidra.framework.Platform;import ghidra.framework.options.CustomOption;-import ghidra.framework.options.SaveState;+import ghidra.framework.options.GProperties;public class ManualViewerCommandWrappedOption implements CustomOption {public static final String OPTIONS_CATEGORY_NAME = "Processor Manuals";@@ -44,17 +44,17 @@ public class ManualViewerCommandWrappedOption implements CustomOption {}@Override- public void readState(SaveState saveState) {- commandString = saveState.getString(COMMAND_STRING, null);- commandArguments = saveState.getStrings(COMMAND_ARGUMENTS, null);- urlReplacementString = saveState.getString(URL_STRING, null);+ public void readState(GProperties properties) {+ commandString = properties.getString(COMMAND_STRING, null);+ commandArguments = properties.getStrings(COMMAND_ARGUMENTS, null);+ urlReplacementString = properties.getString(URL_STRING, null);}@Override- public void writeState(SaveState saveState) {- saveState.putString(COMMAND_STRING, commandString);- saveState.putStrings(COMMAND_ARGUMENTS, commandArguments);- saveState.putString(URL_STRING, urlReplacementString);+ public void writeState(GProperties properties) {+ properties.putString(COMMAND_STRING, commandString);+ properties.putStrings(COMMAND_ARGUMENTS, commandArguments);+ properties.putString(URL_STRING, urlReplacementString);}@Overridediff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/data/OptionsDBTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/data/OptionsDBTest.javaindex e48a7012e2..9df103ea09 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/framework/data/OptionsDBTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/data/OptionsDBTest.java@@ -303,8 +303,7 @@ public class OptionsDBTest extends AbstractDockingTest {@Testpublic void testRegisterPropertyEditor() {MyPropertyEditor editor = new MyPropertyEditor();- options.registerOption("foo", OptionType.INT_TYPE, 5, null, "description",- editor);+ options.registerOption("foo", OptionType.INT_TYPE, 5, null, "description", editor);assertEquals(editor, options.getRegisteredPropertyEditor("foo"));}@@ -621,13 +620,13 @@ public class OptionsDBTest extends AbstractDockingTest {}@Override- public void readState(SaveState saveState) {- value = saveState.getInt("VALUE", 0);+ public void readState(GProperties properties) {+ value = properties.getInt("VALUE", 0);}@Override- public void writeState(SaveState saveState) {- saveState.putInt("VALUE", value);+ public void writeState(GProperties properties) {+ properties.putInt("VALUE", value);}@Overridediff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/FileOptionsTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/FileOptionsTest.javaindex 5c327725d8..372bfc7584 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/FileOptionsTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/FileOptionsTest.java@@ -24,7 +24,6 @@ import java.io.IOException;import org.junit.Test;import generic.test.AbstractGenericTest;-import generic.theme.GThemeDefaults.Colors.Palette;public class FileOptionsTest extends AbstractGenericTest {@@ -76,17 +75,17 @@ public class FileOptionsTest extends AbstractGenericTest {}@Override- public void readState(SaveState saveState) {- name = saveState.getString("name", null);- count = saveState.getInt("count", 0);- active = saveState.getBoolean("active", false);+ public void readState(GProperties properties) {+ name = properties.getString("name", null);+ count = properties.getInt("count", 0);+ active = properties.getBoolean("active", false);}@Override- public void writeState(SaveState saveState) {- saveState.putString("name", name);- saveState.putInt("count", count);- saveState.putBoolean("active", active);+ public void writeState(GProperties properties) {+ properties.putString("name", name);+ properties.putInt("count", count);+ properties.putBoolean("active", active);}@Overridediff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/GPropertiesTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/GPropertiesTest.javanew file mode 100644index 0000000000..b689fa305c--- /dev/null+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/GPropertiesTest.java@@ -0,0 +1,641 @@+/* ###+ * 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.framework.options;++import static org.junit.Assert.*;++import java.awt.Color;+import java.awt.Font;+import java.io.*;+import java.util.Arrays;+import java.util.Date;++import javax.swing.KeyStroke;++import org.jdom.Document;+import org.jdom.Element;+import org.jdom.input.SAXBuilder;+import org.jdom.output.XMLOutputter;+import org.junit.Before;+import org.junit.Test;++import com.google.gson.JsonObject;++import generic.test.AbstractGenericTest;+import generic.theme.GThemeDefaults.Colors.Palette;+import ghidra.app.plugin.core.overview.addresstype.AddressType;+import ghidra.program.model.lang.Endian;+import ghidra.util.xml.GenericXMLOutputter;+import ghidra.util.xml.XmlUtilities;++public class GPropertiesTest extends AbstractGenericTest {++ private GProperties properties;++ @Before+ public void setUp() {+ properties = new GProperties("foo");+ }++ @Test+ public void testString() throws Exception {+ properties.putString("TEST", null);+ String s = properties.getString("TEST", "FRED");+ assertNull(s);++ String validKey = "TEST2";+ properties.putString(validKey, "Value");+ s = properties.getString(validKey, null);+ assertNotNull(s);++ GProperties restoredState = saveAndRestoreToXml();++ String value = restoredState.getString(validKey, null);+ assertNotNull(value);+ }++ @Test+ public void testColor() throws Exception {+ properties.putColor("TEST", Palette.RED);+ Color c = properties.getColor("TEST", null);+ assertEquals(Palette.RED.getRGB(), c.getRGB());++ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ c = restoredState.getColor("TEST", null);+ assertEquals(Palette.RED.getRGB(), c.getRGB());+ }++ @Test+ public void testDate() throws Exception {+ Date date = GProperties.DATE_FORMAT.parse("2020-12-22T14:20:24-0500");+ properties.putDate("TEST", date);+ Date d = properties.getDate("TEST", null);+ assertEquals(date, d);++ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ d = restoredState.getDate("TEST", null);+ assertEquals(date, d);+ }++ @Test+ public void testFile() throws Exception {+ File file = createTempFile("myFile", "txt");+ file.deleteOnExit();+ properties.putFile("TEST", file);+ File f = properties.getFile("TEST", null);+ assertEquals(file, f);++ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ f = restoredState.getFile("TEST", null);+ assertEquals(file, f);+ }++ @Test+ public void testKeyStroke() throws Exception {+ KeyStroke keyStroke = KeyStroke.getKeyStroke("ctrl X");+ assertNotNull(keyStroke);++ properties.putKeyStroke("TEST", keyStroke);+ KeyStroke k = properties.getKeyStroke("TEST", null);+ assertEquals(keyStroke, k);++ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ k = restoredState.getKeyStroke("TEST", null);+ assertEquals(keyStroke, k);+ }++ @Test+ public void testFont() throws Exception {+ Font font = Font.decode("Dialog-BOLD-12");+ properties.putFont("TEST", font);+ Font f = properties.getFont("TEST", null);+ assertEquals(font, f);++ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ f = restoredState.getFont("TEST", null);+ assertEquals(font, f);+ }++ @Test+ public void testSubGProperties() throws Exception {+ GProperties subState = new GProperties("sub");+ subState.putInt("a", 5);+ subState.putString("foo", "bar");++ properties.putGProperties("TEST", subState);+ properties.putString("xxx", "zzzz");+ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ assertEquals("zzzz", restoredState.getString("xxx", null));+ GProperties restoredSub = restoredState.getGProperties("TEST");+ assertEquals(2, restoredSub.getNames().length);+ assertEquals(5, restoredSub.getInt("a", 0));+ assertEquals("bar", restoredSub.getString("foo", ""));+ }++ private GProperties saveAndRestoreToXml() throws Exception {+ // persist the state+ File saveFileTemp = createTempFile("xmlTest");+ Element element = properties.saveToXml();+ saveElement(element, saveFileTemp);++ // read in the state+ InputStream is = new FileInputStream(saveFileTemp);+ SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);+ Element root = sax.build(is).getRootElement();+ GProperties loadedState = new GProperties(root);+ saveFileTemp.deleteOnExit();+ return loadedState;+ }++ private void saveElement(Element element, File saveFile) throws Exception {+ OutputStream os = null;+ try {+ os = new FileOutputStream(saveFile);+ Document doc = new Document(element);+ XMLOutputter xmlout = new GenericXMLOutputter();+ xmlout.output(doc, os);+ os.close();+ }+ finally {+ if (os != null) {+ os.close();+ }+ }+ }++ @Test+ public void testStringArray() throws Exception {+ String[] array1 =+ new String[] { "Dennis", "Bill", "Brian", "Mike", null, "Ellen", "Steve" };+ String[] after = new String[] { "Dennis", "Bill", "Brian", "Mike", "Ellen", "Steve" };++ properties.putStrings("ARRAY", array1);+ String[] array2 = properties.getStrings("ARRAY", null);++ assertArrayEquals(array1, array2);++ GProperties restoredState = saveAndRestoreToXml();++ assertArrayEquals(after, restoredState.getStrings("ARRAY", null));+ }++ @Test+ public void testByte() throws Exception {+ properties.putByte("FOURTYTWO", (byte) 42);+ assertTrue(properties.hasValue("FOURTYTWO"));+ assertEquals((byte) 42, properties.getByte("FOURTYTWO", (byte) 0));+ assertTrue(!properties.hasValue("XXX"));+ assertEquals((byte) 5, properties.getByte("XXX", (byte) 5));++ GProperties restoredState = saveAndRestoreToXml();+ assertEquals((byte) 42, restoredState.getByte(("FOURTYTWO"), (byte) 0));+ }++ @Test+ public void testByteArray() throws Exception {+ byte[] array1 = new byte[] { (byte) 0, (byte) 5, (byte) 9, (byte) 42, (byte) 77 };+ properties.putBytes("ARRAY", array1);+ byte[] array2 = properties.getBytes("ARRAY", null);+ assertArrayEquals(array1, array2);++ GProperties restoredState = saveAndRestoreToXml();+ assertArrayEquals(array1, restoredState.getBytes("ARRAY", null));++ }++ @Test+ public void testShort() throws Exception {+ properties.putShort("FOURTYTWO", (short) 42);+ assertTrue(properties.hasValue("FOURTYTWO"));+ assertEquals((short) 42, properties.getShort("FOURTYTWO", (short) 0));+ assertTrue(!properties.hasValue("XXX"));+ assertEquals((short) 5, properties.getShort("XXX", (short) 5));++ GProperties restoredState = saveAndRestoreToXml();+ assertEquals((short) 42, restoredState.getShort(("FOURTYTWO"), (short) 0));+ }++ @Test+ public void testInt() throws Exception {+ properties.putInt("FOURTYTWO", 42);+ assertTrue(properties.hasValue("FOURTYTWO"));+ assertEquals(42, properties.getInt("FOURTYTWO", 0));+ assertTrue(!properties.hasValue("XXX"));+ assertEquals(5, properties.getInt("XXX", 5));++ GProperties restoredState = saveAndRestoreToXml();+ assertEquals(42, restoredState.getInt(("FOURTYTWO"), 0));+ }++ @Test+ public void testIntArray() throws Exception {+ int[] array1 = new int[] { 0, 5, 9, 42, 77 };+ properties.putInts("ARRAY", array1);+ int[] array2 = properties.getInts("ARRAY", null);+ Arrays.equals(array1, array2);++ GProperties restoredState = saveAndRestoreToXml();++ // make sure our value is inside+ int[] restoredArray = restoredState.getInts("ARRAY", null);+ Arrays.equals(array1, restoredArray);+ }++ @Test+ public void testLong() throws Exception {+ properties.putLong("FOURTYTWO", 42);+ assertTrue(properties.hasValue("FOURTYTWO"));+ assertEquals(42, properties.getLong("FOURTYTWO", 0));+ assertTrue(!properties.hasValue("XXX"));+ assertEquals(5, properties.getLong("XXX", 5));++ GProperties restoredState = saveAndRestoreToXml();+ assertEquals(42L, restoredState.getLong(("FOURTYTWO"), 0));+ }++ @Test+ public void testFloat() throws Exception {+ properties.putFloat("PI", (float) 3.14159);+ assertTrue(properties.hasValue("PI"));+ assertEquals((float) 3.14159, properties.getFloat("PI", (float) 0.0), (float) 0.01);+ assertTrue(!properties.hasValue("XXX"));+ assertEquals(5, properties.getFloat("XXX", 5), (float) 0.01);++ GProperties restoredState = saveAndRestoreToXml();+ assertEquals(3.14159, restoredState.getFloat(("PI"), 0), 0.001f);+ }++ @Test+ public void testDouble() throws Exception {+ properties.putDouble("PI", 3.14159);+ assertTrue(properties.hasValue("PI"));+ assertEquals(3.14159, properties.getDouble("PI", 0.0), 0.01);+ assertTrue(!properties.hasValue("XXX"));+ assertEquals(5, properties.getDouble("XXX", 5), 0.01);++ GProperties restoredState = saveAndRestoreToXml();+ assertEquals(3.14159, restoredState.getDouble(("PI"), 0), 0.000001);+ }++ @Test+ public void testSome() {+ properties.putDouble("PI", 3.14159);+ properties.putByte("BYTE", (byte) 0xEE);+ properties.putLong("LONG", 65536);+ properties.putString("STRING", "See Jane Run");+ properties.putBoolean("BOOL_A", false);+ properties.putBoolean("BOOL_B", true);++ assertEquals(3.1459, properties.getDouble("PI", 0.0), 0.01);+ assertEquals("See Jane Run", properties.getString("STRING", "BOB"));+ assertEquals(true, properties.getBoolean("BOOL_B", false));+ assertEquals((byte) 0xEE, properties.getByte("BYTE", (byte) 0));+ assertEquals(false, properties.getBoolean("BOOL_A", true));+ }++ @Test+ public void testXML() {+ Element elem1 = new Element("ELEM_1");+ Element elem2 = new Element("ELEM_2");+ elem1.setAttribute("NAME", "VALUE");+ elem1.addContent(elem2);+ properties.putXmlElement("XML", elem1);+ Element elem3 = properties.getXmlElement("XML");+ Element elem4 = (Element) elem3.getChildren().get(0);+ assertEquals(elem1, elem3);+ assertEquals(elem1.getName(), elem3.getName());+ assertEquals(elem2, elem4);+ assertEquals(elem2.getName(), elem4.getName());+ }++ @Test+ public void testXMLEntityEscapingForSCR_4675() throws Exception {+ String stringWithGreaterThanAndLessThan =+ "The following statement is true: 1 < 3 > 2 " + "with some trailing text";+ String greaterThanLessThanKey = "GT_LT_KEY";+ properties.putString(greaterThanLessThanKey, stringWithGreaterThanAndLessThan);++ String stringWithLargeHexDigit =+ "The following is a large hex digit: \u0128, \u0132, \307 and \253 \uD835\uDCC8 " ++ "with some trailing text ÿ";+ String hexDigitKey = "HEX_DIGIT_KEY";+ properties.putString(hexDigitKey, stringWithLargeHexDigit);++ String stringWithAmpersandApostropheAndQuote = "That is the Jones' \"love & happiness\".";+ String ampersandApostropheQuoteKey = "AMP_APOS_KEY";+ properties.putString(ampersandApostropheQuoteKey, stringWithAmpersandApostropheAndQuote);++ // persist the state+ File saveFileTemp = null;+ Element root = null;+ try {+ saveFileTemp = createTempFile("xmlTest");+ Element element = properties.saveToXml();+ saveElement(element, saveFileTemp);++ // read in the state+ InputStream is = new FileInputStream(saveFileTemp);+ SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);+ root = sax.build(is).getRootElement();+ }+ catch (Exception e) {+ throw e;+ }+ finally {+ if (saveFileTemp != null) {+ saveFileTemp.delete();+ }+ }++ // make sure our value is the same as we put in (no escaped entities)+ GProperties loadedState = new GProperties(root);+ String value = loadedState.getString(greaterThanLessThanKey, null);+ assertNotNull(value);+ assertEquals("The XML string saved with special characters was not read in correctly",+ stringWithGreaterThanAndLessThan, value);++ value = loadedState.getString(hexDigitKey, null);+ assertNotNull(value);+ assertEquals("The XML string saved with special characters was not read in correctly",+ stringWithLargeHexDigit, value);++ value = loadedState.getString(ampersandApostropheQuoteKey, null);+ assertNotNull(value);+ assertEquals("The XML string saved with special characters was not read in correctly",+ stringWithAmpersandApostropheAndQuote, value);+ }++ @Test+ public void testIsEmpty() {+ assertTrue(properties.isEmpty());+ properties.putBoolean("BOOL", false);+ assertTrue(!properties.isEmpty());+ }++ @Test+ public void testFileInputOutput() throws IOException {+ properties.putBoolean("B1", true);+ properties.putInt("I1", 7);+ properties.putString("S1", "Hey There");+ File file = createTempFile("GPropertiesTest", "xml");+ properties.saveToXmlFile(file);++ GProperties ss2 = new XmlProperties(file);+ assertEquals(true, ss2.getBoolean("B1", false));+ assertEquals(7, ss2.getInt("I1", 1));+ assertEquals("Hey There", ss2.getString("S1", ""));+ file.delete();+ }++ @Test+ public void testJsonStringRoundTrip() {+ properties.putString("foo", "Hey");+ GProperties restored = jsonRoundTrip(properties);+ assertEquals("Hey", restored.getString("foo", "there"));+ }++ @Test+ public void testJsonColorRoundTrip() {+ properties.putColor("foo", Palette.BLUE);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(Palette.BLUE.getRGB(), restored.getColor("foo", null).getRGB());+ }++ @Test+ public void testJsonDatRoundTrip() throws Exception {+ Date date = GProperties.DATE_FORMAT.parse("2020-12-22T14:20:24-0500");+ properties.putDate("foo", date);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(date, restored.getDate("foo", null));+ }++ @Test+ public void testJsonFileRoundTrip() throws IOException {+ File file = createTempFile("myFile", "txt");+ properties.putFile("foo", file);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(file, restored.getFile("foo", null));+ file.deleteOnExit();+ }++ @Test+ public void testJsonKeyStrokRoundTrip() {+ KeyStroke keyStroke = KeyStroke.getKeyStroke("ctrl X");+ assertNotNull(keyStroke);++ properties.putKeyStroke("foo", keyStroke);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(keyStroke, restored.getKeyStroke("foo", null));+ }++ @Test+ public void testJsonFontRoundTrip() {+ Font font = Font.decode("Dialog-BOLD-12");+ properties.putFont("foo", font);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(font, restored.getFont("foo", null));+ }++ @Test+ public void testJsonSubGPropertiesRoundTrip() {+ GProperties subState = new GProperties("sub");+ subState.putInt("a", 5);+ subState.putString("foo", "bar");+ properties.putGProperties("foo", subState);+ properties.putString("bar", "xyz");++ GProperties restored = jsonRoundTrip(properties);+ assertEquals("xyz", restored.getString("bar", null));+ GProperties restoredSub = restored.getGProperties("foo");+ assertEquals(2, restoredSub.getNames().length);+ assertEquals(5, restoredSub.getInt("a", 0));+ assertEquals("bar", restoredSub.getString("foo", ""));+ }++ @Test+ public void testJsonByteRoundTrip() {+ properties.putByte("foo", (byte) 42);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals((byte) 42, restored.getByte("foo", (byte) 0));+ }++ @Test+ public void testJsonShortRoundTrip() {+ properties.putShort("foo", (short) 42);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals((short) 42, restored.getShort("foo", (short) 0));+ }++ @Test+ public void testJsonIntRoundTrip() {+ properties.putInt("foo", 123456789);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(123456789, restored.getInt("foo", 0));+ }++ @Test+ public void testJsonLongRoundTrip() {+ properties.putLong("foo", 12345678901234L);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(12345678901234L, restored.getLong("foo", 0));+ }++ @Test+ public void testJsonFloatRoundTrip() {+ properties.putFloat("foo", 12.123f);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(12.123f, restored.getFloat("foo", 0), 0.0001f);+ }++ @Test+ public void testJsonDoubleRoundTrip() {+ properties.putDouble("foo", 12.123456);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(12.123456, restored.getDouble("foo", 0), 0.00000001);+ }++ @Test+ public void testJsonBooleanRoundTrip() {+ properties.putBoolean("foo", true);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(true, restored.getBoolean("foo", false));+ }++ @Test+ public void testJsonStringArrayRoundTrip() {+ String[] strings = new String[] { "aaa", "bbb", null, "ccc" };+ String[] after = new String[] { "aaa", "bbb", "ccc" };+ properties.putStrings("foo", strings);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(after, restored.getStrings("foo", null));+ }++ @Test+ public void testJsonByteArrayRoundTrip() {+ byte[] bytes = new byte[] { (byte) 1, (byte) 2, (byte) 3 };+ properties.putBytes("foo", bytes);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(bytes, restored.getBytes("foo", null));+ }++ @Test+ public void testJsonShortArrayRoundTrip() {+ short[] shorts = new short[] { (short) 1, (short) 2, (short) 3 };+ properties.putShorts("foo", shorts);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(shorts, restored.getShorts("foo", null));+ }++ @Test+ public void testJsonIntArrayRoundTrip() {+ int[] ints = new int[] { 1, 2, 3, 4, 5 };+ properties.putInts("foo", ints);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(ints, restored.getInts("foo", null));+ }++ @Test+ public void testJsonLongArrayRoundTrip() {+ long[] longs = new long[] { 1, 2, 3, 4, 5 };+ properties.putLongs("foo", longs);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(longs, restored.getLongs("foo", null));+ }++ @Test+ public void testJsonFloatArrayRoundTrip() {+ float[] floats = new float[] { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f };+ properties.putFloats("foo", floats);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(floats, restored.getFloats("foo", null), .1f);+ }++ @Test+ public void testJsonDoubleArrayRoundTrip() {+ double[] doubles = new double[] { 1.1, 2.2, 3.3, 4.4, 5.5 };+ properties.putDoubles("foo", doubles);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(doubles, restored.getDoubles("foo", null), .1);+ }++ @Test+ public void testJsonBooleanArrayRoundTrip() {+ boolean[] booleans = new boolean[] { true, false, true, true, false };+ properties.putBooleans("foo", booleans);+ GProperties restored = jsonRoundTrip(properties);+ assertArrayEquals(booleans, restored.getBooleans("foo", null));+ }++ @Test+ public void testJsonEnumRoundTrip() {+ properties.putEnum("foo", AddressType.FUNCTION);+ GProperties restored = jsonRoundTrip(properties);+ assertEquals(AddressType.FUNCTION, restored.getEnum("foo", null));+ }++ @Test+ public void testJsonXmlRoundTrip() {+ Element element = new Element("ABC");+ element.setAttribute("AAA", "aaa");+ element.setAttribute("BBB", "bbb");+ element.setAttribute("CCC", "ccc");+ properties.putXmlElement("Foo", element);+ GProperties restored = jsonRoundTrip(properties);+ Element restoredElement = restored.getXmlElement("Foo");+ assertEquals("aaa", restoredElement.getAttributeValue("AAA"));+ assertEquals("bbb", restoredElement.getAttributeValue("BBB"));+ assertEquals("ccc", restoredElement.getAttributeValue("CCC"));+ }++ private GProperties jsonRoundTrip(GProperties GProperties) {+ JsonObject saveToJason = GProperties.saveToJson();+ return new GProperties(saveToJason);+ }++ @Test+ public void testJsonFullRountTripThoughFile() throws IOException {+ properties.putString("Name", "Bob");+ properties.putBoolean("Retired", true);+ properties.putInt("Age", 65);+ properties.putEnum("Endian", Endian.BIG);+ int[] ints = new int[] { 90, 95, 82, 93 };+ properties.putInts("grades", ints);++ File file = createTempFile("GPropertiesTest", "json");+ properties.saveToJsonFile(file);+ GProperties restoredGProperties = new JSonProperties(file);++ assertEquals("Bob", restoredGProperties.getString("Name", ""));+ assertEquals(true, restoredGProperties.getBoolean("Retired", false));+ assertEquals(65, restoredGProperties.getInt("Age", 0));+ assertEquals(Endian.BIG, restoredGProperties.getEnum("Endian", Endian.LITTLE));+ assertArrayEquals(ints, restoredGProperties.getInts("grades", null));++ }++}diff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionTypeTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionTypeTest.javaindex 34cab00442..e10107bea4 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionTypeTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionTypeTest.java@@ -186,15 +186,15 @@ public class OptionTypeTest extends AbstractGenericTest {}@Override- public void readState(SaveState saveState) {- a = saveState.getInt("a", 0);- b = saveState.getString("b", null);+ public void readState(GProperties properties) {+ a = properties.getInt("a", 0);+ b = properties.getString("b", null);}@Override- public void writeState(SaveState saveState) {- saveState.putInt("a", a);- saveState.putString("b", b);+ public void writeState(GProperties properties) {+ properties.putInt("a", a);+ properties.putString("b", b);}}diff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionsTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionsTest.javaindex a5c2ce56ac..3b627130c3 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionsTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/OptionsTest.java@@ -67,7 +67,7 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testDefaultsNotSaved() {- options.registerOption("Foo", 5, null, null);+ options.registerOption("Foo", 5, null, "foo");assertTrue(options.contains("Foo"));assertEquals(5, options.getInt("Foo", 0));saveAndRestoreOptions();@@ -198,7 +198,7 @@ public class OptionsTest extends AbstractGuiTest {options.setInt("Foo", 3);options.setColor("COLOR", Palette.RED);options.getLong("LONG", 10);- options.registerOption("Bar", true, null, null);+ options.registerOption("Bar", true, null, "foo");Options optionsCopy = options.copy();assertTrue(optionsCopy.contains("Foo"));assertTrue(optionsCopy.contains("COLOR"));@@ -287,7 +287,7 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testGetDefaultValue() {- options.registerOption("Foo", Color.RED, null, null);+ options.registerOption("Foo", Color.RED, null, "foo");options.setColor("Foo", Color.BLUE);assertColorsEqual(Color.BLUE, options.getColor("Foo", null));assertColorsEqual(Color.RED, (Color) options.getDefaultValue("Foo"));@@ -296,21 +296,21 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testRegisterPropertyEditor() {MyPropertyEditor editor = new MyPropertyEditor();- options.registerOption("color", OptionType.COLOR_TYPE, Color.RED, null, null, editor);+ options.registerOption("color", OptionType.COLOR_TYPE, Color.RED, null, "foo", editor);assertEquals(editor, options.getRegisteredPropertyEditor("color"));}@Testpublic void testGetHelpLocation() {HelpLocation helpLocation = new HelpLocation("topic", "anchor");- options.registerOption("Foo", 3, helpLocation, null);+ options.registerOption("Foo", 3, helpLocation, "foo");assertEquals(helpLocation, options.getHelpLocation("Foo"));}@Testpublic void testRestoreOptionValue() {- options.registerOption("Foo", Color.RED, null, null);+ options.registerOption("Foo", Color.RED, null, "foo");options.setColor("Foo", Color.BLUE);assertColorsEqual(Color.BLUE, options.getColor("Foo", null));@@ -378,16 +378,16 @@ public class OptionsTest extends AbstractGuiTest {assertTrue(!options.isRegistered("Bar"));assertTrue(!options.isRegistered("aaa"));- options.registerOption("aaa", 3, null, null);+ options.registerOption("aaa", 3, null, "foo");assertTrue(options.isRegistered("aaa"));}@Testpublic void testRestoreDefaults() {- options.registerOption("Foo", 10, null, null);+ options.registerOption("Foo", 10, null, "foo");options.setInt("Foo", 2);- options.registerOption("Bar", 100, null, null);+ options.registerOption("Bar", 100, null, "foo");options.setInt("Bar", 1);options.restoreDefaultValues();assertEquals(10, options.getInt("Foo", 0));@@ -423,7 +423,7 @@ public class OptionsTest extends AbstractGuiTest {assertTrue(options.contains("Foo"));assertTrue(options.contains("Bar"));- options.registerOption("Bar", 0, null, null);+ options.registerOption("Bar", 0, null, "foo");options.removeUnusedOptions();@@ -527,7 +527,7 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testGetDefaultValueAsString() {- options.registerOption("foo", 7, null, null);+ options.registerOption("foo", 7, null, "foo");options.setInt("foo", 5);assertEquals("7", options.getDefaultValueAsString("foo"));assertNull(options.getDefaultValueAsString("bar"));@@ -536,7 +536,7 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testResgisteringOptionWithNullValue() {try {- options.registerOption("Foo", null, null, null);+ options.registerOption("Foo", null, null, "foo");Assert.fail("Should not be able to register an options with a default value");}catch (IllegalArgumentException e) {@@ -547,7 +547,7 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testRegisteringOptionWithUnsupportedType() {try {- options.registerOption("Foo", new ArrayList<String>(), null, null);+ options.registerOption("Foo", new ArrayList<String>(), null, "foo");Assert.fail("Should not be able to register an options with an ArrayList as a default value");}@@ -559,7 +559,7 @@ public class OptionsTest extends AbstractGuiTest {@Testpublic void testRegisteringOptionWithTypeNone() {try {- options.registerOption("Foo", OptionType.NO_TYPE, null, null, null);+ options.registerOption("Foo", OptionType.NO_TYPE, null, null, "foo");Assert.fail("Should not be able to register an options of type NONE");}catch (IllegalArgumentException e) {@@ -643,13 +643,13 @@ public class OptionsTest extends AbstractGuiTest {}@Override- public void readState(SaveState saveState) {- value = saveState.getInt("VALUE", 0);+ public void readState(GProperties properties) {+ value = properties.getInt("VALUE", 0);}@Override- public void writeState(SaveState saveState) {- saveState.putInt("VALUE", value);+ public void writeState(GProperties properties) {+ properties.putInt("VALUE", value);}@Overridediff --git a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.javaindex 153337247d..9671f49121 100644--- a/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java+++ b/Ghidra/Features/Base/src/test/java/ghidra/framework/options/SaveStateTest.java@@ -17,633 +17,39 @@ package ghidra.framework.options;import static org.junit.Assert.*;-import java.util.Arrays;-import java.util.Date;--import java.awt.Color;-import java.awt.Font;-import java.io.*;--import javax.swing.KeyStroke;--import org.jdom.Document;import org.jdom.Element;-import org.jdom.input.SAXBuilder;-import org.jdom.output.XMLOutputter;import org.junit.Before;import org.junit.Test;-import com.google.gson.JsonObject;--import generic.test.AbstractGenericTest;-import generic.theme.GThemeDefaults.Colors.Palette;-import ghidra.app.plugin.core.overview.addresstype.AddressType;-import ghidra.program.model.lang.Endian;-import ghidra.util.xml.GenericXMLOutputter;-import ghidra.util.xml.XmlUtilities;--public class SaveStateTest extends AbstractGenericTest {-- private SaveState ss;+public class SaveStateTest {+ private SaveState saveState;@Beforepublic void setUp() {- ss = new SaveState("foo");- }-- @Test- public void testString() throws Exception {- ss.putString("TEST", null);- String s = ss.getString("TEST", "FRED");- assertNull(s);-- String validKey = "TEST2";- ss.putString(validKey, "Value");- s = ss.getString(validKey, null);- assertNotNull(s);-- SaveState restoredState = saveAndRestoreToXml();-- String value = restoredState.getString(validKey, null);- assertNotNull(value);- }-- @Test- public void testColor() throws Exception {- ss.putColor("TEST", Palette.RED);- Color c = ss.getColor("TEST", null);- assertEquals(Palette.RED.getRGB(), c.getRGB());-- SaveState restoredState = saveAndRestoreToXml();-- // make sure our value is inside- c = restoredState.getColor("TEST", null);- assertEquals(Palette.RED.getRGB(), c.getRGB());- }-- @Test- public void testDate() throws Exception {- Date date = SaveState.DATE_FORMAT.parse("2020-12-22T14:20:24-0500");- ss.putDate("TEST", date);- Date d = ss.getDate("TEST", null);- assertEquals(date, d);-- SaveState restoredState = saveAndRestoreToXml();-- // make sure our value is inside- d = restoredState.getDate("TEST", null);- assertEquals(date, d);+ saveState = new SaveState("foo");}@Test- public void testFile() throws Exception {- File file = createTempFile("myFile", "txt");- file.deleteOnExit();- ss.putFile("TEST", file);- File f = ss.getFile("TEST", null);- assertEquals(file, f);-- SaveState restoredState = saveAndRestoreToXml();-- // make sure our value is inside- f = restoredState.getFile("TEST", null);- assertEquals(file, f);- }-- @Test- public void testKeyStroke() throws Exception {- KeyStroke keyStroke = KeyStroke.getKeyStroke("ctrl X");- assertNotNull(keyStroke);-- ss.putKeyStroke("TEST", keyStroke);- KeyStroke k = ss.getKeyStroke("TEST", null);- assertEquals(keyStroke, k);-- SaveState restoredState = saveAndRestoreToXml();-- // make sure our value is inside- k = restoredState.getKeyStroke("TEST", null);- assertEquals(keyStroke, k);- }-- @Test- public void testFont() throws Exception {- Font font = Font.decode("Dialog-BOLD-12");- ss.putFont("TEST", font);- Font f = ss.getFont("TEST", null);- assertEquals(font, f);-- SaveState restoredState = saveAndRestoreToXml();-- // make sure our value is inside- f = restoredState.getFont("TEST", null);- assertEquals(font, f);- }-- @Test- public void testSubSaveState() throws Exception {+ public void testSubSaveStateToXml() throws Exception {SaveState subState = new SaveState("sub");subState.putInt("a", 5);subState.putString("foo", "bar");- ss.putSaveState("TEST", subState);- ss.putString("xxx", "zzzz");+ saveState.putSaveState("TEST", subState);+ saveState.putString("xxx", "zzzz");+SaveState restoredState = saveAndRestoreToXml();// make sure our value is insideassertEquals("zzzz", restoredState.getString("xxx", null));- SaveState restoredSub = restoredState.getSaveState("TEST");- assertEquals(2, restoredSub.getNames().length);- assertEquals(5, restoredSub.getInt("a", 0));- assertEquals("bar", restoredSub.getString("foo", ""));+ SaveState restoreSubState = restoredState.getSaveState("TEST");+ assertEquals(2, restoreSubState.getNames().length);+ assertEquals(5, restoreSubState.getInt("a", 0));+ assertEquals("bar", restoreSubState.getString("foo", ""));}private SaveState saveAndRestoreToXml() throws Exception {- // persist the state- File saveFileTemp = createTempFile("xmlTest");- Element element = ss.saveToXml();- saveElement(element, saveFileTemp);-- // read in the state- InputStream is = new FileInputStream(saveFileTemp);- SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);- Element root = sax.build(is).getRootElement();- SaveState loadedState = new SaveState(root);- saveFileTemp.deleteOnExit();- return loadedState;- }-- private void saveElement(Element element, File saveFile) throws Exception {- OutputStream os = null;- try {- os = new FileOutputStream(saveFile);- Document doc = new Document(element);- XMLOutputter xmlout = new GenericXMLOutputter();- xmlout.output(doc, os);- os.close();- }- finally {- if (os != null) {- os.close();- }- }- }-- @Test- public void testStringArray() throws Exception {- String[] array1 =- new String[] { "Dennis", "Bill", "Brian", "Mike", null, "Ellen", "Steve" };- String[] after =- new String[] { "Dennis", "Bill", "Brian", "Mike", "Ellen", "Steve" };-- ss.putStrings("ARRAY", array1);- String[] array2 = ss.getStrings("ARRAY", null);-- assertArrayEquals(array1, array2);-- SaveState restoredState = saveAndRestoreToXml();-- assertArrayEquals(after, restoredState.getStrings("ARRAY", null));- }-- @Test- public void testByte() throws Exception {- ss.putByte("FOURTYTWO", (byte) 42);- assertTrue(ss.hasValue("FOURTYTWO"));- assertEquals((byte) 42, ss.getByte("FOURTYTWO", (byte) 0));- assertTrue(!ss.hasValue("XXX"));- assertEquals((byte) 5, ss.getByte("XXX", (byte) 5));-- SaveState restoredState = saveAndRestoreToXml();- assertEquals((byte) 42, restoredState.getByte(("FOURTYTWO"), (byte) 0));- }-- @Test- public void testByteArray() throws Exception {- byte[] array1 = new byte[] { (byte) 0, (byte) 5, (byte) 9, (byte) 42, (byte) 77 };- ss.putBytes("ARRAY", array1);- byte[] array2 = ss.getBytes("ARRAY", null);- assertArrayEquals(array1, array2);-- SaveState restoredState = saveAndRestoreToXml();- assertArrayEquals(array1, restoredState.getBytes("ARRAY", null));-- }-- @Test- public void testShort() throws Exception {- ss.putShort("FOURTYTWO", (short) 42);- assertTrue(ss.hasValue("FOURTYTWO"));- assertEquals((short) 42, ss.getShort("FOURTYTWO", (short) 0));- assertTrue(!ss.hasValue("XXX"));- assertEquals((short) 5, ss.getShort("XXX", (short) 5));-- SaveState restoredState = saveAndRestoreToXml();- assertEquals((short) 42, restoredState.getShort(("FOURTYTWO"), (short) 0));- }-- @Test- public void testInt() throws Exception {- ss.putInt("FOURTYTWO", 42);- assertTrue(ss.hasValue("FOURTYTWO"));- assertEquals(42, ss.getInt("FOURTYTWO", 0));- assertTrue(!ss.hasValue("XXX"));- assertEquals(5, ss.getInt("XXX", 5));-- SaveState restoredState = saveAndRestoreToXml();- assertEquals(42, restoredState.getInt(("FOURTYTWO"), 0));- }-- @Test- public void testIntArray() throws Exception {- int[] array1 = new int[] { 0, 5, 9, 42, 77 };- ss.putInts("ARRAY", array1);- int[] array2 = ss.getInts("ARRAY", null);- Arrays.equals(array1, array2);-- SaveState restoredState = saveAndRestoreToXml();-- // make sure our value is inside- int[] restoredArray = restoredState.getInts("ARRAY", null);- Arrays.equals(array1, restoredArray);- }-- @Test- public void testLong() throws Exception {- ss.putLong("FOURTYTWO", 42);- assertTrue(ss.hasValue("FOURTYTWO"));- assertEquals(42, ss.getLong("FOURTYTWO", 0));- assertTrue(!ss.hasValue("XXX"));- assertEquals(5, ss.getLong("XXX", 5));-- SaveState restoredState = saveAndRestoreToXml();- assertEquals(42L, restoredState.getLong(("FOURTYTWO"), 0));- }-- @Test- public void testFloat() throws Exception {- ss.putFloat("PI", (float) 3.14159);- assertTrue(ss.hasValue("PI"));- assertEquals((float) 3.14159, ss.getFloat("PI", (float) 0.0), (float) 0.01);- assertTrue(!ss.hasValue("XXX"));- assertEquals(5, ss.getFloat("XXX", 5), (float) 0.01);-- SaveState restoredState = saveAndRestoreToXml();- assertEquals(3.14159, restoredState.getFloat(("PI"), 0), 0.001f);- }-- @Test- public void testDouble() throws Exception {- ss.putDouble("PI", 3.14159);- assertTrue(ss.hasValue("PI"));- assertEquals(3.14159, ss.getDouble("PI", 0.0), 0.01);- assertTrue(!ss.hasValue("XXX"));- assertEquals(5, ss.getDouble("XXX", 5), 0.01);-- SaveState restoredState = saveAndRestoreToXml();- assertEquals(3.14159, restoredState.getDouble(("PI"), 0), 0.000001);- }-- @Test- public void testSome() {- ss.putDouble("PI", 3.14159);- ss.putByte("BYTE", (byte) 0xEE);- ss.putLong("LONG", 65536);- ss.putString("STRING", "See Jane Run");- ss.putBoolean("BOOL_A", false);- ss.putBoolean("BOOL_B", true);-- assertEquals(3.1459, ss.getDouble("PI", 0.0), 0.01);- assertEquals("See Jane Run", ss.getString("STRING", "BOB"));- assertEquals(true, ss.getBoolean("BOOL_B", false));- assertEquals((byte) 0xEE, ss.getByte("BYTE", (byte) 0));- assertEquals(false, ss.getBoolean("BOOL_A", true));+ Element saveToXml = saveState.saveToXml();+ return new SaveState(saveToXml);}-- @Test- public void testXML() {- Element elem1 = new Element("ELEM_1");- Element elem2 = new Element("ELEM_2");- elem1.setAttribute("NAME", "VALUE");- elem1.addContent(elem2);- ss.putXmlElement("XML", elem1);- Element elem3 = ss.getXmlElement("XML");- Element elem4 = (Element) elem3.getChildren().get(0);- assertEquals(elem1, elem3);- assertEquals(elem1.getName(), elem3.getName());- assertEquals(elem2, elem4);- assertEquals(elem2.getName(), elem4.getName());- }-- @Test- public void testXMLEntityEscapingForSCR_4675() throws Exception {- String stringWithGreaterThanAndLessThan =- "The following statement is true: 1 < 3 > 2 " + "with some trailing text";- String greaterThanLessThanKey = "GT_LT_KEY";- ss.putString(greaterThanLessThanKey, stringWithGreaterThanAndLessThan);-- String stringWithLargeHexDigit =- "The following is a large hex digit: \u0128, \u0132, \307 and \253 \uD835\uDCC8 " +- "with some trailing text ÿ";- String hexDigitKey = "HEX_DIGIT_KEY";- ss.putString(hexDigitKey, stringWithLargeHexDigit);-- String stringWithAmpersandApostropheAndQuote = "That is the Jones' \"love & happiness\".";- String ampersandApostropheQuoteKey = "AMP_APOS_KEY";- ss.putString(ampersandApostropheQuoteKey, stringWithAmpersandApostropheAndQuote);-- // persist the state- File saveFileTemp = null;- Element root = null;- try {- saveFileTemp = createTempFile("xmlTest");- Element element = ss.saveToXml();- saveElement(element, saveFileTemp);-- // read in the state- InputStream is = new FileInputStream(saveFileTemp);- SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);- root = sax.build(is).getRootElement();- }- catch (Exception e) {- throw e;- }- finally {- if (saveFileTemp != null) {- saveFileTemp.delete();- }- }-- // make sure our value is the same as we put in (no escaped entities)- SaveState loadedState = new SaveState(root);- String value = loadedState.getString(greaterThanLessThanKey, null);- assertNotNull(value);- assertEquals("The XML string saved with special characters was not read in correctly",- stringWithGreaterThanAndLessThan, value);-- value = loadedState.getString(hexDigitKey, null);- assertNotNull(value);- assertEquals("The XML string saved with special characters was not read in correctly",- stringWithLargeHexDigit, value);-- value = loadedState.getString(ampersandApostropheQuoteKey, null);- assertNotNull(value);- assertEquals("The XML string saved with special characters was not read in correctly",- stringWithAmpersandApostropheAndQuote, value);- }-- @Test- public void testIsEmpty() {- assertTrue(ss.isEmpty());- ss.putBoolean("BOOL", false);- assertTrue(!ss.isEmpty());- }-- @Test- public void testFileInputOutput() throws IOException {- ss.putBoolean("B1", true);- ss.putInt("I1", 7);- ss.putString("S1", "Hey There");- File file = createTempFile("SaveStateTest", "xml");- ss.saveToFile(file);-- SaveState ss2 = new SaveState(file);- assertEquals(true, ss2.getBoolean("B1", false));- assertEquals(7, ss2.getInt("I1", 1));- assertEquals("Hey There", ss2.getString("S1", ""));- file.delete();- }-- @Test- public void testJsonStringRoundTrip() {- ss.putString("foo", "Hey");- SaveState restored = jsonRoundTrip(ss);- assertEquals("Hey", restored.getString("foo", "there"));- }-- @Test- public void testJsonColorRoundTrip() {- ss.putColor("foo", Palette.BLUE);- SaveState restored = jsonRoundTrip(ss);- assertEquals(Palette.BLUE.getRGB(), restored.getColor("foo", null).getRGB());- }-- @Test- public void testJsonDatRoundTrip() throws Exception {- Date date = SaveState.DATE_FORMAT.parse("2020-12-22T14:20:24-0500");- ss.putDate("foo", date);- SaveState restored = jsonRoundTrip(ss);- assertEquals(date, restored.getDate("foo", null));- }-- @Test- public void testJsonFileRoundTrip() throws IOException {- File file = createTempFile("myFile", "txt");- ss.putFile("foo", file);- SaveState restored = jsonRoundTrip(ss);- assertEquals(file, restored.getFile("foo", null));- file.deleteOnExit();- }-- @Test- public void testJsonKeyStrokRoundTrip() {- KeyStroke keyStroke = KeyStroke.getKeyStroke("ctrl X");- assertNotNull(keyStroke);-- ss.putKeyStroke("foo", keyStroke);- SaveState restored = jsonRoundTrip(ss);- assertEquals(keyStroke, restored.getKeyStroke("foo", null));- }-- @Test- public void testJsonFontRoundTrip() {- Font font = Font.decode("Dialog-BOLD-12");- ss.putFont("foo", font);- SaveState restored = jsonRoundTrip(ss);- assertEquals(font, restored.getFont("foo", null));- }-- @Test- public void testJsonSubSaveStateRoundTrip() {- SaveState subState = new SaveState("sub");- subState.putInt("a", 5);- subState.putString("foo", "bar");- ss.putSaveState("foo", subState);- ss.putString("bar", "xyz");-- SaveState restored = jsonRoundTrip(ss);- assertEquals("xyz", restored.getString("bar", null));- SaveState restoredSub = restored.getSaveState("foo");- assertEquals(2, restoredSub.getNames().length);- assertEquals(5, restoredSub.getInt("a", 0));- assertEquals("bar", restoredSub.getString("foo", ""));- }-- @Test- public void testJsonByteRoundTrip() {- ss.putByte("foo", (byte) 42);- SaveState restored = jsonRoundTrip(ss);- assertEquals((byte) 42, restored.getByte("foo", (byte) 0));- }-- @Test- public void testJsonShortRoundTrip() {- ss.putShort("foo", (short) 42);- SaveState restored = jsonRoundTrip(ss);- assertEquals((short) 42, restored.getShort("foo", (short) 0));- }-- @Test- public void testJsonIntRoundTrip() {- ss.putInt("foo", 123456789);- SaveState restored = jsonRoundTrip(ss);- assertEquals(123456789, restored.getInt("foo", 0));- }-- @Test- public void testJsonLongRoundTrip() {- ss.putLong("foo", 12345678901234L);- SaveState restored = jsonRoundTrip(ss);- assertEquals(12345678901234L, restored.getLong("foo", 0));- }-- @Test- public void testJsonFloatRoundTrip() {- ss.putFloat("foo", 12.123f);- SaveState restored = jsonRoundTrip(ss);- assertEquals(12.123f, restored.getFloat("foo", 0), 0.0001f);- }-- @Test- public void testJsonDoubleRoundTrip() {- ss.putDouble("foo", 12.123456);- SaveState restored = jsonRoundTrip(ss);- assertEquals(12.123456, restored.getDouble("foo", 0), 0.00000001);- }-- @Test- public void testJsonBooleanRoundTrip() {- ss.putBoolean("foo", true);- SaveState restored = jsonRoundTrip(ss);- assertEquals(true, restored.getBoolean("foo", false));- }-- @Test- public void testJsonStringArrayRoundTrip() {- String[] strings = new String[] { "aaa", "bbb", null, "ccc" };- String[] after = new String[] { "aaa", "bbb", "ccc" };- ss.putStrings("foo", strings);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(after, restored.getStrings("foo", null));- }-- @Test- public void testJsonByteArrayRoundTrip() {- byte[] bytes = new byte[] { (byte) 1, (byte) 2, (byte) 3 };- ss.putBytes("foo", bytes);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(bytes, restored.getBytes("foo", null));- }-- @Test- public void testJsonShortArrayRoundTrip() {- short[] shorts = new short[] { (short) 1, (short) 2, (short) 3 };- ss.putShorts("foo", shorts);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(shorts, restored.getShorts("foo", null));- }-- @Test- public void testJsonIntArrayRoundTrip() {- int[] ints = new int[] { 1, 2, 3, 4, 5 };- ss.putInts("foo", ints);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(ints, restored.getInts("foo", null));- }-- @Test- public void testJsonLongArrayRoundTrip() {- long[] longs = new long[] { 1, 2, 3, 4, 5 };- ss.putLongs("foo", longs);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(longs, restored.getLongs("foo", null));- }-- @Test- public void testJsonFloatArrayRoundTrip() {- float[] floats = new float[] { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f };- ss.putFloats("foo", floats);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(floats, restored.getFloats("foo", null), .1f);- }-- @Test- public void testJsonDoubleArrayRoundTrip() {- double[] doubles = new double[] { 1.1, 2.2, 3.3, 4.4, 5.5 };- ss.putDoubles("foo", doubles);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(doubles, restored.getDoubles("foo", null), .1);- }-- @Test- public void testJsonBooleanArrayRoundTrip() {- boolean[] booleans = new boolean[] { true, false, true, true, false };- ss.putBooleans("foo", booleans);- SaveState restored = jsonRoundTrip(ss);- assertArrayEquals(booleans, restored.getBooleans("foo", null));- }-- @Test- public void testJsonEnumRoundTrip() {- ss.putEnum("foo", AddressType.FUNCTION);- SaveState restored = jsonRoundTrip(ss);- assertEquals(AddressType.FUNCTION, restored.getEnum("foo", null));- }-- @Test- public void testJsonXmlRoundTrip() {- Element element = new Element("ABC");- element.setAttribute("AAA", "aaa");- element.setAttribute("BBB", "bbb");- element.setAttribute("CCC", "ccc");- ss.putXmlElement("Foo", element);- SaveState restored = jsonRoundTrip(ss);- Element restoredElement = restored.getXmlElement("Foo");- assertEquals("aaa", restoredElement.getAttributeValue("AAA"));- assertEquals("bbb", restoredElement.getAttributeValue("BBB"));- assertEquals("ccc", restoredElement.getAttributeValue("CCC"));- }-- private SaveState jsonRoundTrip(SaveState saveState) {- JsonObject saveToJason = saveState.saveToJson();- return new SaveState(saveToJason);- }--// private void printJson(SaveState saveState) {-// JsonObject saveToJson = saveState.saveToJson();-// Gson gson = new GsonBuilder().setPrettyPrinting().create();-// System.out.println(gson.toJson(saveToJson));-// }-- @Test- public void testJsonFullRountTripThoughFile() throws IOException {- ss.putString("Name", "Bob");- ss.putBoolean("Retired", true);- ss.putInt("Age", 65);- ss.putEnum("Endian", Endian.BIG);- int[] ints = new int[] { 90, 95, 82, 93 };- ss.putInts("grades", ints);-- File file = createTempFile("SaveStateTest", "json");- ss.saveToJsonFile(file);- SaveState restoredSaveState = SaveState.readJsonFile(file);-- assertEquals("Bob", restoredSaveState.getString("Name", ""));- assertEquals(true, restoredSaveState.getBoolean("Retired", false));- assertEquals(65, restoredSaveState.getInt("Age", 0));- assertEquals(Endian.BIG, restoredSaveState.getEnum("Endian", Endian.LITTLE));- assertArrayEquals(ints, restoredSaveState.getInts("grades", null));-- }-}diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/Application.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/Application.javaindex e67653b674..5b3404d120 100644--- a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/Application.java+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/Application.java@@ -23,7 +23,10 @@ import generic.jar.ResourceFile;import ghidra.util.*;import ghidra.util.datastruct.LRUMap;import ghidra.util.exception.AssertException;+import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;+import util.CollectionUtils;+import utilities.util.FileUtilities;import utilities.util.reflection.ReflectionUtilities;import utility.application.ApplicationLayout;import utility.module.ModuleUtilities;@@ -618,6 +621,39 @@ public class Application {return app.layout.getUserSettingsDir();}+ /**+ * Returns a list of files in a setting subdirectory that have the given file extension,+ * copying files from older versions of Ghidra if the settings dir is not yet established.+ * @param dirName the name of the settings subdirectory.+ * @param fileExtension the file name suffix+ * @return a list of files in a setting sub directory that have the given file extension+ */+ public static List<File> getUserSettingsFiles(String dirName, String fileExtension) {+ File userSettingsDir = getUserSettingsDirectory();+ File subSettingsDir = new File(userSettingsDir, dirName);+ FileFilter filter = f -> f.getName().endsWith(fileExtension);++ if (!subSettingsDir.exists()) {+ subSettingsDir.mkdir();+ copyFilesFromPreviousVersion(subSettingsDir, dirName, filter);+ }+ File[] files = subSettingsDir.listFiles(filter);+ return CollectionUtils.asList(files);+ }++ private static void copyFilesFromPreviousVersion(File subSettingsDir, String dirName,+ FileFilter filter) {+ File previousDir = GenericRunInfo.getPreviousApplicationSettingsDir(dirName, filter);+ if (previousDir != null) {+ try {+ FileUtilities.copyDir(previousDir, subSettingsDir, filter, TaskMonitor.DUMMY);+ }+ catch (CancelledException | IOException e) {+ // don't care - just means we couldn't copy old files to new ghidra version+ }+ }+ }+/*** Returns the temporary directory specific to the user and the application.* Directory has name of <username>-<appname>diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/GenericRunInfo.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/GenericRunInfo.javaindex c4c972cbf6..80bdc5649e 100644--- a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/GenericRunInfo.java+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/GenericRunInfo.java@@ -80,8 +80,7 @@ public class GenericRunInfo {private static List<File> collectAllApplicationDirectories(File dataDirectoryParentDir) {- String settingsDirPrefix =- "." + Application.getName().replaceAll("\\s", "").toLowerCase();+ String settingsDirPrefix = "." + Application.getName().replaceAll("\\s", "").toLowerCase();FileFilter userDirFilter = f -> {String name = f.getName();return f.isDirectory() && name.startsWith(settingsDirPrefix) &&@@ -125,6 +124,45 @@ public class GenericRunInfo {return null;}+ /**+ * Searches previous Application Settings directories+ * ({@link #getUserSettingsDirsByTime()}) to find a settings directory containing+ * files that match the given file filter. This is+ * useful for loading previous directories of saved settings files of a particular type.+ *+ * <p>Note: this method will ignore any test versions of settings directories.+ *+ * @param dirName the name of a settings subdir; must be relative to a settings directory+ * @param filter the file filter for the files of interest+ * @return the most recent file matching that name and containing at least one file+ * of the given type, in a previous version's settings directory.+ */+ public static File getPreviousApplicationSettingsDir(String dirName, FileFilter filter) {++ List<File> settingsDirs = getPreviousApplicationSettingsDirsByTime();+ for (File dir : settingsDirs) {+ String dirPath = dir.getPath();+ if (dirPath.endsWith("Test")) {+ continue; // Ignore any test directories.+ }++ String altFilePath = dirPath + File.separatorChar + dirName;++ File altSettingsDir = new File(altFilePath);+ if (!altSettingsDir.exists()) {+ continue;+ }+ if (!altSettingsDir.isDirectory()) {+ continue;+ }+ File[] listFiles = altSettingsDir.listFiles(filter);+ if (listFiles != null && listFiles.length > 0) {+ return altSettingsDir;+ }+ }+ return null;+ }+/*** This is the same as {@link #getUserSettingsDirsByTime()} except that it doesn't include the* current installation or installations with different release namesdiff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/GProperties.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/GProperties.javanew file mode 100644index 0000000000..126713ef58--- /dev/null+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/GProperties.java@@ -0,0 +1,1436 @@+/* ###+ * 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.framework.options;++import java.awt.Color;+import java.awt.Font;+import java.io.*;+import java.lang.reflect.*;+import java.nio.charset.StandardCharsets;+import java.text.*;+import java.util.*;++import javax.swing.KeyStroke;++import org.jdom.Element;+import org.jdom.JDOMException;+import org.jdom.output.XMLOutputter;++import com.google.gson.*;++import ghidra.util.Msg;+import ghidra.util.NumericUtilities;+import ghidra.util.exception.AssertException;+import ghidra.util.xml.XmlUtilities;+import utilities.util.FileUtilities;++/**+ * Class for saving name/value pairs as XML or Json. Classes that want to be+ * able to save their state can do so using the GProperies object.+ * The idea is that each state variable in the class+ * is first saved into a GProperties object via a String key. Then the GProperties+ * object is written out as XML or Json. When the GProperties object is+ * restored, the GProperties object is constructed with an XML Element or JsonObject+ * that contains all of the name/value pairs. There are convenience subclasses for reading+ * these from a file (XmlProperties and JsonProperties).+ *+ * Since the "get" methods require a default value, the object that is recovering its+ * state variables will be successfully initialized even if+ * the given key,value pair is not found in the SaveState object.+ * <p> <i>Note: Names for property names are assumed to be unique. When a putXXX()+ * method is called, if a value already exists for a name, it will+ * be overwritten.</i>+ * <P>+ * The GProperties supports the following types:+ * <pre>+ * java primitives+ * arrays of java primitives+ * String+ * Color+ * Font+ * KeyStroke+ * File+ * Date+ * Enum+ * GProperties (values can be nested GProperties)+ * </pre>+ */++public class GProperties {+ private static final String G_PROPERTIES_TYPE = "GProperties";+ private static final String SAVE_STATE_LEGACY_TYPE = "SaveState";+ private static final String GPROPERTIES_TAG = "GPROPERTIES";+ private static final String PROPERTIES_NAME = "GPROPERTIES_NAME";+ private static final String LEGACY_PROPERTIES_NAME = "SAVE_STATE_NAME";+ private static final String STATE = "STATE";+ protected static final String TYPE = "TYPE";+ protected static final String NAME = "NAME";+ private static final String VALUE = "VALUE";+ public static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");+ private static final String ARRAY_ELEMENT_NAME = "A";+ protected TreeMap<String, Object> map; // use ordered map for deterministic serialization+ private String propertiesName;++ /**+ * Creates a new GProperties object with a non-default name. The name serves no real purpose+ * other than as a hint as to what the GProperties represents+ *+ * @param name of this GProperties object+ */+ public GProperties(String name) {+ this.propertiesName = name;+ this.map = new TreeMap<>();+ }++ /**+ * Construct a new GProperties object using the given XML element.+ * @param root XML contents of GProperties+ */+ public GProperties(Element root) {+ this(root.getName());+ Iterator<?> iter = root.getChildren().iterator();+ while (iter.hasNext()) {+ Element elem = (Element) iter.next();+ processElement(elem);+ }+ }++ /**+ * Construct a new GProperties object using the given JSonObject.+ * @param root JSonObject representing a GProperties+ */+ public GProperties(JsonObject root) {+ this(getPropertiesName(root));+ JsonObject values = root.get("VALUES").getAsJsonObject();+ JsonObject types = root.get("TYPES").getAsJsonObject();+ JsonObject enumClasses = root.get("ENUM_CLASSES").getAsJsonObject();++ for (String name : values.keySet()) {+ String type = types.get(name).getAsString();+ JsonElement valueElement = values.get(name);+ JsonElement enumClass = enumClasses.get(name);+ Object value = getObjectFromJson(type, valueElement, enumClass);+ if (value != null) {+ map.put(name, value);+ }+ }+ }++ protected void processElement(Element elem) {+ String tag = elem.getName();+ String name = elem.getAttributeValue(NAME);+ String type = elem.getAttributeValue(TYPE);+ String value = elem.getAttributeValue(VALUE);+ if (tag.equals("XML")) {+ map.put(name, elem.getChildren().get(0));+ }+ else if (tag.equals("BYTES")) {+ if (value != null) {+ map.put(name, NumericUtilities.convertStringToBytes(value));+ }+ }+ else if (tag.equals(STATE)) {+ try {+ if (type == null) {+ // skip this element+ }+ else if (type.equals("byte")) {+ map.put(name, Byte.valueOf(value));+ }+ else if (type.equals("short")) {+ map.put(name, Short.valueOf(value));+ }+ else if (type.equals("int")) {+ map.put(name, Integer.valueOf(value));+ }+ else if (type.equals("long")) {+ map.put(name, Long.valueOf(value));+ }+ else if (type.equals("float")) {+ map.put(name, Float.valueOf(value));+ }+ else if (type.equals("double")) {+ map.put(name, Double.valueOf(value));+ }+ else if (type.equals("boolean")) {+ map.put(name, Boolean.valueOf(value));+ }+ else if (type.equals("string")) {+ String encodedValue = elem.getAttributeValue("ENCODED_VALUE");+ if (value == null && encodedValue != null) {+ byte[] strBytes = NumericUtilities.convertStringToBytes(encodedValue);+ value = new String(strBytes, StandardCharsets.UTF_8);+ }+ map.put(name, value);+ }+ else if (type.equals("Color")) {+ map.put(name, new Color(Integer.valueOf(value)));+ }+ else if (type.equals("Date")) {+ map.put(name, DATE_FORMAT.parse(value));+ }+ else if (type.equals("File")) {+ map.put(name, new File(value));+ }+ else if (type.equals("KeyStroke")) {+ map.put(name, KeyStroke.getKeyStroke(value));+ }+ else if (type.equals("Font")) {+ map.put(name, Font.decode(value));+ }+ }+ catch (Exception e) {+ Msg.warn(this, "Error processing primitive value in GProperties", e);+ }+ }+ else if (tag.equals("ARRAY")) {+ if (type == null) {+ return;+ }++ try {+ List<?> list = elem.getChildren(ARRAY_ELEMENT_NAME);+ Iterator<?> it = list.iterator();+ int i = 0;+ if (type.equals("short")) {+ short[] vals = new short[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = Short.parseShort(e.getAttributeValue(VALUE));+ }+ map.put(name, vals);+ }+ else if (type.equals("int")) {+ int[] vals = new int[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = Integer.parseInt(e.getAttributeValue(VALUE));+ }+ map.put(name, vals);+ }+ else if (type.equals("long")) {+ long[] vals = new long[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = Long.parseLong(e.getAttributeValue(VALUE));+ }+ map.put(name, vals);+ }+ else if (type.equals("float")) {+ float[] vals = new float[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = Float.parseFloat(e.getAttributeValue(VALUE));+ }+ map.put(name, vals);+ }+ else if (type.equals("double")) {+ double[] vals = new double[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = Double.parseDouble(e.getAttributeValue(VALUE));+ }+ map.put(name, vals);+ }+ else if (type.equals("boolean")) {+ boolean[] vals = new boolean[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = Boolean.valueOf(e.getAttributeValue(VALUE)).booleanValue();+ }+ map.put(name, vals);+ }+ else if (type.equals("string")) {+ String[] vals = new String[list.size()];+ while (it.hasNext()) {+ Element e = (Element) it.next();+ vals[i++] = e.getAttributeValue(VALUE);+ }+ map.put(name, vals);+ }+ }+ catch (Exception exc) {+ Msg.warn(this, "Error processing array value in GProperties", exc);+ }+ }+ else if (tag.equals("ENUM")) {+ if (type == null) {+ return;+ }+ if (type.equals("stringenum")) {+ return;+ }+ if (type.equals("enum")) {+ String className = elem.getAttributeValue("CLASS");+ Enum<?> e = getEnumValue(className, value);+ if (e != null) {+ map.put(name, e);+ }+ }+ }+ else if (tag.equals(GPROPERTIES_TAG)) {+ Element element = (Element) elem.getChildren().get(0);+ if (element != null) {+ map.put(name, new GProperties(element));+ }+ }+ else if (tag.equals("NULL")) {+ map.put(name, null);+ }+ }++ private static String getPropertiesName(JsonObject root) {+ if (root.has(LEGACY_PROPERTIES_NAME)) {+ return root.get(LEGACY_PROPERTIES_NAME).getAsString();+ }+ return root.get(PROPERTIES_NAME).getAsString();+ }++ private Object getObjectFromJson(String type, JsonElement value, JsonElement enumClass) {++ switch (type) {+ case "null":+ return null;+ case "String":+ return value.getAsString();+ case "Color":+ return new Color(value.getAsInt());+ case "Date":+ return parseDate(value.getAsString());+ case "File":+ return new File(value.getAsString());+ case "KeyStroke":+ return KeyStroke.getKeyStroke(value.getAsString());+ case "Font":+ return Font.decode(value.getAsString());+ case "byte":+ return value.getAsByte();+ case "short":+ return value.getAsShort();+ case "int":+ return value.getAsInt();+ case "long":+ return value.getAsLong();+ case "float":+ return value.getAsFloat();+ case "double":+ return value.getAsDouble();+ case "boolean":+ return value.getAsBoolean();+ case "byte[]":+ JsonArray byteArray = value.getAsJsonArray();+ byte[] bytes = new byte[byteArray.size()];+ for (int i = 0; i < bytes.length; i++) {+ bytes[i] = byteArray.get(i).getAsByte();+ }+ return bytes;+ case "short[]":+ JsonArray shortArray = value.getAsJsonArray();+ short[] shorts = new short[shortArray.size()];+ for (int i = 0; i < shorts.length; i++) {+ shorts[i] = shortArray.get(i).getAsShort();+ }+ return shorts;+ case "int[]":+ JsonArray intArray = value.getAsJsonArray();+ int[] ints = new int[intArray.size()];+ for (int i = 0; i < ints.length; i++) {+ ints[i] = intArray.get(i).getAsInt();+ }+ return ints;+ case "long[]":+ JsonArray longArray = value.getAsJsonArray();+ long[] longs = new long[longArray.size()];+ for (int i = 0; i < longs.length; i++) {+ longs[i] = longArray.get(i).getAsLong();+ }+ return longs;+ case "float[]":+ JsonArray floatArray = value.getAsJsonArray();+ float[] floats = new float[floatArray.size()];+ for (int i = 0; i < floats.length; i++) {+ floats[i] = floatArray.get(i).getAsFloat();+ }+ return floats;+ case "double[]":+ JsonArray doubleArray = value.getAsJsonArray();+ double[] doubles = new double[doubleArray.size()];+ for (int i = 0; i < doubles.length; i++) {+ doubles[i] = doubleArray.get(i).getAsDouble();+ }+ return doubles;+ case "boolean[]":+ JsonArray boolArray = value.getAsJsonArray();+ boolean[] booleans = new boolean[boolArray.size()];+ for (int i = 0; i < booleans.length; i++) {+ booleans[i] = boolArray.get(i).getAsBoolean();+ }+ return booleans;+ case "String[]":+ JsonArray stringArray = value.getAsJsonArray();+ String[] strings = new String[stringArray.size()];+ for (int i = 0; i < strings.length; i++) {+ strings[i] = stringArray.get(i).getAsString();+ }+ return strings;+ case "xml":+ try {+ return XmlUtilities.fromString(value.getAsString());+ }+ catch (JDOMException | IOException e) {+ throw new AssertException("Error processing embedded XML");+ }++ case "enum":+ String enumClassName = enumClass.getAsString();+ String enumValue = value.getAsString();+ return getEnumValue(enumClassName, enumValue);++ case G_PROPERTIES_TYPE:+ case SAVE_STATE_LEGACY_TYPE:+ JsonObject json = (JsonObject) value;+ return new GProperties(json);++ default:+ throw new AssertException("Unknown type: " + type);+ }+ }++ private Date parseDate(String dateString) {+ try {+ return DATE_FORMAT.parse(dateString);+ }+ catch (ParseException e) {+ throw new AssertException("Can't parse date string: " + dateString);+ }+ }++ Enum<?> getEnumValue(String enumClassName, String value) {+ try {+ Class<?> enumClass = Class.forName(enumClassName).asSubclass(Enum.class);++ Method m = enumClass.getMethod("valueOf", new Class[] { String.class });+ if (m != null) {+ return (Enum<?>) m.invoke(null, new Object[] { value });+ }+ }+ catch (Exception e) {+ Msg.warn(this, "Can't find field " + value + " in enum class " + enumClassName, e);+ }+ return null;+ }++ /**+ * Outputs this GProperties to a file using Json+ * <P>+ * For example, a GProperties that is created with:+ * <pre>+ * ss = new GProperties("foo")+ * ss.putString("Name", "Bob");+ * ss.putBoolean("Retired", true);+ * ss.putInt("Age", 65);+ * ss.putEnum("Endian", Endian.BIG);+ *+ * would produce a Json file with the following text+ *+ * {+ * "GPROPERTIES NAME": "foo",+ * "VALUES": {+ * "Name": "Bob"+ * "Retired": true,+ * "Age": 65,+ * "Endian": "BIG",+ * },+ * "TYPES": {+ * "Name": "String"+ * "Retired": "boolean",+ * "Age": "int",+ * "Endian": "enum",+ * },+ * "ENUM CLASSES": {+ * "Endian": "ghidra.program.model.lang.Endian"+ * }+ *}+ * </pre>+ *+ * @param file the file to save to+ * @throws IOException if an error occurs writing to the given file+ */+ public void saveToJsonFile(File file) throws IOException {+ Gson gson = new GsonBuilder().setPrettyPrinting().create();+ JsonObject saveToJson = saveToJson();+ try (FileWriter writer = new FileWriter(file)) {+ writer.write(gson.toJson(saveToJson));+ }+ }++ /**+ * Write the properties to a file as XML+ * @param file the file to write to.+ * @throws IOException if the file could not be written+ */+ public void saveToXmlFile(File file) throws IOException {+ Element saveToXml = saveToXml();+ byte[] bytes = XmlUtilities.xmlToByteArray(saveToXml);+ FileUtilities.writeBytes(file, bytes);+ }++ /**+ * Save this object to an XML element.+ * @return Element XML element containing the properties+ */+ public Element saveToXml() {+ Element root = new Element(propertiesName);+ Iterator<String> iter = map.keySet().iterator();+ while (iter.hasNext()) {+ String key = iter.next();+ Object value = map.get(key);+ Element elem = createElement(key, value);+ root.addContent(elem);+ }+ return root;+ }++ protected Element createElement(String key, Object value) {+ Element elem = null;+ if (value instanceof Element) {+ elem = createElementFromElement(key, (Element) value);+ }+ else if (value instanceof Byte) {+ elem = setAttributes(key, "byte", ((Byte) value).toString());+ }+ else if (value instanceof Short) {+ elem = setAttributes(key, "short", ((Short) value).toString());+ }+ else if (value instanceof Integer) {+ elem = setAttributes(key, "int", ((Integer) value).toString());+ }+ else if (value instanceof Long) {+ elem = setAttributes(key, "long", ((Long) value).toString());+ }+ else if (value instanceof Float) {+ elem = setAttributes(key, "float", ((Float) value).toString());+ }+ else if (value instanceof Double) {+ elem = setAttributes(key, "double", ((Double) value).toString());+ }+ else if (value instanceof Boolean) {+ elem = setAttributes(key, "boolean", ((Boolean) value).toString());+ }+ else if (value instanceof String) {+ elem = new Element(STATE);+ elem.setAttribute(NAME, key);+ elem.setAttribute(TYPE, "string");+ if (XmlUtilities.hasInvalidXMLCharacters((String) value)) {+ elem.setAttribute("ENCODED_VALUE", NumericUtilities+ .convertBytesToString(((String) value).getBytes(StandardCharsets.UTF_8)));+ }+ else {+ elem.setAttribute(VALUE, (String) value);+ }+ }+ else if (value instanceof Color) {+ elem = setAttributes(key, "Color", Integer.toString(((Color) value).getRGB()));+ }+ else if (value instanceof Date) {+ elem = setAttributes(key, "Date", DATE_FORMAT.format((Date) value));+ }+ else if (value instanceof File) {+ elem = setAttributes(key, "File", ((File) value).getAbsolutePath());+ }+ else if (value instanceof KeyStroke) {+ elem = setAttributes(key, "KeyStroke", value.toString());+ }+ else if (value instanceof Font font) {+ elem = setAttributes(key, "Font", toFontString(font));+ }+ else if (value instanceof byte[]) {+ elem = new Element("BYTES");+ elem.setAttribute(NAME, key);+ elem.setAttribute(VALUE, NumericUtilities.convertBytesToString((byte[]) value));+ }+ else if (value instanceof short[]) {+ elem = setArrayAttributes(key, "short", value);+ }+ else if (value instanceof int[]) {+ elem = setArrayAttributes(key, "int", value);+ }+ else if (value instanceof long[]) {+ elem = setArrayAttributes(key, "long", value);+ }+ else if (value instanceof float[]) {+ elem = setArrayAttributes(key, "float", value);+ }+ else if (value instanceof double[]) {+ elem = setArrayAttributes(key, "double", value);+ }+ else if (value instanceof boolean[]) {+ elem = setArrayAttributes(key, "boolean", value);+ }+ else if (value instanceof String[]) {+ elem = setArrayAttributes(key, "string", value);+ }+ else if (value instanceof Enum) {+ Enum<?> e = (Enum<?>) value;+ elem = new Element("ENUM");+ elem.setAttribute(NAME, key);+ elem.setAttribute(TYPE, "enum");+ elem.setAttribute("CLASS", e.getClass().getName());+ elem.setAttribute(VALUE, e.name());+ }+ else if (value instanceof GProperties) {+ Element savedElement = ((GProperties) value).saveToXml();+ elem = new Element(GPROPERTIES_TAG);+ elem.setAttribute(NAME, key);+ elem.setAttribute(TYPE, G_PROPERTIES_TYPE);+ elem.addContent(savedElement);+ }+ else {+ elem = new Element("NULL");+ elem.setAttribute(NAME, key);+ }+ return elem;+ }++ private <T> Element setArrayAttributes(String key, String type, Object values) {+ Element elem = new Element("ARRAY");+ elem.setAttribute(NAME, key);+ elem.setAttribute(TYPE, type);+ for (int i = 0; i < Array.getLength(values); i++) {+ Object value = Array.get(values, i);+ if (value != null) {+ Element arrElem = new Element(ARRAY_ELEMENT_NAME);+ arrElem.setAttribute(VALUE, value.toString());+ elem.addContent(arrElem);+ }+ }+ return elem;+ }++ private Element setAttributes(String key, String type, String value) {+ Element elem;+ elem = new Element(STATE);+ elem.setAttribute(NAME, key);+ elem.setAttribute(TYPE, type);+ elem.setAttribute(VALUE, value);+ return elem;+ }++ /**+ * Save this object to an JsonObject+ *+ * @return JsonObject containing the properties+ */+ public JsonObject saveToJson() {+ JsonObject types = new JsonObject();+ JsonObject values = new JsonObject();+ JsonObject enumClasses = new JsonObject();+ Iterator<String> iter = map.keySet().iterator();+ while (iter.hasNext()) {+ String key = iter.next();+ Object value = map.get(key);+ if (value == null) {+ types.addProperty(key, "null");+ values.addProperty(key, "null");+ }+ else if (value instanceof Element) {+ types.addProperty(key, "xml");+ String outputString = new XMLOutputter().outputString((Element) value);+ values.addProperty(key, outputString);+ }+ else if (value instanceof Color) {+ types.addProperty(key, "Color");+ values.addProperty(key, ((Color) value).getRGB());+ }+ else if (value instanceof Date) {+ types.addProperty(key, "Date");+ values.addProperty(key, DATE_FORMAT.format((Date) value));+ }+ else if (value instanceof File) {+ types.addProperty(key, "File");+ values.addProperty(key, ((File) value).getAbsolutePath());+ }+ else if (value instanceof KeyStroke) {+ types.addProperty(key, "KeyStroke");+ values.addProperty(key, value.toString());+ }+ else if (value instanceof Font font) {+ types.addProperty(key, "Font");+ values.addProperty(key, toFontString(font));+ }+ else if (value instanceof Byte) {+ types.addProperty(key, "byte");+ values.addProperty(key, (Byte) value);+ }+ else if (value instanceof Short) {+ types.addProperty(key, "short");+ values.addProperty(key, (Short) value);+ }+ else if (value instanceof Integer) {+ types.addProperty(key, "int");+ values.addProperty(key, (Integer) value);+ }+ else if (value instanceof Long) {+ types.addProperty(key, "long");+ values.addProperty(key, (Long) value);+ }+ else if (value instanceof Float) {+ types.addProperty(key, "float");+ values.addProperty(key, (Float) value);+ }+ else if (value instanceof Double) {+ types.addProperty(key, "double");+ values.addProperty(key, (Double) value);+ }+ else if (value instanceof Boolean) {+ types.addProperty(key, "boolean");+ values.addProperty(key, (Boolean) value);+ }+ else if (value instanceof String) {+ types.addProperty(key, "String");+ values.addProperty(key, (String) value);+ }+ else if (value instanceof byte[]) {+ JsonArray ja = new JsonArray();+ for (byte b : (byte[]) value) {+ ja.add(b);+ }+ types.addProperty(key, "byte[]");+ values.add(key, ja);+ }+ else if (value instanceof short[]) {+ JsonArray ja = new JsonArray();+ for (short s : (short[]) value) {+ ja.add(s);+ }+ types.addProperty(key, "short[]");+ values.add(key, ja);+ }+ else if (value instanceof int[]) {+ JsonArray ja = new JsonArray();+ for (int i : (int[]) value) {+ ja.add(i);+ }+ types.addProperty(key, "int[]");+ values.add(key, ja);+ }+ else if (value instanceof long[]) {+ JsonArray ja = new JsonArray();+ for (long i : (long[]) value) {+ ja.add(i);+ }+ types.addProperty(key, "long[]");+ values.add(key, ja);+ }+ else if (value instanceof float[]) {+ JsonArray ja = new JsonArray();+ for (float f : (float[]) value) {+ ja.add(f);+ }+ types.addProperty(key, "float[]");+ values.add(key, ja);+ }+ else if (value instanceof double[]) {+ JsonArray ja = new JsonArray();+ for (double f : (double[]) value) {+ ja.add(f);+ }+ types.addProperty(key, "double[]");+ values.add(key, ja);+ }+ else if (value instanceof boolean[]) {+ JsonArray ja = new JsonArray();+ for (boolean b : (boolean[]) value) {+ ja.add(b);+ }+ types.addProperty(key, "boolean[]");+ values.add(key, ja);+ }+ else if (value instanceof String[]) {+ JsonArray ja = new JsonArray();+ for (String s : (String[]) value) {+ if (s != null) {+ ja.add(s);+ }+ }+ types.addProperty(key, "String[]");+ values.add(key, ja);+ }+ else if (value instanceof Enum) {+ Enum<?> e = (Enum<?>) value;+ types.addProperty(key, "enum");+ enumClasses.addProperty(key, e.getClass().getName());+ values.addProperty(key, e.name());+ }+ else if (value instanceof GProperties) {+ types.addProperty(key, G_PROPERTIES_TYPE);+ JsonObject json = ((GProperties) value).saveToJson();+ values.add(key, json);+ }+ else {+ throw new AssertException("found unsupported object type: " + value.getClass());+ }+ }+ JsonObject jsonObject = new JsonObject();+ jsonObject.addProperty(PROPERTIES_NAME, propertiesName);+ jsonObject.add("VALUES", values);+ jsonObject.add("TYPES", types);+ jsonObject.add("ENUM_CLASSES", enumClasses);+ return jsonObject;+ }++ protected Element createElementFromElement(String internalKey, Element internalElement) {+ Element newElement = new Element("XML");+ newElement.setAttribute(NAME, internalKey);++ Element internalElementClone = (Element) internalElement.clone();+ newElement.addContent(internalElementClone);++ return newElement;+ }++ /**+ * Returns true if this GProperties contains no elements+ * @return true if there are no properties in this GProperties+ */+ public boolean isEmpty() {+ return map.isEmpty();+ }++ /**+ * Remove the object identified by the given name+ *+ * @param name the name of the property to remove+ */+ public void remove(String name) {+ map.remove(name);+ }++ /**+ * Clear all objects from this GProperties+ */+ public void clear() {+ map.clear();+ }++ /**+ * Return the number of properties in this GProperties+ * @return The number of properties in this GProperties+ */+ public int size() {+ return map.size();+ }++ /**+ * Return the names of the properties in this GProperties.+ * @return the names of the properties in this GProperties.+ */+ public String[] getNames() {+ String[] names = new String[map.size()];+ int idx = 0;+ Iterator<String> iter = map.keySet().iterator();+ while (iter.hasNext()) {+ names[idx] = iter.next();+ ++idx;+ }+ return names;+ }++ //////////////////////////////////////////////////////////////++ void putObject(String name, Object obj) {+ map.put(name, obj);+ }++ Object getObject(String name) {+ return map.get(name);+ }++ //////////////////////////////////////////////////////////////++ /**+ * Associates an integer value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putInt(String name, int value) {+ map.put(name, Integer.valueOf(value));+ }++ /**+ * Associates a byte value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putByte(String name, byte value) {+ map.put(name, Byte.valueOf(value));+ }++ /**+ * Associates a short value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putShort(String name, short value) {+ map.put(name, Short.valueOf(value));+ }++ /**+ * Associates a long value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putLong(String name, long value) {+ map.put(name, Long.valueOf(value));+ }++ /**+ * Associates a String value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putString(String name, String value) {+ map.put(name, value);+ }++ /**+ * Associates a Color value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putColor(String name, Color value) {+ map.put(name, value);+ }++ /**+ * Associates a Date value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putDate(String name, Date value) {+ map.put(name, value);+ }++ /**+ * Associates a File value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putFile(String name, File value) {+ map.put(name, value);+ }++ /**+ * Associates a KeyStroke value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putKeyStroke(String name, KeyStroke value) {+ map.put(name, value);+ }++ /**+ * Associates a Font value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putFont(String name, Font value) {+ map.put(name, value);+ }++ /**+ * Associates a boolean value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putBoolean(String name, boolean value) {+ map.put(name, Boolean.valueOf(value));+ }++ /**+ * Associates a float value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putFloat(String name, float value) {+ map.put(name, Float.valueOf(value));+ }++ /**+ * Associates a double value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putDouble(String name, double value) {+ map.put(name, Double.valueOf(value));+ }++ /**+ * Associates a sub SaveState value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putGProperties(String name, GProperties value) {+ map.put(name, value);+ }++ /**+ * Gets the int value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the int value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public int getInt(String name, int defaultValue) {+ return getAsType(name, defaultValue, Integer.class);+ }++ /**+ * Gets the byte value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the byte value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public byte getByte(String name, byte defaultValue) {+ return getAsType(name, defaultValue, Byte.class);+ }++ /**+ * Gets the short value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the short value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public short getShort(String name, short defaultValue) {+ return getAsType(name, defaultValue, Short.class);+ }++ /**+ * Gets the long value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the long value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public long getLong(String name, long defaultValue) {+ return getAsType(name, defaultValue, Long.class);+ }++ /**+ * Gets the boolean value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the boolean value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public boolean getBoolean(String name, boolean defaultValue) {+ return getAsType(name, defaultValue, Boolean.class);+ }++ /**+ * Gets the String value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the String value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public String getString(String name, String defaultValue) {+ return getAsType(name, defaultValue, String.class);+ }++ /**+ * Gets the Color value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the Color value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public Color getColor(String name, Color defaultValue) {+ return getAsType(name, defaultValue, Color.class);+ }++ /**+ * Gets the Date value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the Date value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public Date getDate(String name, Date defaultValue) {+ return getAsType(name, defaultValue, Date.class);+ }++ /**+ * Gets the File value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the File value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public File getFile(String name, File defaultValue) {+ return getAsType(name, defaultValue, File.class);+ }++ /**+ * Gets the KeyStroke value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the KeyStroke value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public KeyStroke getKeyStroke(String name, KeyStroke defaultValue) {+ return getAsType(name, defaultValue, KeyStroke.class);+ }++ /**+ * Gets the Font value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the Font value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public Font getFont(String name, Font defaultValue) {+ return getAsType(name, defaultValue, Font.class);+ }++ /**+ * Gets the float value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the float value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public float getFloat(String name, float defaultValue) {+ return getAsType(name, defaultValue, Float.class);+ }++ /**+ * Gets the double value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the double value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public double getDouble(String name, double defaultValue) {+ return getAsType(name, defaultValue, Double.class);+ }++ /**+ * Associates an integer array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putInts(String name, int[] value) {+ map.put(name, value);+ }++ /**+ * Associates a byte array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putBytes(String name, byte[] value) {+ map.put(name, value);+ }++ /**+ * Associates a short array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putShorts(String name, short[] value) {+ map.put(name, value);+ }++ /**+ * Associates a long array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putLongs(String name, long[] value) {+ map.put(name, value);+ }++ /**+ * Associates a String array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putStrings(String name, String[] value) {+ map.put(name, value);+ }++ /**+ * Associates an Enum with the given name.+ * @param name The name in the name,value pair.+ * @param value The Enum value in the name,value pair.+ */+ public void putEnum(String name, Enum<?> value) {+ if ((value.getClass().getModifiers() & Modifier.PUBLIC) == 0) {+ throw new IllegalArgumentException("enum '" + value.name() + "' must be public");+ }+ map.put(name, value);+ }++ /**+ * Associates a boolean array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putBooleans(String name, boolean[] value) {+ map.put(name, value);+ }++ /**+ * Associates a float array with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putFloats(String name, float[] value) {+ map.put(name, value);+ }++ /**+ * Associates a double value with the given name.+ * @param name The name in the name,value pair.+ * @param value The value in the name,value pair.+ */+ public void putDoubles(String name, double[] value) {+ map.put(name, value);+ }++ /**+ * Gets the int array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the int array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public int[] getInts(String name, int[] defaultValue) {+ return map.containsKey(name) ? (int[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the byte array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the byte array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public byte[] getBytes(String name, byte[] defaultValue) {+ return map.containsKey(name) ? (byte[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the short array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the short array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public short[] getShorts(String name, short[] defaultValue) {+ return map.containsKey(name) ? (short[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the long array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the long array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public long[] getLongs(String name, long[] defaultValue) {+ return map.containsKey(name) ? (long[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the boolean array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the boolean array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public boolean[] getBooleans(String name, boolean[] defaultValue) {+ return map.containsKey(name) ? (boolean[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the String array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the String array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public String[] getStrings(String name, String[] defaultValue) {+ return map.containsKey(name) ? (String[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the Enum value for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default Enum value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the Enum value associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ @SuppressWarnings("unchecked")+ public <T extends Enum<T>> T getEnum(String name, T defaultValue) {+ if (defaultValue != null &&+ (defaultValue.getClass().getModifiers() & Modifier.PUBLIC) == 0) {+ throw new IllegalArgumentException("enum '" + defaultValue.name() + "' must be public");+ }+ try {+ if (map.containsKey(name)) {+ return (T) map.get(name);+ }+ }+ catch (ClassCastException e) {+ // Facilitate transition from StringEnum to Enum+ map.put(name, defaultValue);+ }+ return defaultValue;+ }++ /**+ * Gets the float array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the float array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public float[] getFloats(String name, float[] defaultValue) {+ return map.containsKey(name) ? (float[]) map.get(name) : defaultValue;+ }++ /**+ * Gets the double array for the given name.+ * @param name the name of the pair.+ * @param defaultValue the default value to be returned if the name does+ * not exist in the map, or it does not contain the proper object type.+ * @return the double array associated with the given name or the defaultValue+ * passed in if the name doesn't exist or is the wrong type.+ */+ public double[] getDoubles(String name, double[] defaultValue) {+ return map.containsKey(name) ? (double[]) map.get(name) : defaultValue;+ }++ /**+ * Returns true if there is a value for the given name+ *+ * @param name true the name of the property to check for a value+ * @return true if this GProperties has a value for the given name+ */+ public boolean hasValue(String name) {+ return map.containsKey(name);+ }++ /**+ * Adds an XML element to the+ * this GProperties. Used by plugins that have more+ * complicated state information that needs to be saved.+ * @param name the name to associate with the element+ * @param element XML element which is the root of an+ * XML sub-tree.+ */+ public void putXmlElement(String name, Element element) {+ map.put(name, element);+ }++ /**+ * Returns the root of an XML sub-tree associated with the+ * given name.+ * @param name The name associated with the desired Element.+ * @return The root of an XML sub-tree associated with the+ * given name.+ */+ public Element getXmlElement(String name) {+ return getAsType(name, null, Element.class);+ }++ public GProperties getGProperties(String name) {+ return getAsType(name, null, GProperties.class);++ }++ @Override+ public String toString() {+ return XmlUtilities.toString(saveToXml());+ }++ protected <T> T getAsType(String name, T defaultValue, Class<T> clazz) {+ if (map.containsKey(name)) {+ Object value = map.get(name);+ if (isExpectedType(name, value, clazz)) {+ return clazz.cast(value);+ }+ }+ return defaultValue;++ }++ private boolean isExpectedType(String name, Object value, Class<?> expectedType) {+ if (value != null && !expectedType.isInstance(value)) {+ Msg.debug(this,+ "Type mismatch on GProperties property \"" + name ++ "\". Attempted to retrieve value as a " + expectedType.getName() ++ " but was of type " + value.getClass().getName());+ return false;+ }+ return true;+ }++ private String toFontString(Font font) {+ return String.format("%s-%s-%s", font.getName(), getStyleString(font), font.getSize());+ }++ private String getStyleString(Font font) {+ boolean bold = font.isBold();+ boolean italic = font.isItalic();+ if (bold && italic) {+ return "BOLDITALIC";+ }+ if (bold) {+ return "BOLD";+ }+ if (italic) {+ return "ITALIC";+ }+ return "PLAIN";+ }++}diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/JSonProperties.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/JSonProperties.javanew file mode 100644index 0000000000..0a9375479d--- /dev/null+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/JSonProperties.java@@ -0,0 +1,40 @@+/* ###+ * 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.framework.options;++import java.io.*;++import com.google.gson.JsonObject;+import com.google.gson.JsonParser;++/**+ * A convenience class for creating a GProperties object from a file containing JSon data+ * generated from {@link GProperties#saveToJsonFile(File)}+ */+public class JSonProperties extends GProperties {++ public JSonProperties(File file) throws IOException {+ super(getJsonObject(file));++ }++ private static JsonObject getJsonObject(File file) throws IOException {+ try (Reader reader = new FileReader(file)) {+ return (JsonObject) JsonParser.parseReader(reader);+ }+ }++}diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.javaindex f1ce2ea17b..3bef330802 100644--- a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/SaveState.java@@ -15,27 +15,10 @@*/package ghidra.framework.options;-import java.awt.Color;-import java.awt.Font;-import java.io.*;-import java.lang.reflect.*;-import java.nio.charset.StandardCharsets;-import java.text.*;-import java.util.*;--import javax.swing.KeyStroke;+import java.io.File;+import java.io.IOException;import org.jdom.Element;-import org.jdom.JDOMException;-import org.jdom.output.XMLOutputter;--import com.google.gson.*;--import ghidra.util.Msg;-import ghidra.util.NumericUtilities;-import ghidra.util.exception.AssertException;-import ghidra.util.xml.XmlUtilities;-import utilities.util.FileUtilities;/*** Class for saving name/value pairs as XML or Json. Classes that want to be@@ -67,31 +50,8 @@ import utilities.util.FileUtilities;* </pre>*/-public class SaveState {- private static final String STATE = "STATE";- private static final String TYPE = "TYPE";- private static final String NAME = "NAME";- private static final String VALUE = "VALUE";+public class SaveState extends XmlProperties {private static final String SAVE_STATE = "SAVE_STATE";- public static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");- private static final String ARRAY_ELEMENT_NAME = "A";- private TreeMap<String, Object> map; // use ordered map for deterministic serialization- private String saveStateName;-- /**- * Creates a SaveState object and populates its values from the given file. The file must- * conform to the format that is created with {@link #saveToJson()}- *- * @param file the file to load values from- * @return a new SaveState object loaded with values from the given file.- * @throws IOException if an error occurs reading the given file.- */- public static SaveState readJsonFile(File file) throws IOException {- try (Reader reader = new FileReader(file)) {- JsonElement element = JsonParser.parseReader(reader);- return new SaveState((JsonObject) element);- }- }/*** Creates a new SaveState object with a non-default name. The name serves no real purpose@@ -100,8 +60,7 @@ public class SaveState {* @param name of the state*/public SaveState(String name) {- this.saveStateName = name;- this.map = new TreeMap<>();+ super(name);}/**@@ -119,877 +78,20 @@ public class SaveState {* @throws IOException if the file can't be read or is not formatted properly for a SaveState*/public SaveState(File file) throws IOException {- this(getXmlElementFromFile(file));- }-- /**- * Construct a new SaveState object using the given XML element.- * @param root XML contents of the save state- */- public SaveState(Element root) {- this(root.getName());- Iterator<?> iter = root.getChildren().iterator();- while (iter.hasNext()) {- Element elem = (Element) iter.next();- String tag = elem.getName();- String name = elem.getAttributeValue(NAME);- String type = elem.getAttributeValue(TYPE);- String value = elem.getAttributeValue(VALUE);- if (tag.equals("XML")) {- map.put(name, elem.getChildren().get(0));- }- else if (tag.equals("BYTES")) {- if (value != null) {- map.put(name, NumericUtilities.convertStringToBytes(value));- }- }- else if (tag.equals(STATE)) {- try {- if (type == null) {- // skip this element- }- else if (type.equals("byte")) {- map.put(name, Byte.valueOf(value));- }- else if (type.equals("short")) {- map.put(name, Short.valueOf(value));- }- else if (type.equals("int")) {- map.put(name, Integer.valueOf(value));- }- else if (type.equals("long")) {- map.put(name, Long.valueOf(value));- }- else if (type.equals("float")) {- map.put(name, Float.valueOf(value));- }- else if (type.equals("double")) {- map.put(name, Double.valueOf(value));- }- else if (type.equals("boolean")) {- map.put(name, Boolean.valueOf(value));- }- else if (type.equals("string")) {- String encodedValue = elem.getAttributeValue("ENCODED_VALUE");- if (value == null && encodedValue != null) {- byte[] strBytes = NumericUtilities.convertStringToBytes(encodedValue);- value = new String(strBytes, StandardCharsets.UTF_8);- }- map.put(name, value);- }- else if (type.equals("Color")) {- map.put(name, new Color(Integer.valueOf(value)));- }- else if (type.equals("Date")) {- map.put(name, DATE_FORMAT.parse(value));- }- else if (type.equals("File")) {- map.put(name, new File(value));- }- else if (type.equals("KeyStroke")) {- map.put(name, KeyStroke.getKeyStroke(value));- }- else if (type.equals("Font")) {- map.put(name, Font.decode(value));- }- }- catch (Exception e) {- Msg.warn(this, "Error processing primitive value in saveState", e);- }- }- else if (tag.equals("ARRAY")) {- if (type == null) {- continue;- }-- try {- List<?> list = elem.getChildren(ARRAY_ELEMENT_NAME);- Iterator<?> it = list.iterator();- int i = 0;- if (type.equals("short")) {- short[] vals = new short[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = Short.parseShort(e.getAttributeValue(VALUE));- }- map.put(name, vals);- }- else if (type.equals("int")) {- int[] vals = new int[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = Integer.parseInt(e.getAttributeValue(VALUE));- }- map.put(name, vals);- }- else if (type.equals("long")) {- long[] vals = new long[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = Long.parseLong(e.getAttributeValue(VALUE));- }- map.put(name, vals);- }- else if (type.equals("float")) {- float[] vals = new float[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = Float.parseFloat(e.getAttributeValue(VALUE));- }- map.put(name, vals);- }- else if (type.equals("double")) {- double[] vals = new double[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = Double.parseDouble(e.getAttributeValue(VALUE));- }- map.put(name, vals);- }- else if (type.equals("boolean")) {- boolean[] vals = new boolean[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = Boolean.valueOf(e.getAttributeValue(VALUE)).booleanValue();- }- map.put(name, vals);- }- else if (type.equals("string")) {- String[] vals = new String[list.size()];- while (it.hasNext()) {- Element e = (Element) it.next();- vals[i++] = e.getAttributeValue(VALUE);- }- map.put(name, vals);- }- }- catch (Exception exc) {- Msg.warn(this, "Error processing array value in saveState", exc);- }- }- else if (tag.equals("ENUM")) {- if (type == null) {- continue;- }- if (type.equals("stringenum")) {- // skip it, string enums are no longer supported- continue;- }- if (type.equals("enum")) {- String className = elem.getAttributeValue("CLASS");- Enum<?> e = getEnumValue(className, value);- if (e != null) {- map.put(name, e);- }- }- }- else if (tag.equals(SAVE_STATE)) {- Element element = (Element) elem.getChildren().get(0);- if (element != null) {- map.put(name, new SaveState(element));- }- }- else if (tag.equals("NULL")) {- map.put(name, null);- }- }- }-- protected SaveState(JsonObject root) {- this(root.get("SAVE_STATE_NAME").getAsString());- JsonObject values = root.get("VALUES").getAsJsonObject();- JsonObject types = root.get("TYPES").getAsJsonObject();- JsonObject enumClasses = root.get("ENUM_CLASSES").getAsJsonObject();-- for (String name : values.keySet()) {- String type = types.get(name).getAsString();- JsonElement valueElement = values.get(name);- JsonElement enumClass = enumClasses.get(name);- Object value = getObjectFromJson(type, valueElement, enumClass);- if (value != null) {- map.put(name, value);- }- }- }-- private Object getObjectFromJson(String type, JsonElement value, JsonElement enumClass) {-- switch (type) {- case "null":- return null;- case "String":- return value.getAsString();- case "Color":- return new Color(value.getAsInt());- case "Date":- return parseDate(value.getAsString());- case "File":- return new File(value.getAsString());- case "KeyStroke":- return KeyStroke.getKeyStroke(value.getAsString());- case "Font":- return Font.decode(value.getAsString());- case "byte":- return value.getAsByte();- case "short":- return value.getAsShort();- case "int":- return value.getAsInt();- case "long":- return value.getAsLong();- case "float":- return value.getAsFloat();- case "double":- return value.getAsDouble();- case "boolean":- return value.getAsBoolean();- case "byte[]":- JsonArray byteArray = value.getAsJsonArray();- byte[] bytes = new byte[byteArray.size()];- for (int i = 0; i < bytes.length; i++) {- bytes[i] = byteArray.get(i).getAsByte();- }- return bytes;- case "short[]":- JsonArray shortArray = value.getAsJsonArray();- short[] shorts = new short[shortArray.size()];- for (int i = 0; i < shorts.length; i++) {- shorts[i] = shortArray.get(i).getAsShort();- }- return shorts;- case "int[]":- JsonArray intArray = value.getAsJsonArray();- int[] ints = new int[intArray.size()];- for (int i = 0; i < ints.length; i++) {- ints[i] = intArray.get(i).getAsInt();- }- return ints;- case "long[]":- JsonArray longArray = value.getAsJsonArray();- long[] longs = new long[longArray.size()];- for (int i = 0; i < longs.length; i++) {- longs[i] = longArray.get(i).getAsLong();- }- return longs;- case "float[]":- JsonArray floatArray = value.getAsJsonArray();- float[] floats = new float[floatArray.size()];- for (int i = 0; i < floats.length; i++) {- floats[i] = floatArray.get(i).getAsFloat();- }- return floats;- case "double[]":- JsonArray doubleArray = value.getAsJsonArray();- double[] doubles = new double[doubleArray.size()];- for (int i = 0; i < doubles.length; i++) {- doubles[i] = doubleArray.get(i).getAsDouble();- }- return doubles;- case "boolean[]":- JsonArray boolArray = value.getAsJsonArray();- boolean[] booleans = new boolean[boolArray.size()];- for (int i = 0; i < booleans.length; i++) {- booleans[i] = boolArray.get(i).getAsBoolean();- }- return booleans;- case "String[]":- JsonArray stringArray = value.getAsJsonArray();- String[] strings = new String[stringArray.size()];- for (int i = 0; i < strings.length; i++) {- strings[i] = stringArray.get(i).getAsString();- }- return strings;- case "xml":- try {- return XmlUtilities.fromString(value.getAsString());- }- catch (JDOMException | IOException e) {- throw new AssertException("Error processing embedded XML");- }-- case "enum":- String enumClassName = enumClass.getAsString();- String enumValue = value.getAsString();- return getEnumValue(enumClassName, enumValue);-- case "SaveState":- JsonObject json = (JsonObject) value;- return new SaveState(json);-- default:- throw new AssertException("Unknown type: " + type);- }- }-- private Date parseDate(String dateString) {- try {- return DATE_FORMAT.parse(dateString);- }- catch (ParseException e) {- throw new AssertException("Can't parse date string: " + dateString);- }- }-- Enum<?> getEnumValue(String enumClassName, String value) {- try {- Class<?> enumClass = Class.forName(enumClassName).asSubclass(Enum.class);-- Method m = enumClass.getMethod("valueOf", new Class[] { String.class });- if (m != null) {- return (Enum<?>) m.invoke(null, new Object[] { value });- }- }- catch (Exception e) {- Msg.warn(this, "Can't find field " + value + " in enum class " + enumClassName, e);- }- return null;+ super(file);}- private static Element getXmlElementFromFile(File file) throws IOException {- byte[] bytes = FileUtilities.getBytesFromFile(file);- return XmlUtilities.byteArrayToXml(bytes);+ public SaveState(Element element) {+ super(element);}/*** Write the saveState to a file as XML* @param file the file to write to.- * @throws FileNotFoundException if the file does not represent a valid file path.* @throws IOException if the file could not be written*/- public void saveToFile(File file) throws FileNotFoundException, IOException {- Element saveToXml = saveToXml();- byte[] bytes = XmlUtilities.xmlToByteArray(saveToXml);- FileUtilities.writeBytes(file, bytes);- }-- /**- * Outputs this SaveState to a file using Json- * <P>- * For example, a SaveState that is created with:- * <pre>- * ss = new SaveState("foo")- * ss.putString("Name", "Bob");- * ss.putBoolean("Retired", true);- * ss.putInt("Age", 65);- * ss.putEnum("Endian", Endian.BIG);- *- * would produce a Json file with the following text- *- * {- * "SAVE STATE NAME": "foo",- * "VALUES": {- * "Name": "Bob"- * "Retired": true,- * "Age": 65,- * "Endian": "BIG",- * },- * "TYPES": {- * "Name": "String"- * "Retired": "boolean",- * "Age": "int",- * "Endian": "enum",- * },- * "ENUM CLASSES": {- * "Endian": "ghidra.program.model.lang.Endian"- * }- *}- * </pre>- *- * @param file the file to save to- * @throws IOException if an error occurs writing to the given file- */- public void saveToJsonFile(File file) throws IOException {- Gson gson = new GsonBuilder().setPrettyPrinting().create();- JsonObject saveToJson = saveToJson();- try (FileWriter writer = new FileWriter(file)) {- writer.write(gson.toJson(saveToJson));- }- }-- /**- * Save this object to an XML element.- * @return Element XML element containing the state- */- public Element saveToXml() {- Element root = new Element(saveStateName);- Iterator<String> iter = map.keySet().iterator();- while (iter.hasNext()) {- String key = iter.next();- Object value = map.get(key);- Element elem = null;- if (value instanceof Element) {- elem = createElementFromElement(key, (Element) value);- }- else if (value instanceof Byte) {- elem = setAttributes(key, "byte", ((Byte) value).toString());- }- else if (value instanceof Short) {- elem = setAttributes(key, "short", ((Short) value).toString());- }- else if (value instanceof Integer) {- elem = setAttributes(key, "int", ((Integer) value).toString());- }- else if (value instanceof Long) {- elem = setAttributes(key, "long", ((Long) value).toString());- }- else if (value instanceof Float) {- elem = setAttributes(key, "float", ((Float) value).toString());- }- else if (value instanceof Double) {- elem = setAttributes(key, "double", ((Double) value).toString());- }- else if (value instanceof Boolean) {- elem = setAttributes(key, "boolean", ((Boolean) value).toString());- }- else if (value instanceof String) {- elem = new Element(STATE);- elem.setAttribute(NAME, key);- elem.setAttribute(TYPE, "string");- if (XmlUtilities.hasInvalidXMLCharacters((String) value)) {- elem.setAttribute("ENCODED_VALUE", NumericUtilities.convertBytesToString(- ((String) value).getBytes(StandardCharsets.UTF_8)));- }- else {- elem.setAttribute(VALUE, (String) value);- }- }- else if (value instanceof Color) {- elem = setAttributes(key, "Color", Integer.toString(((Color) value).getRGB()));- }- else if (value instanceof Date) {- elem = setAttributes(key, "Date", DATE_FORMAT.format((Date) value));- }- else if (value instanceof File) {- elem = setAttributes(key, "File", ((File) value).getAbsolutePath());- }- else if (value instanceof KeyStroke) {- elem = setAttributes(key, "KeyStroke", value.toString());- }- else if (value instanceof Font font) {- elem = setAttributes(key, "Font", toFontString(font));- }- else if (value instanceof byte[]) {- elem = new Element("BYTES");- elem.setAttribute(NAME, key);- elem.setAttribute(VALUE, NumericUtilities.convertBytesToString((byte[]) value));- }- else if (value instanceof short[]) {- elem = setArrayAttributes(key, "short", value);- }- else if (value instanceof int[]) {- elem = setArrayAttributes(key, "int", value);- }- else if (value instanceof long[]) {- elem = setArrayAttributes(key, "long", value);- }- else if (value instanceof float[]) {- elem = setArrayAttributes(key, "float", value);- }- else if (value instanceof double[]) {- elem = setArrayAttributes(key, "double", value);- }- else if (value instanceof boolean[]) {- elem = setArrayAttributes(key, "boolean", value);- }- else if (value instanceof String[]) {- elem = setArrayAttributes(key, "string", value);- }- else if (value instanceof Enum) {- Enum<?> e = (Enum<?>) value;- elem = new Element("ENUM");- elem.setAttribute(NAME, key);- elem.setAttribute(TYPE, "enum");- elem.setAttribute("CLASS", e.getClass().getName());- elem.setAttribute(VALUE, e.name());- }- else if (value instanceof SaveState) {- Element element = ((SaveState) value).saveToXml();- elem = new Element(SAVE_STATE);- elem.setAttribute(NAME, key);- elem.setAttribute(TYPE, "SaveState");- elem.addContent(element);- }- else {- elem = new Element("NULL");- elem.setAttribute(NAME, key);- }- root.addContent(elem);- }- return root;- }-- private <T> Element setArrayAttributes(String key, String type, Object values) {- Element elem = new Element("ARRAY");- elem.setAttribute(NAME, key);- elem.setAttribute(TYPE, type);- for (int i = 0; i < Array.getLength(values); i++) {- Object value = Array.get(values, i);- if (value != null) {- Element arrElem = new Element(ARRAY_ELEMENT_NAME);- arrElem.setAttribute(VALUE, value.toString());- elem.addContent(arrElem);- }- }- return elem;- }-- private Element setAttributes(String key, String type, String value) {- Element elem;- elem = new Element(STATE);- elem.setAttribute(NAME, key);- elem.setAttribute(TYPE, type);- elem.setAttribute(VALUE, value);- return elem;- }-- /**- * Save this object to an JsonObject- *- * @return JsonObject containing the state- */- public JsonObject saveToJson() {- JsonObject types = new JsonObject();- JsonObject values = new JsonObject();- JsonObject enumClasses = new JsonObject();- Iterator<String> iter = map.keySet().iterator();- while (iter.hasNext()) {- String key = iter.next();- Object value = map.get(key);- if (value == null) {- types.addProperty(key, "null");- values.addProperty(key, "null");- }- else if (value instanceof Element) {- types.addProperty(key, "xml");- String outputString = new XMLOutputter().outputString((Element) value);- values.addProperty(key, outputString);- }- else if (value instanceof Color) {- types.addProperty(key, "Color");- values.addProperty(key, ((Color) value).getRGB());- }- else if (value instanceof Date) {- types.addProperty(key, "Date");- values.addProperty(key, DATE_FORMAT.format((Date) value));- }- else if (value instanceof File) {- types.addProperty(key, "File");- values.addProperty(key, ((File) value).getAbsolutePath());- }- else if (value instanceof KeyStroke) {- types.addProperty(key, "KeyStroke");- values.addProperty(key, value.toString());- }- else if (value instanceof Font font) {- types.addProperty(key, "Font");- values.addProperty(key, toFontString(font));- }- else if (value instanceof Byte) {- types.addProperty(key, "byte");- values.addProperty(key, (Byte) value);- }- else if (value instanceof Short) {- types.addProperty(key, "short");- values.addProperty(key, (Short) value);- }- else if (value instanceof Integer) {- types.addProperty(key, "int");- values.addProperty(key, (Integer) value);- }- else if (value instanceof Long) {- types.addProperty(key, "long");- values.addProperty(key, (Long) value);- }- else if (value instanceof Float) {- types.addProperty(key, "float");- values.addProperty(key, (Float) value);- }- else if (value instanceof Double) {- types.addProperty(key, "double");- values.addProperty(key, (Double) value);- }- else if (value instanceof Boolean) {- types.addProperty(key, "boolean");- values.addProperty(key, (Boolean) value);- }- else if (value instanceof String) {- types.addProperty(key, "String");- values.addProperty(key, (String) value);- }- else if (value instanceof byte[]) {- JsonArray ja = new JsonArray();- for (byte b : (byte[]) value) {- ja.add(b);- }- types.addProperty(key, "byte[]");- values.add(key, ja);- }- else if (value instanceof short[]) {- JsonArray ja = new JsonArray();- for (short s : (short[]) value) {- ja.add(s);- }- types.addProperty(key, "short[]");- values.add(key, ja);- }- else if (value instanceof int[]) {- JsonArray ja = new JsonArray();- for (int i : (int[]) value) {- ja.add(i);- }- types.addProperty(key, "int[]");- values.add(key, ja);- }- else if (value instanceof long[]) {- JsonArray ja = new JsonArray();- for (long i : (long[]) value) {- ja.add(i);- }- types.addProperty(key, "long[]");- values.add(key, ja);- }- else if (value instanceof float[]) {- JsonArray ja = new JsonArray();- for (float f : (float[]) value) {- ja.add(f);- }- types.addProperty(key, "float[]");- values.add(key, ja);- }- else if (value instanceof double[]) {- JsonArray ja = new JsonArray();- for (double f : (double[]) value) {- ja.add(f);- }- types.addProperty(key, "double[]");- values.add(key, ja);- }- else if (value instanceof boolean[]) {- JsonArray ja = new JsonArray();- for (boolean b : (boolean[]) value) {- ja.add(b);- }- types.addProperty(key, "boolean[]");- values.add(key, ja);- }- else if (value instanceof String[]) {- JsonArray ja = new JsonArray();- for (String s : (String[]) value) {- if (s != null) {- ja.add(s);- }- }- types.addProperty(key, "String[]");- values.add(key, ja);- }- else if (value instanceof Enum) {- Enum<?> e = (Enum<?>) value;- types.addProperty(key, "enum");- enumClasses.addProperty(key, e.getClass().getName());- values.addProperty(key, e.name());- }- else if (value instanceof SaveState) {- types.addProperty(key, "SaveState");- JsonObject json = ((SaveState) value).saveToJson();- values.add(key, json);- }- else {- throw new AssertException("found unsupported object type: " + value.getClass());- }- }- JsonObject jsonObject = new JsonObject();- jsonObject.addProperty("SAVE_STATE_NAME", saveStateName);- jsonObject.add("VALUES", values);- jsonObject.add("TYPES", types);- jsonObject.add("ENUM_CLASSES", enumClasses);- return jsonObject;- }-- protected Element createElementFromElement(String internalKey, Element internalElement) {- Element newElement = new Element("XML");- newElement.setAttribute(NAME, internalKey);-- Element internalElementClone = (Element) internalElement.clone();- newElement.addContent(internalElementClone);-- return newElement;- }-- /**- * Returns true if this list contains no elements- * @return true if there are no properties in this save state- */- public boolean isEmpty() {- return map.isEmpty();- }-- /**- * Remove the object identified by the given name- *- * @param name the name of the property to remove- */- public void remove(String name) {- map.remove(name);- }-- /**- * Clear all objects from the save state.- */- public void clear() {- map.clear();- }-- /**- * Return the number of properties in the save state- * @return The number of properties in the save state- */- public int size() {- return map.size();- }-- /**- * Return the names of the objects saved in the state.- * @return String[] array will be zero length if the save state- * is empty- */- public String[] getNames() {- String[] names = new String[map.size()];- int idx = 0;- Iterator<String> iter = map.keySet().iterator();- while (iter.hasNext()) {- names[idx] = iter.next();- ++idx;- }- return names;- }-- //////////////////////////////////////////////////////////////-- void putObject(String name, Object obj) {- map.put(name, obj);- }-- Object getObject(String name) {- return map.get(name);- }-- //////////////////////////////////////////////////////////////-- /**- * Associates an integer value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putInt(String name, int value) {- map.put(name, Integer.valueOf(value));- }-- /**- * Associates a byte value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putByte(String name, byte value) {- map.put(name, Byte.valueOf(value));- }-- /**- * Associates a short value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putShort(String name, short value) {- map.put(name, Short.valueOf(value));- }-- /**- * Associates a long value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putLong(String name, long value) {- map.put(name, Long.valueOf(value));- }-- /**- * Associates a String value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putString(String name, String value) {- map.put(name, value);- }-- /**- * Associates a Color value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putColor(String name, Color value) {- map.put(name, value);- }-- /**- * Associates a Date value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putDate(String name, Date value) {- map.put(name, value);- }-- /**- * Associates a File value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putFile(String name, File value) {- map.put(name, value);- }-- /**- * Associates a KeyStroke value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putKeyStroke(String name, KeyStroke value) {- map.put(name, value);- }-- /**- * Associates a Font value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putFont(String name, Font value) {- map.put(name, value);- }-- /**- * Associates a boolean value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putBoolean(String name, boolean value) {- map.put(name, Boolean.valueOf(value));- }-- /**- * Associates a float value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putFloat(String name, float value) {- map.put(name, Float.valueOf(value));- }-- /**- * Associates a double value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putDouble(String name, double value) {- map.put(name, Double.valueOf(value));+ public void saveToFile(File file) throws IOException {+ saveToXmlFile(file);}/**@@ -1001,401 +103,6 @@ public class SaveState {map.put(name, value);}- /**- * Gets the int value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the int value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public int getInt(String name, int defaultValue) {- return getAsType(name, defaultValue, Integer.class);- }-- /**- * Gets the byte value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the byte value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public byte getByte(String name, byte defaultValue) {- return getAsType(name, defaultValue, Byte.class);- }-- /**- * Gets the short value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the short value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public short getShort(String name, short defaultValue) {- return getAsType(name, defaultValue, Short.class);- }-- /**- * Gets the long value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the long value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public long getLong(String name, long defaultValue) {- return getAsType(name, defaultValue, Long.class);- }-- /**- * Gets the boolean value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the boolean value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public boolean getBoolean(String name, boolean defaultValue) {- return getAsType(name, defaultValue, Boolean.class);- }-- /**- * Gets the String value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the String value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public String getString(String name, String defaultValue) {- return getAsType(name, defaultValue, String.class);- }-- /**- * Gets the Color value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the Color value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public Color getColor(String name, Color defaultValue) {- return getAsType(name, defaultValue, Color.class);- }-- /**- * Gets the Date value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the Date value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public Date getDate(String name, Date defaultValue) {- return getAsType(name, defaultValue, Date.class);- }-- /**- * Gets the File value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the File value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public File getFile(String name, File defaultValue) {- return getAsType(name, defaultValue, File.class);- }-- /**- * Gets the KeyStroke value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the KeyStroke value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public KeyStroke getKeyStroke(String name, KeyStroke defaultValue) {- return getAsType(name, defaultValue, KeyStroke.class);- }-- /**- * Gets the Font value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the Font value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public Font getFont(String name, Font defaultValue) {- return getAsType(name, defaultValue, Font.class);- }-- /**- * Gets the float value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the float value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public float getFloat(String name, float defaultValue) {- return getAsType(name, defaultValue, Float.class);- }-- /**- * Gets the double value for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the double value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public double getDouble(String name, double defaultValue) {- return getAsType(name, defaultValue, Double.class);- }-- /**- * Associates an integer array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putInts(String name, int[] value) {- map.put(name, value);- }-- /**- * Associates a byte array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putBytes(String name, byte[] value) {- map.put(name, value);- }-- /**- * Associates a short array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putShorts(String name, short[] value) {- map.put(name, value);- }-- /**- * Associates a long array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putLongs(String name, long[] value) {- map.put(name, value);- }-- /**- * Associates a String array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putStrings(String name, String[] value) {- map.put(name, value);- }-- /**- * Associates an Enum with the given name.- * @param name The name in the name,value pair.- * @param value The Enum value in the name,value pair.- */- public void putEnum(String name, Enum<?> value) {- if ((value.getClass().getModifiers() & Modifier.PUBLIC) == 0) {- throw new IllegalArgumentException("enum '" + value.name() + "' must be public");- }- map.put(name, value);- }-- /**- * Associates a boolean array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putBooleans(String name, boolean[] value) {- map.put(name, value);- }-- /**- * Associates a float array with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putFloats(String name, float[] value) {- map.put(name, value);- }-- /**- * Associates a double value with the given name.- * @param name The name in the name,value pair.- * @param value The value in the name,value pair.- */- public void putDoubles(String name, double[] value) {- map.put(name, value);- }-- /**- * Gets the int array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the int array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public int[] getInts(String name, int[] defaultValue) {- return map.containsKey(name) ? (int[]) map.get(name) : defaultValue;- }-- /**- * Gets the byte array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the byte array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public byte[] getBytes(String name, byte[] defaultValue) {- return map.containsKey(name) ? (byte[]) map.get(name) : defaultValue;- }-- /**- * Gets the short array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the short array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public short[] getShorts(String name, short[] defaultValue) {- return map.containsKey(name) ? (short[]) map.get(name) : defaultValue;- }-- /**- * Gets the long array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the long array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public long[] getLongs(String name, long[] defaultValue) {- return map.containsKey(name) ? (long[]) map.get(name) : defaultValue;- }-- /**- * Gets the boolean array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the boolean array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public boolean[] getBooleans(String name, boolean[] defaultValue) {- return map.containsKey(name) ? (boolean[]) map.get(name) : defaultValue;- }-- /**- * Gets the String array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the String array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public String[] getStrings(String name, String[] defaultValue) {- return map.containsKey(name) ? (String[]) map.get(name) : defaultValue;- }-- /**- * Gets the Enum value for the given name.- * @param name the name of the pair.- * @param defaultValue the default Enum value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the Enum value associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- @SuppressWarnings("unchecked")- public <T extends Enum<T>> T getEnum(String name, T defaultValue) {- if (defaultValue != null &&- (defaultValue.getClass().getModifiers() & Modifier.PUBLIC) == 0) {- throw new IllegalArgumentException("enum '" + defaultValue.name() + "' must be public");- }- try {- if (map.containsKey(name)) {- return (T) map.get(name);- }- }- catch (ClassCastException e) {- // Facilitate transition from StringEnum to Enum- map.put(name, defaultValue);- }- return defaultValue;- }-- /**- * Gets the float array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the float array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public float[] getFloats(String name, float[] defaultValue) {- return map.containsKey(name) ? (float[]) map.get(name) : defaultValue;- }-- /**- * Gets the double array for the given name.- * @param name the name of the pair.- * @param defaultValue the default value to be returned if the name does- * not exist in the map, or it does not contain the proper object type.- * @return the double array associated with the given name or the defaultValue- * passed in if the name doesn't exist or is the wrong type.- */- public double[] getDoubles(String name, double[] defaultValue) {- return map.containsKey(name) ? (double[]) map.get(name) : defaultValue;- }-- /**- * Returns true if there is a value for the given name- *- * @param name true the name of the property to check for a value- * @return true if the SaveState object has a value for the given name- */- public boolean hasValue(String name) {- return map.containsKey(name);- }-- /**- * Adds an XML element to the- * saved state object. Used by plugins that have more- * complicated state information that needs to be saved.- * @param name the name to associate with the element- * @param element XML element which is the root of an- * XML sub-tree.- */- public void putXmlElement(String name, Element element) {- map.put(name, element);- }-- /**- * Returns the root of an XML sub-tree associated with the- * given name.- * @param name The name associated with the desired Element.- * @return The root of an XML sub-tree associated with the- * given name.- */- public Element getXmlElement(String name) {- return getAsType(name, null, Element.class);- }-/*** Returns the sub SaveState associated with the* given name.@@ -1407,49 +114,30 @@ public class SaveState {return getAsType(name, null, SaveState.class);}- @Override- public String toString() {- return XmlUtilities.toString(saveToXml());- }+ protected void processElement(Element element) {+ String tag = element.getName();- private <T> T getAsType(String name, T defaultValue, Class<T> clazz) {- if (map.containsKey(name)) {- Object value = map.get(name);- if (isExpectedType(name, value, clazz)) {- return clazz.cast(value);+ if (tag.equals("SAVE_STATE")) {+ Element child = (Element) element.getChildren().get(0);+ if (child != null) {+ String name = element.getAttributeValue(NAME);+ map.put(name, new SaveState(child));+ return;}}- return defaultValue;-- }-- private boolean isExpectedType(String name, Object value, Class<?> expectedType) {- if (value != null && !expectedType.isInstance(value)) {- Msg.debug(this,- "Type mismatch on saveState property \"" + name +- "\". Attempted to retrieve value as a " + expectedType.getName() +- " but was of type " + value.getClass().getName());- return false;- }- return true;+ super.processElement(element);}- private String toFontString(Font font) {- return String.format("%s-%s-%s", font.getName(), getStyleString(font), font.getSize());- }-- private String getStyleString(Font font) {- boolean bold = font.isBold();- boolean italic = font.isItalic();- if (bold && italic) {- return "BOLDITALIC";- }- if (bold) {- return "BOLD";- }- if (italic) {- return "ITALIC";- }- return "PLAIN";+ @Override+ protected Element createElement(String key, Object value) {+ if (value instanceof SaveState saveState) {+ Element savedElement = saveState.saveToXml();+ Element element = new Element("SAVE_STATE");+ element.setAttribute(NAME, key);+ element.setAttribute(TYPE, "SaveState");+ element.addContent(savedElement);+ return element;+ }+ return super.createElement(key, value);}}diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/XmlProperties.java b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/XmlProperties.javanew file mode 100644index 0000000000..ab0c89417e--- /dev/null+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/framework/options/XmlProperties.java@@ -0,0 +1,49 @@+/* ###+ * 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.framework.options;++import java.io.File;+import java.io.IOException;++import org.jdom.Element;++import ghidra.util.xml.XmlUtilities;+import utilities.util.FileUtilities;++/**+ * A convenience class for creating a GProperties object from a file containing XML data+ * generated from {@link GProperties#saveToXmlFile(File)}+ */+public class XmlProperties extends GProperties {++ public XmlProperties(File file) throws IOException {+ super(getXmlElement(file));+ }++ public XmlProperties(Element element) {+ super(element);+ }++ protected XmlProperties(String name) {+ super(name);+ }++ private static Element getXmlElement(File file) throws IOException {+ byte[] bytes = FileUtilities.getBytesFromFile(file);+ return XmlUtilities.byteArrayToXml(bytes);+ }++}diff --git a/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/CustomOption.java b/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/CustomOption.javaindex d5fe87f61e..cc27a7f9f8 100644--- a/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/CustomOption.java+++ b/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/CustomOption.java@@ -29,16 +29,16 @@ public interface CustomOption {/*** Concrete subclass of WrappedOption should read all of its* state from the given saveState object.- * @param saveState container of state information+ * @param properties container of state information*/- public void readState(SaveState saveState);+ public void readState(GProperties properties);/*** Concrete subclass of WrappedOption should write all of its* state to the given saveState object.- * @param saveState container of state information+ * @param properties container of state information*/- public void writeState(SaveState saveState);+ public void writeState(GProperties properties);/*** CustomOption should implement this method to provide a formatteddiff --git a/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/FileOptions.java b/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/FileOptions.javaindex 29da331428..3f29a7541a 100644--- a/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/FileOptions.java+++ b/Ghidra/Framework/Gui/src/main/java/ghidra/framework/options/FileOptions.java@@ -48,12 +48,12 @@ public class FileOptions extends AbstractOptions {return file;}- public CustomOption readCustomOption(SaveState saveState) {- String customOptionClassName = saveState.getString("CUSTOM_OPTION_CLASS", null);+ public CustomOption readCustomOption(GProperties properties) {+ String customOptionClassName = properties.getString("CUSTOM_OPTION_CLASS", null);try {Class<?> c = Class.forName(customOptionClassName);CustomOption customOption = (CustomOption) c.getDeclaredConstructor().newInstance();- customOption.readState(saveState);+ customOption.readState(properties);return customOption;}catch (Exception e) {@@ -63,11 +63,10 @@ public class FileOptions extends AbstractOptions {}private void loadFromFile() throws IOException {- SaveState saveState = SaveState.readJsonFile(file);- for (String optionName : saveState.getNames()) {- Object object = saveState.getObject(optionName);- if (object instanceof SaveState) {- SaveState customState = (SaveState) object;+ GProperties properties = new JSonProperties(file);+ for (String optionName : properties.getNames()) {+ Object object = properties.getObject(optionName);+ if (object instanceof GProperties customState) {object = readCustomOption(customState);}Option option =