diff --git a/java_console/.idea/libraries/jep.xml b/java_console/.idea/libraries/jep.xml new file mode 100644 index 0000000000..70023f8067 --- /dev/null +++ b/java_console/.idea/libraries/jep.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/java_console/.idea/libraries/swing_layout_1_0.xml b/java_console/.idea/libraries/swing_layout_1_0.xml new file mode 100644 index 0000000000..4893bfcb0c --- /dev/null +++ b/java_console/.idea/libraries/swing_layout_1_0.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/java_console/lib/jep.jar b/java_console/lib/jep.jar new file mode 100644 index 0000000000..926b295a92 Binary files /dev/null and b/java_console/lib/jep.jar differ diff --git a/java_console/lib/swing-layout-1.0.jar b/java_console/lib/swing-layout-1.0.jar new file mode 100644 index 0000000000..50f159011a Binary files /dev/null and b/java_console/lib/swing-layout-1.0.jar differ diff --git a/java_console/romraider/resources/graphics/1d.gif b/java_console/romraider/resources/graphics/1d.gif new file mode 100644 index 0000000000..9b263a08ca Binary files /dev/null and b/java_console/romraider/resources/graphics/1d.gif differ diff --git a/java_console/romraider/resources/graphics/2d.gif b/java_console/romraider/resources/graphics/2d.gif new file mode 100644 index 0000000000..f925371dae Binary files /dev/null and b/java_console/romraider/resources/graphics/2d.gif differ diff --git a/java_console/romraider/resources/graphics/3d.gif b/java_console/romraider/resources/graphics/3d.gif new file mode 100644 index 0000000000..11b2f1f969 Binary files /dev/null and b/java_console/romraider/resources/graphics/3d.gif differ diff --git a/java_console/romraider/resources/graphics/3d_render.png b/java_console/romraider/resources/graphics/3d_render.png new file mode 100644 index 0000000000..b9ef82870e Binary files /dev/null and b/java_console/romraider/resources/graphics/3d_render.png differ diff --git a/java_console/romraider/resources/graphics/icon-close.png b/java_console/romraider/resources/graphics/icon-close.png new file mode 100644 index 0000000000..0fcb3075b4 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-close.png differ diff --git a/java_console/romraider/resources/graphics/icon-deccoarse.png b/java_console/romraider/resources/graphics/icon-deccoarse.png new file mode 100644 index 0000000000..a19369127d Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-deccoarse.png differ diff --git a/java_console/romraider/resources/graphics/icon-decfine.png b/java_console/romraider/resources/graphics/icon-decfine.png new file mode 100644 index 0000000000..8e9ee95160 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-decfine.png differ diff --git a/java_console/romraider/resources/graphics/icon-inccoarse.png b/java_console/romraider/resources/graphics/icon-inccoarse.png new file mode 100644 index 0000000000..20feaee6e7 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-inccoarse.png differ diff --git a/java_console/romraider/resources/graphics/icon-incfine.png b/java_console/romraider/resources/graphics/icon-incfine.png new file mode 100644 index 0000000000..4badc746c4 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-incfine.png differ diff --git a/java_console/romraider/resources/graphics/icon-open.png b/java_console/romraider/resources/graphics/icon-open.png new file mode 100644 index 0000000000..a63492d04f Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-open.png differ diff --git a/java_console/romraider/resources/graphics/icon-palette.png b/java_console/romraider/resources/graphics/icon-palette.png new file mode 100644 index 0000000000..035c927376 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-palette.png differ diff --git a/java_console/romraider/resources/graphics/icon-save.png b/java_console/romraider/resources/graphics/icon-save.png new file mode 100644 index 0000000000..5a40f66e29 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-save.png differ diff --git a/java_console/romraider/resources/graphics/icon-smooth.ico b/java_console/romraider/resources/graphics/icon-smooth.ico new file mode 100644 index 0000000000..fee26db5c0 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-smooth.ico differ diff --git a/java_console/romraider/resources/graphics/icon-smooth.png b/java_console/romraider/resources/graphics/icon-smooth.png new file mode 100644 index 0000000000..87fda8b2e0 Binary files /dev/null and b/java_console/romraider/resources/graphics/icon-smooth.png differ diff --git a/java_console/romraider/resources/graphics/logger_blue.png b/java_console/romraider/resources/graphics/logger_blue.png new file mode 100644 index 0000000000..411b2e696a Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_blue.png differ diff --git a/java_console/romraider/resources/graphics/logger_green.png b/java_console/romraider/resources/graphics/logger_green.png new file mode 100644 index 0000000000..764d5582ae Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_green.png differ diff --git a/java_console/romraider/resources/graphics/logger_log_to_file.png b/java_console/romraider/resources/graphics/logger_log_to_file.png new file mode 100644 index 0000000000..da20009c6e Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_log_to_file.png differ diff --git a/java_console/romraider/resources/graphics/logger_recording.png b/java_console/romraider/resources/graphics/logger_recording.png new file mode 100644 index 0000000000..7abf4250a2 Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_recording.png differ diff --git a/java_console/romraider/resources/graphics/logger_red.png b/java_console/romraider/resources/graphics/logger_red.png new file mode 100644 index 0000000000..53816d9521 Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_red.png differ diff --git a/java_console/romraider/resources/graphics/logger_restart.png b/java_console/romraider/resources/graphics/logger_restart.png new file mode 100644 index 0000000000..383e3579d2 Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_restart.png differ diff --git a/java_console/romraider/resources/graphics/logger_stop.png b/java_console/romraider/resources/graphics/logger_stop.png new file mode 100644 index 0000000000..dc05ac60e4 Binary files /dev/null and b/java_console/romraider/resources/graphics/logger_stop.png differ diff --git a/java_console/romraider/resources/graphics/romraider-ico-large.gif b/java_console/romraider/resources/graphics/romraider-ico-large.gif new file mode 100644 index 0000000000..c926be8fef Binary files /dev/null and b/java_console/romraider/resources/graphics/romraider-ico-large.gif differ diff --git a/java_console/romraider/resources/graphics/romraider-ico.gif b/java_console/romraider/resources/graphics/romraider-ico.gif new file mode 100644 index 0000000000..d379c14b6e Binary files /dev/null and b/java_console/romraider/resources/graphics/romraider-ico.gif differ diff --git a/java_console/romraider/resources/graphics/romraider-ico.ico b/java_console/romraider/resources/graphics/romraider-ico.ico new file mode 100644 index 0000000000..9fb4931601 Binary files /dev/null and b/java_console/romraider/resources/graphics/romraider-ico.ico differ diff --git a/java_console/romraider/resources/graphics/splash.bmp b/java_console/romraider/resources/graphics/splash.bmp new file mode 100644 index 0000000000..71345c70c0 Binary files /dev/null and b/java_console/romraider/resources/graphics/splash.bmp differ diff --git a/java_console/romraider/resources/graphics/switch.gif b/java_console/romraider/resources/graphics/switch.gif new file mode 100644 index 0000000000..09f5a09661 Binary files /dev/null and b/java_console/romraider/resources/graphics/switch.gif differ diff --git a/java_console/romraider/romraider.iml b/java_console/romraider/romraider.iml index 015c172575..ea38c34862 100644 --- a/java_console/romraider/romraider.iml +++ b/java_console/romraider/romraider.iml @@ -9,5 +9,7 @@ + + \ No newline at end of file diff --git a/java_console/romraider/src/ZoeloeSoft/projects/JFontChooser/JFontChooser.java b/java_console/romraider/src/ZoeloeSoft/projects/JFontChooser/JFontChooser.java new file mode 100644 index 0000000000..0039a45efc --- /dev/null +++ b/java_console/romraider/src/ZoeloeSoft/projects/JFontChooser/JFontChooser.java @@ -0,0 +1,271 @@ +/******************************************************************************** + * ********************************************************* * + * * $Package: ZoeloeSoft.projects.JFontChooser * * + * * $Id: JFontChooser.java * * + * * $Date: 23:39 19/04/2004 * * + * * * * + * * $Creator: Tim Eeckhaut * * + * * $Alias: zoeloeboeloe * * + * * * * + * * $Company: ZoeloeSoft * * + * * $Website: http://users.pandora.be/ZoeloeSof * * + * ********************************************************* * + * * + * Copyright (c) 2004, Tim Eeckhaut * + * All rights reserved. * + * * + * Redistribution and use in source and binary forms, with or without * + * modification, are permitted provided that the following conditions * + * are met: * + * * + * 1. Redistributions of source code must retain the above copyright * + * notice, this list of conditions and the following disclaimer. * + * * + * 2. Redistributions in binary form must reproduce the above copyright * + * notice, this list of conditions and the following disclaimer in the * + * documentation and/or other materials provided with the distribution. * + * * + * 3. Neither the name of the company nor the names of its * + * contributors may be used to endorse or promote products derived from this * + * software without specific prior written permission. * + * * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR * + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * + * * + ********************************************************************************/ + + +package ZoeloeSoft.projects.JFontChooser; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +public class JFontChooser extends JDialog +{ + public static int OK_OPTION = 0; + public static int CANCEL_OPTION = 1; + + private JList fontList, sizeList; + private JCheckBox cbBold, cbItalic; + private JTextArea txtSample; + + private int OPTION; + + private final String[] sizes = new String[] + { "2","4","6","8","10","11","12","13","14","16","18","20","22","24","30","36","48","72" }; + + public int showDialog(Font font) + { + setFont(font); + return showDialog(); + } + + public int showDialog() + { + setVisible(true); + + return OPTION; + } + + public JFontChooser(Frame parent) + { + super(parent, true); + setTitle("JFontChooser"); + + OPTION = JFontChooser.CANCEL_OPTION; + + + // create all components + + JButton btnOK = new JButton("OK"); + btnOK.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + JFontChooser.this.OPTION = JFontChooser.OK_OPTION; + JFontChooser.this.setVisible(false); + } + }); + + + JButton btnCancel = new JButton("Cancel"); + btnCancel.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + JFontChooser.this.OPTION = JFontChooser.CANCEL_OPTION; + JFontChooser.this.setVisible(false); + } + }); + + + fontList = new JList(GraphicsEnvironment.getLocalGraphicsEnvironment(). + getAvailableFontFamilyNames()) + { + @Override + public Dimension getPreferredScrollableViewportSize() + { return new Dimension(150, 144); } + }; + fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + + sizeList = new JList(sizes) + { + @Override + public Dimension getPreferredScrollableViewportSize() + { return new Dimension(25, 144); } + }; + sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + + cbBold = new JCheckBox("Bold"); + + cbItalic = new JCheckBox("Italic"); + + + txtSample = new JTextArea() + { + @Override + public Dimension getPreferredScrollableViewportSize() + { return new Dimension(385, 80); } + }; + txtSample.setFont(new Font("Monospaced", Font.PLAIN, 12)); + txtSample.setText("The quick brown fox jumped over the fence"); + + // set the default font + + setFont(null); + + + // add the listeners + + ListSelectionListener listListener = new ListSelectionListener() + { + @Override + public void valueChanged(ListSelectionEvent e) + { txtSample.setFont(getCurrentFont()); } + }; + + fontList.addListSelectionListener(listListener); + sizeList.addListSelectionListener(listListener); + + + ActionListener cbListener = new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { txtSample.setFont(getCurrentFont()); } + }; + + cbBold.addActionListener(cbListener); + cbItalic.addActionListener(cbListener); + + // build the container + + getContentPane().setLayout(new java.awt.BorderLayout()); + + JPanel leftPanel = new JPanel(); + leftPanel.setLayout(new java.awt.BorderLayout()); + + leftPanel.add(new JScrollPane(fontList), java.awt.BorderLayout.CENTER); + leftPanel.add(new JScrollPane(sizeList), java.awt.BorderLayout.EAST); + + getContentPane().add(leftPanel, java.awt.BorderLayout.CENTER); + + + JPanel rightPanel = new JPanel(); + rightPanel.setLayout(new java.awt.BorderLayout()); + + JPanel rightPanelSub1 = new JPanel(); + rightPanelSub1.setLayout(new java.awt.FlowLayout()); + + rightPanelSub1.add(cbBold); + rightPanelSub1.add(cbItalic); + + rightPanel.add(rightPanelSub1, java.awt.BorderLayout.NORTH); + + JPanel rightPanelSub2 = new JPanel(); + rightPanelSub2.setLayout(new java.awt.GridLayout(2, 1)); + + rightPanelSub2.add(btnOK); + rightPanelSub2.add(btnCancel); + + rightPanel.add(rightPanelSub2, java.awt.BorderLayout.SOUTH); + + getContentPane().add(rightPanel, java.awt.BorderLayout.EAST); + + getContentPane().add(new JScrollPane(txtSample), java.awt.BorderLayout.SOUTH); + + setSize(200, 200); + setResizable(false); + + pack(); + } + + @Override + public void setFont(Font font) + { + if (font == null) font = txtSample.getFont(); + + fontList.setSelectedValue(font.getName(), true); + fontList.ensureIndexIsVisible(fontList.getSelectedIndex()); + sizeList.setSelectedValue("" + font.getSize(), true); + sizeList.ensureIndexIsVisible(sizeList.getSelectedIndex()); + + cbBold.setSelected(font.isBold()); + cbItalic.setSelected(font.isItalic()); + } + + @Override + public Font getFont() + { + if (OPTION == OK_OPTION) + { + return getCurrentFont(); + } + else return null; + } + + private Font getCurrentFont() + { + try { + String fontFamily = (String)fontList.getSelectedValue(); + int fontSize = Integer.parseInt((String)sizeList.getSelectedValue()); + + int fontType = Font.PLAIN; + + if (cbBold.isSelected()) fontType += Font.BOLD; + if (cbItalic.isSelected()) fontType += Font.ITALIC; + return new Font(fontFamily, fontType, fontSize); + } catch (Exception ex) { + // if error return current sample font. + return txtSample.getFont(); + } + } +} diff --git a/java_console/romraider/src/com/romraider/ECUExec.java b/java_console/romraider/src/com/romraider/ECUExec.java new file mode 100644 index 0000000000..a0f4d439c5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/ECUExec.java @@ -0,0 +1,146 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider; + +import static com.romraider.Version.BUILDNUMBER; +import static com.romraider.Version.PRODUCT_NAME; +import static com.romraider.Version.SUPPORT_URL; +import static com.romraider.Version.VERSION; +import static com.romraider.editor.ecu.ECUEditorManager.getECUEditor; +import static com.romraider.swing.LookAndFeelManager.initLookAndFeel; +import static com.romraider.util.LogManager.initDebugLogging; +import static com.romraider.util.RomServer.isRunning; +import static com.romraider.util.RomServer.sendRomToOpenInstance; +import static com.romraider.util.RomServer.waitForRom; +import static javax.swing.JOptionPane.INFORMATION_MESSAGE; +import static javax.swing.JOptionPane.WARNING_MESSAGE; +import static javax.swing.JOptionPane.showMessageDialog; +import static javax.swing.SwingUtilities.invokeLater; +import static javax.swing.WindowConstants.EXIT_ON_CLOSE; +import static org.apache.log4j.Logger.getLogger; + +import java.io.File; +import java.text.DateFormat; + +import org.apache.log4j.Logger; + +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.util.JREChecker; + +public class ECUExec { + private static final Logger LOGGER = getLogger(ECUExec.class); + private static final String START_LOGGER_ARG = "-logger"; + private static final String START_LOGGER_FULLSCREEN_ARG = "-logger.fullscreen"; + + private ECUExec() { + throw new UnsupportedOperationException(); + } + + public static void main(String args[]) { + // init debug logging + initDebugLogging(); + // dump the system properties to the log file as early as practical to + // help debugging/support + LOGGER.info(PRODUCT_NAME + " " + VERSION + " Build: " + BUILDNUMBER); + LOGGER.info("When requesting assistance at " + SUPPORT_URL + " please include the System Properties information below:"); + LOGGER.info(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG).format(System.currentTimeMillis())); + LOGGER.info("System Properties: \n\t" + + System.getProperties().toString().replace(",", "\n\t")); + + // 64-bit won't work with the native libs (e.g. serial rxtx) but won't + // fail until we actually try to use them we'll just warn here + if (!JREChecker.is32bit() && + !containsLoggerArg(args)) { + showMessageDialog(null, + "Incompatible JRE detected.\n" + + PRODUCT_NAME + + " requires a 32-bit JRE for some operations.\nSome features may be unavailable.", + "JRE Incompatibility Warning", + WARNING_MESSAGE); + } + + // check for dodgy threading - dev only + //RepaintManager.setCurrentManager(new ThreadCheckingRepaintManager(true)); + + // set look and feel + initLookAndFeel(); + + // check if already running + if (isRunning()) { + if (args.length == 0 || containsLoggerArg(args)) { + showAlreadyRunningMessage(); + } else { + sendRomToOpenInstance(args[0]); + } + } else { + openEditor(args); + } + } + + private static void showAlreadyRunningMessage() { + showMessageDialog(null, PRODUCT_NAME + " is already running.", PRODUCT_NAME, INFORMATION_MESSAGE); + } + + private static boolean containsLoggerArg(String[] args) { + for (String arg : args) { + if (arg.equalsIgnoreCase(START_LOGGER_ARG) || arg.equalsIgnoreCase(START_LOGGER_FULLSCREEN_ARG)) { + return true; + } + } + return false; + } + + + private static void openRom(final ECUEditor editor, final String rom) { + invokeLater(new Runnable() { + @Override + public void run() { + try { + File file = new File(rom); + editor.openImage(file); + } catch (Exception ex) { + LOGGER.error("Error opening rom", ex); + } + } + }); + } + + private static void openEditor(String[] args) { + ECUEditor editor = getECUEditor(); + editor.initializeEditorUI(); + editor.checkDefinitions(); + + if (args.length > 0) { + openRom(editor, args[0]); + } + startRomListener(editor); + } + + private static void startRomListener(ECUEditor editor) { + try { + while (true) { + String rom = waitForRom(); + openRom(editor, rom); + } + } catch (Throwable e) { + LOGGER.error("Error occurred", e); + } + } +} diff --git a/java_console/romraider/src/com/romraider/Settings.java b/java_console/romraider/src/com/romraider/Settings.java new file mode 100644 index 0000000000..4ab85a14ab --- /dev/null +++ b/java_console/romraider/src/com/romraider/Settings.java @@ -0,0 +1,873 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider; + +import static com.romraider.Version.RELEASE_NOTES; +import static com.romraider.Version.ROM_REVISION_URL; +import static com.romraider.Version.SUPPORT_URL; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Point; +import java.io.File; +import java.io.Serializable; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; + +import com.romraider.io.connection.ConnectionProperties; +import com.romraider.logger.ecu.definition.EcuDefinition; +//import com.romraider.logger.external.phidget.interfacekit.io.IntfKitSensor; + +public class Settings implements Serializable { + + private static final long serialVersionUID = 1026542922680475190L; + + /* String Format Settings */ + public static final String NEW_LINE = System.getProperty("line.separator"); + public static final String TAB = "\t"; + public static final String BLANK = ""; + + /* Clipboard Settings */ + public static final String TABLE_CLIPBOARD_FORMAT_ELEMENT = "table-clipboard-format"; + public static final String TABLE_CLIPBOARD_FORMAT_ATTRIBUTE = "format-string"; + public static final String TABLE_ELEMENT = "table"; + public static final String TABLE1D_ELEMENT = "table1D"; + public static final String TABLE2D_ELEMENT = "table2D"; + public static final String TABLE3D_ELEMENT = "table3D"; + public static final String TABLE_HEADER_ATTRIBUTE = "table-header"; + + public static final String DEFAULT_CLIPBOARD_FORMAT = "Default"; + public static final String DEFAULT_TABLE_HEADER = "[Table1D]" + NEW_LINE; + public static final String DEFAULT_TABLE1D_HEADER = ""; + public static final String DEFAULT_TABLE2D_HEADER = "[Table2D]" + NEW_LINE; + public static final String DEFAULT_TABLE3D_HEADER = "[Table3D]" + NEW_LINE; + + public static final String AIRBOYS_CLIPBOARD_FORMAT = "Airboys"; + public static final String AIRBOYS_TABLE_HEADER = ""; + public static final String AIRBOYS_TABLE1D_HEADER = ""; + public static final String AIRBOYS_TABLE2D_HEADER = "[Table2D]" + NEW_LINE; + public static final String AIRBOYS_TABLE3D_HEADER = "[Table3D]" + TAB; + + public static final String CUSTOM_CLIPBOARD_FORMAT = "Custom"; + + /* XML Settings */ + public static final String REPOSITORY_ELEMENT_NAME = "repository-dir"; + public static final String REPOSITORY_ATTRIBUTE_NAME = "path"; + + public static final String ICONS_ELEMENT_NAME = "icons"; + public static final String EDITOR_ICONS_ELEMENT_NAME = "editor-toolbar"; + public static final String EDITOR_ICONS_SCALE_ATTRIBUTE_NAME = "scale"; + public static final String TABLE_ICONS_ELEMENT_NAME = "table-toolbar"; + public static final String TABLE_ICONS_SCALE_ATTRIBUTE_NAME = "scale"; + + /* UI Settings */ + public static final int DEFAULT_EDITOR_ICON_SCALE = 50; + public static final int DEFAULT_TABLE_ICON_SCALE = 70; + + /* Table Settings */ + public static final String defaultTableToolBarName = "Table Tools"; + + public static final int ENDIAN_LITTLE = 1; + public static final int ENDIAN_BIG = 2; + + public static final int TABLE_1D = 1; + public static final int TABLE_2D = 2; + public static final int TABLE_3D = 3; + public static final int TABLE_X_AXIS = 4; + public static final int TABLE_Y_AXIS = 5; + public static final int TABLE_SWITCH = 6; + + public static final int DATA_TYPE_ORIGINAL = 0; + public static final int DATA_TYPE_BIN = 1; + public static final int DATA_TYPE_REAL = 3; + + public static final int COMPARE_DISPLAY_PERCENT = 1; + public static final int COMPARE_DISPLAY_ABSOLUTE = 2; + + public static final int STORAGE_TYPE_FLOAT = 99; + public static final boolean STORAGE_DATA_SIGNED = false; + + public static final Color UNCHANGED_VALUE_COLOR = new Color(160, 160, 160); + + public static final String INVALID_ATTRIBUTE_TEXT = "invalid"; + + public static final String DEFAULT_TABLE_NAME = "Unknown"; + + /* Rom Settings */ + public static final int CHECK_TOTAL = 0x5AA5A55A; + public static final int SIXTEENBIT_START_ADDRESS = 0x20000; + public static final int SIXTEENBIT_END_ADDRESS = 0x28000; + public static final int SIXTEENBIT_SMALL_SIZE = 0x28000; + public static final int SIXTEENBIT_LARGE_SIZE = 0x30000; + public static final int SIXTEENBIT_SEGMENT_SIZE = SIXTEENBIT_SMALL_SIZE - SIXTEENBIT_START_ADDRESS; // 0x8000 + public static final int SIXTEENBIT_SEGMENT_VALUE = 0x00; + + /* Scale Settings */ + public static final int LINEAR = 1; + public static final int INVERSE = 2; + + /* Compare Image Settings */ + public static Color TABLE_EQUAL_COLOR = new Color(52,114,53); + public static Color TABLE_DIFFERENT_COLOR = new Color(193, 27, 23); + public static Color TABLE_MISSING_COLOR = new Color(251,185,23); + + /* Compare DTC Foreground Colors */ + public static Color TABLESWITCH_DEFAULT_COLOR = Color.black; + public static Color TABLESWITCH_DIFFERENT_COLOR = new Color(193, 27, 23); + + /* MDI Desktop Settings*/ + public static int FRAME_OFFSET = 20; + + /* Scale Settings */ + public static String DEFAULT_SCALE = "Default"; + public static String METRIC_SCALE = "Metric"; + public static String STANDARD_SCALE = "Standard"; + + /* DataCell Colors */ + public static final Color scaleTextColor = new Color(0, 0, 0); + public static final Color highlightTextColor = new Color(255, 255, 255); + public static final Color selectTextColor = new Color(0, 0, 0); + public static final Color liveDataTraceTextColor = new Color(50, 50, 50); + + private static final String ISO15765 = "ISO15765"; + private static final String ISO9141 = "ISO9141"; + private static final String SYSTEM_NUMFORMAT = "system"; + private static final String USER_LANGUAGE = "user.language"; + private static final String USER_COUNTRY = "user.country"; + private static final String EN_US = "en_US"; + private static final String SSM = "SSM"; + private static final String OBD = "OBD"; + + private final Dimension windowSize = new Dimension(800, 600); + private final Point windowLocation = new Point(); + private int splitPaneLocation = 150; + private boolean windowMaximized; + + private String recentVersion = "x"; + + private Vector ecuDefinitionFiles = new Vector(); + private File lastImageDir = new File("images"); + private File lastRepositoryDir = new File("repositories"); + private boolean obsoleteWarning = true; + private boolean calcConflictWarning = true; + private boolean debug; + private int userLevel = 1; + private boolean saveDebugTables = true; + private boolean displayHighTables = true; + private boolean valueLimitWarning = true; + + private Font tableFont = new Font("Arial", Font.BOLD, 11); + private Dimension cellSize = new Dimension(42, 18); + private Color maxColor = new Color(255, 102, 102); + private Color minColor = new Color(153, 153, 255); + + private Color selectColor = new Color(204, 204, 204); + private Color highlightColor = new Color(27, 161, 226); + private Color liveValueColor = new Color (0, 255, 0); + + private Color decreaseBorder = new Color(0, 0, 255); + private Color increaseBorder = new Color(255, 0, 0); + + private Color axisColor = new Color(255, 255, 255); + private Color warningColor = new Color(255, 0, 0); + private int tableClickCount = 1; // number of clicks to open table + private int tableClickBehavior = 0; // TableTreeNode click behavior. 0=open/close frame, 1=open/focus frame + private boolean colorAxis = false; + + private String loggerPort; + private String loggerPortDefault; + private static String loggerProtocol = SSM; + private static String loggerDefinitionFilePath; + private static String loggerProfileFilePath; + private static String loggerOutputDirPath = System.getProperty("user.home"); + private String fileLoggingControllerSwitchId = "S20"; // defogger switch by default + private boolean fileLoggingControllerSwitchActive = true; + private boolean fileLoggingAbsoluteTimestamp; + private String logfileNameText; + private boolean logExternalsOnly; + private static String userLocale = SYSTEM_NUMFORMAT; + + private Dimension loggerWindowSize = new Dimension(1000, 600); + private Point loggerWindowLocation = new Point(); + private boolean loggerWindowMaximized; + private int loggerSelectedTabIndex; + private boolean loggerParameterListState = true; + private ConnectionProperties loggerConnectionProperties; + private Map loggerEcuDefinitionMap; + private Map loggerPluginPorts; + private boolean loggerRefreshMode; + private static byte loggerDestinationId = 0x10; + private boolean fastPoll = true; + private double loggerDividerLocation = 400; + private String loggerDebuggingLevel = "info"; + private static String j2534Device; + private static String transportProtocol = ISO9141; + + private String tableClipboardFormat = DEFAULT_CLIPBOARD_FORMAT; // Currently 2 options. Default and Airboy. Custom is not hooked up. + private String tableHeader = DEFAULT_TABLE_HEADER; + private String table1DHeader = DEFAULT_TABLE1D_HEADER; + private String table2DHeader = DEFAULT_TABLE2D_HEADER; + private String table3DHeader = DEFAULT_TABLE3D_HEADER; + + private int editorIconScale = DEFAULT_EDITOR_ICON_SCALE; + private int tableIconScale = DEFAULT_TABLE_ICON_SCALE; + + private boolean openExpanded = true; + private boolean showTableToolbarBorder = false; + private boolean alwaysOpenTableAtZero = false; + private boolean scaleHeadersAndData = true; + + private String defaultScale = "Metric"; + +// private Map phidgetSensors; + + public Settings() { + //center window by default + Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); + windowLocation.move(((int) (screenSize.getWidth() - windowSize.getWidth()) / 2), + ((int) (screenSize.getHeight() - windowSize.getHeight()) / 2)); + } + + public Dimension getWindowSize() { + return windowSize; + } + + public Point getWindowLocation() { + return windowLocation; + } + + public void setWindowSize(Dimension size) { + windowSize.setSize(size); + } + + public void setWindowLocation(Point location) { + windowLocation.setLocation(location); + } + + public Vector getEcuDefinitionFiles() { + return ecuDefinitionFiles; + } + + public void addEcuDefinitionFile(File ecuDefinitionFile) { + ecuDefinitionFiles.add(ecuDefinitionFile); + } + + public void setEcuDefinitionFiles(Vector ecuDefinitionFiles) { + this.ecuDefinitionFiles = ecuDefinitionFiles; + } + + public File getLastImageDir() { + return lastImageDir; + } + + public void setLastImageDir(File lastImageDir) { + this.lastImageDir = lastImageDir; + } + + public File getLastRepositoryDir() { + return lastRepositoryDir; + } + + public void setLastRepositoryDir(File lastRepositoryDir) { + this.lastRepositoryDir = lastRepositoryDir; + } + + public int getSplitPaneLocation() { + return splitPaneLocation; + } + + public void setSplitPaneLocation(int splitPaneLocation) { + this.splitPaneLocation = splitPaneLocation; + } + + public boolean isWindowMaximized() { + return windowMaximized; + } + + public void setWindowMaximized(boolean windowMaximized) { + this.windowMaximized = windowMaximized; + } + + public String getRomRevisionURL() { + return ROM_REVISION_URL; + } + + public String getSupportURL() { + return SUPPORT_URL; + } + + public Font getTableFont() { + return tableFont; + } + + public void setTableFont(Font tableFont) { + this.tableFont = tableFont; + } + + public boolean isObsoleteWarning() { + return obsoleteWarning; + } + + public void setObsoleteWarning(boolean obsoleteWarning) { + this.obsoleteWarning = obsoleteWarning; + } + + public boolean isDebug() { + return debug; + } + + public void setDebug(boolean debug) { + this.debug = debug; + } + + public Dimension getCellSize() { + return cellSize; + } + + public void setCellSize(Dimension cellSize) { + this.cellSize = cellSize; + } + + public Color getMaxColor() { + return maxColor; + } + + public void setMaxColor(Color maxColor) { + this.maxColor = maxColor; + } + + public Color getMinColor() { + return minColor; + } + + public void setMinColor(Color minColor) { + this.minColor = minColor; + } + + public Color getHighlightColor() { + return highlightColor; + } + + public void setHighlightColor(Color highlightColor) { + this.highlightColor = highlightColor; + } + + public Color getliveValueColor() { + return this.liveValueColor; + } + + public void setLiveValueColor(Color liveValueColor) { + this.liveValueColor = liveValueColor; + } + + public Color getSelectColor() { + return selectColor; + } + + public void setSelectColor(Color selectColor) { + this.selectColor = selectColor; + } + + public boolean isCalcConflictWarning() { + return calcConflictWarning; + } + + public void setCalcConflictWarning(boolean calcConflictWarning) { + this.calcConflictWarning = calcConflictWarning; + } + + public Color getIncreaseBorder() { + return increaseBorder; + } + + public void setIncreaseBorder(Color increaseBorder) { + this.increaseBorder = increaseBorder; + } + + public Color getDecreaseBorder() { + return decreaseBorder; + } + + public void setDecreaseBorder(Color decreaseBorder) { + this.decreaseBorder = decreaseBorder; + } + + public Color getAxisColor() { + return axisColor; + } + + public void setAxisColor(Color axisColor) { + this.axisColor = axisColor; + } + + public int getUserLevel() { + return userLevel; + } + + public void setUserLevel(int userLevel) { + if (userLevel > 5) { + this.userLevel = 5; + } else if (userLevel < 1) { + this.userLevel = 1; + } else { + this.userLevel = userLevel; + } + } + + public int getTableClickCount() { + return tableClickCount; + } + + public void setTableClickCount(int tableClickCount) { + this.tableClickCount = tableClickCount; + } + + public int getTableClickBehavior() { + return tableClickBehavior; + } + + public void setTableClickBehavior(int clickBehavior) { + // 0 = open/close + // 1 = open/focus + this.tableClickBehavior = clickBehavior; + } + + public String getRecentVersion() { + return recentVersion; + } + + public void setRecentVersion(String recentVersion) { + this.recentVersion = recentVersion; + } + + public String getReleaseNotes() { + return RELEASE_NOTES; + } + + public boolean isSaveDebugTables() { + return saveDebugTables; + } + + public void setSaveDebugTables(boolean saveDebugTables) { + this.saveDebugTables = saveDebugTables; + } + + public boolean isDisplayHighTables() { + return displayHighTables; + } + + public void setDisplayHighTables(boolean displayHighTables) { + this.displayHighTables = displayHighTables; + } + + public boolean isValueLimitWarning() { + return valueLimitWarning; + } + + public void setValueLimitWarning(boolean valueLimitWarning) { + this.valueLimitWarning = valueLimitWarning; + } + + public Color getWarningColor() { + return warningColor; + } + + public void setWarningColor(Color warningColor) { + this.warningColor = warningColor; + } + + public String getLoggerPort() { + return loggerPort; + } + + public void setLoggerPort(String loggerPort) { + this.loggerPort = loggerPort; + } + + public String getLoggerPortDefault() { + return loggerPortDefault; + } + + public void setLoggerPortDefault(String loggerPortDefault) { + this.loggerPortDefault = loggerPortDefault; + } + + public void setLoggerProtocol(String protocol) { + Settings.loggerProtocol = protocol; + } + + public String getLoggerProtocol() { + return loggerProtocol; + } + + public String getLoggerDefinitionFilePath() { + return loggerDefinitionFilePath; + } + + public void setLoggerDefinitionFilePath(String loggerDefinitionFilePath) { + Settings.loggerDefinitionFilePath = loggerDefinitionFilePath; + } + + public String getLoggerOutputDirPath() { + return loggerOutputDirPath; + } + + public Point getLoggerWindowLocation() { + return loggerWindowLocation; + } + + public void setLoggerWindowLocation(Point loggerWindowLocation) { + this.loggerWindowLocation = loggerWindowLocation; + } + + public boolean isLoggerWindowMaximized() { + return loggerWindowMaximized; + } + + public void setLoggerWindowMaximized(boolean loggerWindowMaximized) { + this.loggerWindowMaximized = loggerWindowMaximized; + } + + public Dimension getLoggerWindowSize() { + return loggerWindowSize; + } + + public void setLoggerWindowSize(Dimension loggerWindowSize) { + this.loggerWindowSize = loggerWindowSize; + } + + public double getDividerLocation() { + return loggerDividerLocation; + } + + public void setLoggerDividerLocation(double dividerLocation) { + this.loggerDividerLocation = dividerLocation; + } + + public String getLoggerProfileFilePath() { + return loggerProfileFilePath; + } + + public void setLoggerProfileFilePath(String loggerProfileFilePath) { + Settings.loggerProfileFilePath = loggerProfileFilePath; + } + + public void setLoggerOutputDirPath(String loggerOutputDirPath) { + Settings.loggerOutputDirPath = loggerOutputDirPath; + } + + public String getFileLoggingControllerSwitchId() { + return fileLoggingControllerSwitchId; + } + + public void setFileLoggingControllerSwitchId(String fileLoggingControllerSwitchId) { + checkNotNullOrEmpty(fileLoggingControllerSwitchId, "fileLoggingControllerSwitchId"); + this.fileLoggingControllerSwitchId = fileLoggingControllerSwitchId; + } + + public boolean isFileLoggingControllerSwitchActive() { + return fileLoggingControllerSwitchActive; + } + + public void setFileLoggingControllerSwitchActive(boolean fileLoggingControllerSwitchActive) { + this.fileLoggingControllerSwitchActive = fileLoggingControllerSwitchActive; + } + + public boolean isFileLoggingAbsoluteTimestamp() { + return fileLoggingAbsoluteTimestamp; + } + + public void setFileLoggingAbsoluteTimestamp(boolean fileLoggingAbsoluteTimestamp) { + this.fileLoggingAbsoluteTimestamp = fileLoggingAbsoluteTimestamp; + } + + public ConnectionProperties getLoggerConnectionProperties() { + return loggerConnectionProperties; + } + + public void setLoggerConnectionProperties(ConnectionProperties loggerConnectionProperties) { + this.loggerConnectionProperties = loggerConnectionProperties; + } + + public Map getLoggerEcuDefinitionMap() { + return loggerEcuDefinitionMap; + } + + public void setLoggerEcuDefinitionMap(Map loggerEcuDefinitionMap) { + this.loggerEcuDefinitionMap = loggerEcuDefinitionMap; + } + + public void setLoggerSelectedTabIndex(int loggerSelectedTabIndex) { + this.loggerSelectedTabIndex = loggerSelectedTabIndex; + } + + public int getLoggerSelectedTabIndex() { + return loggerSelectedTabIndex; + } + + public Map getLoggerPluginPorts() { + return loggerPluginPorts; + } + + public void setLoggerPluginPorts(Map loggerPluginPorts) { + this.loggerPluginPorts = loggerPluginPorts; + } + + public void setLoggerParameterListState(boolean ShowListState) { + this.loggerParameterListState = ShowListState; + } + + public boolean getLoggerParameterListState() { + return loggerParameterListState; + } + + public void setRefreshMode(boolean selected) { + this.loggerRefreshMode = selected; + } + + public boolean getRefreshMode() { + return loggerRefreshMode; + } + + public void setDestinationId(byte id) { + loggerDestinationId = id; + } + + public byte getDestinationId() { + return loggerDestinationId; + } + + public void setFastPoll(boolean state) { + this.fastPoll = state; + } + + public boolean isFastPoll() { + return fastPoll; + } + + public void setLogfileNameText(String text) { + this.logfileNameText = text; + } + + public String getLogfileNameText() { + return logfileNameText; + } + + public void setLoggerDebuggingLevel(String level) { + this.loggerDebuggingLevel = level; + } + + public String getLoggerDebuggingLevel() { + return loggerDebuggingLevel; + } + + public void setJ2534Device(String j2534Device) { + Settings.j2534Device = j2534Device; + } + + public String getJ2534Device() { + return j2534Device; + } + + public void setTransportProtocol(String transport) { + Settings.transportProtocol = transport; + } + + public String getTransportProtocol() { + return transportProtocol; + } + + public void setTableClipboardFormat(String formatString) { + this.tableClipboardFormat = formatString; + } + + public String getTableClipboardFormat() { + return this.tableClipboardFormat; + } + + public void setTableHeader(String header) { + this.tableHeader = header; + } + + public String getTableHeader() { + return this.tableHeader; + } + + public void setTable1DHeader(String header) { + this.table1DHeader = header; + } + + public String getTable1DHeader() { + return this.table1DHeader; + } + + public void setTable2DHeader(String header) { + this.table2DHeader = header; + } + + public String getTable2DHeader() { + return this.table2DHeader; + } + + public void setTable3DHeader(String header) { + this.table3DHeader = header; + } + + public String getTable3DHeader() { + return this.table3DHeader; + } + + public void setDefaultFormat() { + this.tableClipboardFormat = DEFAULT_CLIPBOARD_FORMAT; + this.tableHeader = DEFAULT_TABLE_HEADER; + this.table1DHeader = DEFAULT_TABLE1D_HEADER; + this.table2DHeader = DEFAULT_TABLE2D_HEADER; + this.table3DHeader = DEFAULT_TABLE3D_HEADER; + } + + public void setAirboysFormat() { + this.tableClipboardFormat = AIRBOYS_CLIPBOARD_FORMAT; + this.tableHeader = AIRBOYS_TABLE_HEADER; + this.table1DHeader = AIRBOYS_TABLE1D_HEADER; + this.table2DHeader = AIRBOYS_TABLE2D_HEADER; + this.table3DHeader = AIRBOYS_TABLE3D_HEADER; + } + + public int getEditorIconScale() { + return this.editorIconScale; + } + + public void setEditorIconScale(int scale) { + this.editorIconScale = scale; + } + + public int getTableIconScale() { + return this.tableIconScale; + } + + public void setTableIconScale(int scale) { + this.tableIconScale = scale; + } + + public void setLogExternalsOnly(boolean state) { + this.logExternalsOnly = state; + } + + public boolean isLogExternalsOnly() { + return logExternalsOnly; + } + + public boolean isCanBus() { + if (transportProtocol.equals(ISO15765)) { + return true; + } + return false; + } + + public boolean isObdProtocol() { + if (loggerProtocol.equals(OBD)) { + return true; + } + return false; + } + + public final boolean isUsNumberFormat() { + if (userLocale.equalsIgnoreCase(EN_US)) { + return true; + } + return false; + } + + public final String getLocale() { + return userLocale; + } + + public final void setLocale(String locale) { + userLocale = locale; + if (!locale.equalsIgnoreCase(SYSTEM_NUMFORMAT)) { + final String[] language = locale.split("_"); + System.setProperty(USER_LANGUAGE, language[0]); + System.setProperty(USER_COUNTRY, language[1]); + final Locale lc = new Locale(language[0], language[1]); + Locale.setDefault(lc); + } + } + + public boolean isOpenExpanded() { + return openExpanded; + } + + public void setOpenExpanded(boolean expanded) { + this.openExpanded = expanded; + } + + public boolean isShowTableToolbarBorder() { + return showTableToolbarBorder; + } + + public void setShowTableToolbarBorder(boolean showBorder) { + this.showTableToolbarBorder = showBorder; + } + + public boolean isAlwaysOpenTableAtZero() { + return alwaysOpenTableAtZero; + } + + public void setAlwaysOpenTableAtZero(boolean openAtZero) { + this.alwaysOpenTableAtZero = openAtZero; + } + + public boolean isScaleHeadersAndData() { + return this.scaleHeadersAndData; + } + + public void setScaleHeadersAndData(boolean headersAndData) { + this.scaleHeadersAndData = headersAndData; + } + + public boolean isColorAxis() { + return this.colorAxis; + } + + public void setColorAxis(boolean colorAxis) { + this.colorAxis = colorAxis; + } + + public String getDefaultScale() { + return this.defaultScale; + } + + public void setDefaultScale(String defaultScale) { + this.defaultScale = defaultScale; + } + +// public Map getPhidgetSensors() { +// return this.phidgetSensors; +// } +// +// public void setPhidgetSensors( +// Map phidgetSensors) { +// +// this.phidgetSensors = phidgetSensors; +// } +} diff --git a/java_console/romraider/src/com/romraider/Version.java.template b/java_console/romraider/src/com/romraider/Version.java.template new file mode 100644 index 0000000000..88732ede8d --- /dev/null +++ b/java_console/romraider/src/com/romraider/Version.java.template @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +// @warning.generated-file@ + +package com.romraider; + +import javax.swing.ImageIcon; + +public final class Version { + public static final String PRODUCT_NAME = "@name.package@"; + public static final String VERSION = "@version.major@.@version.minor@.@version.patch@ @version.extra@ @version.extra1@"; + public static final String BUILDNUMBER = "@version.buildnumber@"; + public static final String SUPPORT_URL = "@supporturl@"; + public static final String ROM_REVISION_URL = "@romrevisionurl@"; + public static final String ECU_DEFS_URL = "@ecudefsurl@"; + public static final String LOGGER_DEFS_URL = "@loggerdefsurl@"; + public static final String CARS_DEFS_URL = "@carsdefsurl@"; + public static final String RELEASE_NOTES = "@release_notes@"; + public static final ImageIcon ABOUT_ICON = new ImageIcon(Version.class.getClass().getResource("/graphics/romraider-ico-large.gif")); + public static final int MIN_LOG_DEF_VERSION = @min.logger.def.version@; + + private Version() { + } +} diff --git a/java_console/romraider/src/com/romraider/editor/ecu/ECUEditor.java b/java_console/romraider/src/com/romraider/editor/ecu/ECUEditor.java new file mode 100644 index 0000000000..04560311f5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/editor/ecu/ECUEditor.java @@ -0,0 +1,742 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.editor.ecu; + +import static com.romraider.Version.ECU_DEFS_URL; +import static com.romraider.Version.PRODUCT_NAME; +import static com.romraider.Version.VERSION; +import static javax.swing.JOptionPane.DEFAULT_OPTION; +import static javax.swing.JOptionPane.ERROR_MESSAGE; +import static javax.swing.JOptionPane.INFORMATION_MESSAGE; +import static javax.swing.JOptionPane.WARNING_MESSAGE; +import static javax.swing.JOptionPane.showMessageDialog; +import static javax.swing.JOptionPane.showOptionDialog; +import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; +import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER; +import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS; +import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyVetoException; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.Vector; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBox; +import javax.swing.JInternalFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextArea; +import javax.swing.SwingWorker; +import javax.swing.tree.TreePath; + +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.xml.sax.SAXParseException; + +import com.romraider.net.BrowserControl; +import com.romraider.Settings; +import com.romraider.maps.Rom; +import com.romraider.net.URL; +import com.romraider.swing.AbstractFrame; +import com.romraider.swing.CustomToolbarLayout; +import com.romraider.swing.ECUEditorMenuBar; +import com.romraider.swing.ECUEditorToolBar; +import com.romraider.swing.JProgressPane; +import com.romraider.swing.MDIDesktopPane; +import com.romraider.swing.RomTree; +import com.romraider.swing.RomTreeRootNode; +import com.romraider.swing.TableFrame; +import com.romraider.swing.TableToolBar; +import com.romraider.util.SettingsManager; +import com.romraider.xml.DOMRomUnmarshaller; +import com.romraider.xml.RomNotFoundException; +import com.sun.org.apache.xerces.internal.parsers.DOMParser; + +public class ECUEditor extends AbstractFrame { + private static final long serialVersionUID = -7826850987392016292L; + + private final String titleText = PRODUCT_NAME + " v" + VERSION + " | ECU Editor"; + + private final RomTreeRootNode imageRoot = new RomTreeRootNode("Open Images"); + private final RomTree imageList = new RomTree(imageRoot); + public MDIDesktopPane rightPanel = new MDIDesktopPane(); + public JProgressPane statusPanel = new JProgressPane(); + private JSplitPane splitPane = new JSplitPane(); + private Rom lastSelectedRom = null; + private ECUEditorToolBar toolBar; + private ECUEditorMenuBar menuBar; + private TableToolBar tableToolBar; + private final JPanel toolBarPanel = new JPanel(); + private OpenImageWorker openImageWorker; + private CloseImageWorker closeImageWorker; + private SetUserLevelWorker setUserLevelWorker; + private LaunchLoggerWorker launchLoggerWorker; + private final ImageIcon editorIcon = new ImageIcon(getClass().getResource("/graphics/romraider-ico.gif"), "RomRaider ECU Editor"); + + public ECUEditor() { + Settings settings = SettingsManager.getSettings(); + if (!settings.getRecentVersion().equalsIgnoreCase(VERSION)) { + showReleaseNotes(); + } + + setSize(settings.getWindowSize()); + setLocation(settings.getWindowLocation()); + if (settings.isWindowMaximized()) { + setExtendedState(MAXIMIZED_BOTH); + } + + JScrollPane rightScrollPane = new JScrollPane(rightPanel, + VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); + JScrollPane leftScrollPane = new JScrollPane(imageList, + VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); + + splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScrollPane, rightScrollPane); + splitPane.setDividerSize(3); + splitPane.setDividerLocation(settings.getSplitPaneLocation()); + splitPane.addPropertyChangeListener(this); + splitPane.setContinuousLayout(true); + getContentPane().add(splitPane); + + rightPanel.setBackground(Color.BLACK); + imageList.setScrollsOnExpand(true); + + this.add(statusPanel, BorderLayout.SOUTH); + + //set remaining window properties + setIconImage(editorIcon.getImage()); + + setDefaultCloseOperation(EXIT_ON_CLOSE); + addWindowListener(this); + setTitle(titleText); + setVisible(true); + toFront(); + } + + public void initializeEditorUI() { + //create menubar + menuBar = new ECUEditorMenuBar(); + this.setJMenuBar(menuBar); + + // create toolbars + toolBar = new ECUEditorToolBar("Editor Tools"); + + tableToolBar = new TableToolBar(); + tableToolBar.updateTableToolBar(); + + CustomToolbarLayout toolBarLayout = new CustomToolbarLayout(FlowLayout.LEFT, 0, 0); + + toolBarPanel.setLayout(toolBarLayout); + toolBarPanel.add(toolBar); + toolBarPanel.add(tableToolBar); + toolBarPanel.setVisible(true); + + this.add(toolBarPanel, BorderLayout.NORTH); + validate(); + } + + public void checkDefinitions() { + if (SettingsManager.getSettings().getEcuDefinitionFiles().size() <= 0) { + // no ECU definitions configured - let user choose to get latest or configure later + Object[] options = {"Yes", "No"}; + int answer = showOptionDialog(null, + "ECU definitions not configured.\nGo online to download the latest definition files?", + "Editor Configuration", + DEFAULT_OPTION, + WARNING_MESSAGE, + null, + options, + options[0]); + if (answer == 0) { + BrowserControl.displayURL(ECU_DEFS_URL); + } else { + showMessageDialog(this, + "ECU definition files need to be configured before ROM images can be opened.\nMenu: ECU Definitions > ECU Definition Manager...", + "Editor Configuration", + INFORMATION_MESSAGE); + } + } + } + + private void showReleaseNotes() { + try { + BufferedReader br = new BufferedReader(new FileReader(SettingsManager.getSettings().getReleaseNotes())); + try { + // new version being used, display release notes + JTextArea releaseNotes = new JTextArea(); + releaseNotes.setEditable(false); + releaseNotes.setWrapStyleWord(true); + releaseNotes.setLineWrap(true); + releaseNotes.setFont(new Font("Tahoma", Font.PLAIN, 12)); + + StringBuffer sb = new StringBuffer(); + while (br.ready()) { + sb.append(br.readLine()).append(Settings.NEW_LINE); + } + releaseNotes.setText(sb.toString()); + releaseNotes.setCaretPosition(0); + + JScrollPane scroller = new JScrollPane(releaseNotes, VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_NEVER); + scroller.setPreferredSize(new Dimension(600, 500)); + + showMessageDialog(this, scroller, + PRODUCT_NAME + VERSION + " Release Notes", INFORMATION_MESSAGE); + } finally { + br.close(); + } + } catch (Exception e) { + /* Ignore */ + } + } + + public void handleExit() { + Settings settings = SettingsManager.getSettings(); + settings.setSplitPaneLocation(splitPane.getDividerLocation()); + settings.setWindowMaximized(getExtendedState() == MAXIMIZED_BOTH); + settings.setWindowSize(getSize()); + settings.setWindowLocation(getLocation()); + + // Save when exit to save file settings. + SettingsManager.save(settings, statusPanel); + statusPanel.update("Ready...", 0); + repaint(); + } + + @Override + public void windowClosing(WindowEvent e) { + handleExit(); + } + + @Override + public void windowOpened(WindowEvent e) { + } + + @Override + public void windowClosed(WindowEvent e) { + } + + @Override + public void windowIconified(WindowEvent e) { + } + + @Override + public void windowDeiconified(WindowEvent e) { + } + + @Override + public void windowActivated(WindowEvent e) { + } + + @Override + public void windowDeactivated(WindowEvent e) { + } + + public String getVersion() { + return VERSION; + } + + public void addRom(Rom input) { + Settings settings = SettingsManager.getSettings(); + input.refreshDisplayedTables(); + + // add to ecu image list pane + getImageRoot().add(input); + + getImageList().setVisible(true); + getImageList().expandPath(new TreePath(getImageRoot())); + + getImageList().expandPath(new TreePath(input.getPath())); + + if(!settings.isOpenExpanded()) { + imageList.collapsePath(new TreePath(input.getPath())); + } + + getImageList().setRootVisible(false); + getImageList().repaint(); + + // Only set if no other rom has been selected. + if(null == getLastSelectedRom()) { + setLastSelectedRom(input); + } + + if (input.getRomID().isObsolete() && settings.isObsoleteWarning()) { + JPanel infoPanel = new JPanel(); + infoPanel.setLayout(new GridLayout(3, 1)); + infoPanel.add(new JLabel("A newer version of this ECU revision exists. " + + "Please visit the following link to download the latest revision:")); + infoPanel.add(new URL(settings.getRomRevisionURL())); + + JCheckBox check = new JCheckBox("Always display this message", true); + check.setHorizontalAlignment(JCheckBox.RIGHT); + + check.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + SettingsManager.getSettings().setObsoleteWarning(((JCheckBox) e.getSource()).isSelected()); + } + }); + + infoPanel.add(check); + showMessageDialog(this, infoPanel, "ECU Revision is Obsolete", INFORMATION_MESSAGE); + } + } + + public void displayTable(TableFrame frame) { + try { + // check if frame has been added. + for(JInternalFrame curFrame : getRightPanel().getAllFrames()) { + if(curFrame.equals(frame)) { + // table is already open. + if(1 == SettingsManager.getSettings().getTableClickBehavior()) { // open/focus frame + // table is already open, so set focus on the frame. + boolean selected = true; + frame.toFront(); + try { + frame.setSelected(true); + } catch (PropertyVetoException e) { + frame.toBack(); + selected = false; + } + if(selected) { + frame.requestFocusInWindow(); + } + } else { // default to open/close frame + // table is already open, so close the frame. + rightPanel.remove(frame); + frame.setVisible(false); + try { + frame.setClosed(true); + } catch (PropertyVetoException e) { + ; // Do nothing. + } + frame.dispose(); + } + frame.pack(); + rightPanel.repaint(); + return; + } + } + + // frame not added. Draw table and add the frame. + frame.getTable().drawTable(); + rightPanel.add(frame); + } catch (IllegalArgumentException ex) { + ;// Do nothing. + } + frame.pack(); + rightPanel.repaint(); + } + + public void removeDisplayTable(TableFrame frame) { + frame.setVisible(false); + this.getTableToolBar().updateTableToolBar(); + rightPanel.remove(frame); + rightPanel.validate(); + refreshUI(); + } + + public void closeImage() { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + closeImageWorker = new CloseImageWorker(getLastSelectedRom()); + closeImageWorker.addPropertyChangeListener(getStatusPanel()); + closeImageWorker.execute(); + } + + public void closeAllImages() { + while (imageRoot.getChildCount() > 0) { + closeImage(); + } + } + + public Rom getLastSelectedRom() { + return lastSelectedRom; + } + + public String getLastSelectedRomFileName() { + Rom lastSelRom = getLastSelectedRom(); + return lastSelRom == null ? "" : lastSelRom.getFileName() + " "; + } + + public void setLastSelectedRom(Rom lastSelectedRom) { + this.lastSelectedRom = lastSelectedRom; + if (lastSelectedRom == null) { + setTitle(titleText); + } else { + setTitle(titleText + " - " + lastSelectedRom.getFileName()); + } + } + + public ECUEditorToolBar getToolBar() { + return toolBar; + } + + public void setToolBar(ECUEditorToolBar toolBar) { + this.toolBar = toolBar; + } + + public ECUEditorMenuBar getEditorMenuBar() { + return menuBar; + } + + public TableToolBar getTableToolBar() { + return tableToolBar; + } + + public void redrawVisableTables(Settings settings) { + + } + + public void setUserLevel(int userLevel) { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + SettingsManager.getSettings().setUserLevel(userLevel); + setUserLevelWorker = new SetUserLevelWorker(); + setUserLevelWorker.addPropertyChangeListener(getStatusPanel()); + setUserLevelWorker.execute(); + } + + public Vector getImages() { + Vector images = new Vector(); + for (int i = 0; i < imageRoot.getChildCount(); i++) { + if(imageRoot.getChildAt(i) instanceof Rom) { + Rom rom = (Rom) imageRoot.getChildAt(i); + if(null != rom) { + images.add(rom); + } + } + } + return images; + } + + @Override + public void propertyChange(PropertyChangeEvent evt) { + imageList.updateUI(); + imageList.repaint(); + rightPanel.updateUI(); + rightPanel.repaint(); + } + + public void refreshUI() + { + getToolBar().updateButtons(); + getEditorMenuBar().updateMenu(); + getTableToolBar().updateTableToolBar(); + imageList.updateUI(); + imageList.repaint(); + rightPanel.updateUI(); + rightPanel.repaint(); + } + + public void refreshTableCompareMenus() { + for (int i = 0; i < imageRoot.getChildCount(); i++) { + if(imageRoot.getChildAt(i) instanceof Rom) { + Rom rom = (Rom) imageRoot.getChildAt(i); + if(null != rom) { + rom.refreshTableCompareMenus(); + } + } + } + } + + public void openImage(File inputFile) throws Exception { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + openImageWorker = new OpenImageWorker(inputFile); + openImageWorker.addPropertyChangeListener(getStatusPanel()); + openImageWorker.execute(); + } + + public void openImages(File[] inputFiles) throws Exception { + if(inputFiles.length < 1) { + showMessageDialog(this, "Image Not Found", "Error Loading Image(s)", ERROR_MESSAGE); + return; + } + for(int j = 0; j < inputFiles.length; j++) { + openImage(inputFiles[j]); + } + } + + public byte[] readFile(File inputFile) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + FileInputStream fis = new FileInputStream(inputFile); + try { + byte[] buf = new byte[8192]; + int bytesRead; + while ((bytesRead = fis.read(buf)) != -1) { + baos.write(buf, 0, bytesRead); + } + } finally { + fis.close(); + } + return baos.toByteArray(); + } + + public void launchLogger() { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); +// launchLoggerWorker = new LaunchLoggerWorker(); +// launchLoggerWorker.addPropertyChangeListener(getStatusPanel()); +// launchLoggerWorker.execute(); + } + + public RomTreeRootNode getImageRoot() { + return imageRoot; + } + + public RomTree getImageList() { + return imageList; + } + + public JProgressPane getStatusPanel() { + return this.statusPanel; + } + + public MDIDesktopPane getRightPanel() { + return this.rightPanel; + } +} + +class LaunchLoggerWorker extends SwingWorker { + public LaunchLoggerWorker() { + } + + @Override + protected Void doInBackground() throws Exception { + ECUEditor editor = ECUEditorManager.getECUEditor(); + editor.getStatusPanel().setStatus("Launching Logger..."); + setProgress(10); +// EcuLogger.startLogger(javax.swing.WindowConstants.DISPOSE_ON_CLOSE, editor); + return null; + } + + public void propertyChange(PropertyChangeEvent evnt) + { + SwingWorker source = (SwingWorker) evnt.getSource(); + if (null != source && "state".equals( evnt.getPropertyName() ) + && (source.isDone() || source.isCancelled() ) ) + { + source.removePropertyChangeListener(ECUEditorManager.getECUEditor().getStatusPanel()); + } + } + + @Override + public void done() { + ECUEditor editor = ECUEditorManager.getECUEditor(); + editor.getStatusPanel().setStatus("Ready..."); + setProgress(0); + editor.setCursor(null); + editor.refreshUI(); + } +} + +class SetUserLevelWorker extends SwingWorker { + public SetUserLevelWorker() { + } + + @Override + protected Void doInBackground() throws Exception { + for(Rom rom : ECUEditorManager.getECUEditor().getImages()) { + rom.refreshDisplayedTables(); + } + return null; + } + + public void propertyChange(PropertyChangeEvent evnt) + { + SwingWorker source = (SwingWorker) evnt.getSource(); + if (null != source && "state".equals( evnt.getPropertyName() ) + && (source.isDone() || source.isCancelled() ) ) + { + source.removePropertyChangeListener(ECUEditorManager.getECUEditor().getStatusPanel()); + } + } + + @Override + public void done() { + ECUEditor editor = ECUEditorManager.getECUEditor(); + editor.getStatusPanel().setStatus("Ready..."); + setProgress(0); + editor.setCursor(null); + editor.refreshUI(); + } +} + +class CloseImageWorker extends SwingWorker { + Rom rom; + + public CloseImageWorker(Rom romToRemove) { + this.rom = romToRemove; + } + + @Override + protected Void doInBackground() throws Exception { + ECUEditor editor = ECUEditorManager.getECUEditor(); + RomTreeRootNode imageRoot = editor.getImageRoot(); + + rom.clearData(); + rom.removeFromParent(); + rom = null; + + if (imageRoot.getChildCount() > 0) { + editor.setLastSelectedRom((Rom) imageRoot.getChildAt(0)); + } else { + // no other images open + editor.setLastSelectedRom(null); + } + + editor.refreshTableCompareMenus(); + + return null; + } + + @Override + public void done() { + ECUEditor editor = ECUEditorManager.getECUEditor(); + editor.getStatusPanel().setStatus("Ready..."); + setProgress(0); + editor.setCursor(null); + editor.refreshUI(); + System.gc(); + } +} + +class OpenImageWorker extends SwingWorker { + private final File inputFile; + + public OpenImageWorker(File inputFile) { + this.inputFile = inputFile; + } + + @Override + protected Void doInBackground() throws Exception { + ECUEditor editor = ECUEditorManager.getECUEditor(); + Settings settings = SettingsManager.getSettings(); + + DOMParser parser = new DOMParser(); + Document doc; + FileInputStream fileStream; + + try { + editor.getStatusPanel().setStatus("Parsing ECU definitions..."); + setProgress(0); + + byte[] input = editor.readFile(inputFile); + + editor.getStatusPanel().setStatus("Finding ECU definition..."); + setProgress(10); + + // parse ecu definition files until result found + for (int i = 0; i < settings.getEcuDefinitionFiles().size(); i++) { + fileStream = new FileInputStream(settings.getEcuDefinitionFiles().get(i)); + InputSource src = new InputSource(fileStream); + + parser.parse(src); + doc = parser.getDocument(); + + Rom rom; + + try { + rom = new DOMRomUnmarshaller().unmarshallXMLDefinition(doc.getDocumentElement(), input, editor.getStatusPanel()); + } catch (RomNotFoundException rex) { + // rom was not found in current file, skip to next + continue; + } catch (Exception ex) { + ex.printStackTrace(); + showMessageDialog(editor, "Error Loading. Unknown Exception.", "Error Loading " + inputFile.getName(), ERROR_MESSAGE); + return null; + } finally { + // Release mem after unmarshall. + parser.reset(); + doc.removeChild(doc.getDocumentElement()); + doc = null; + fileStream.close(); + System.gc(); + } + + editor.getStatusPanel().setStatus("Populating tables..."); + setProgress(50); + + rom.setFullFileName(inputFile); + rom.populateTables(input, editor.getStatusPanel()); + + editor.getStatusPanel().setStatus("Finalizing..."); + setProgress(90); + + editor.addRom(rom); + editor.refreshTableCompareMenus(); + + editor.getStatusPanel().setStatus("Done loading image..."); + setProgress(100); + return null; + } + + // if code executes to this point, no ROM was found, report to user + showMessageDialog(editor, "ECU Definition Not Found", "Error Loading " + inputFile.getName(), ERROR_MESSAGE); + + } catch (SAXParseException spe) { + // catch general parsing exception - enough people don't unzip the defs that a better error message is in order + showMessageDialog(editor, "Unable to read XML definitions. Please make sure the definition file is correct. If it is in a ZIP archive, unzip the file and try again.", "Error Loading " + inputFile.getName(), ERROR_MESSAGE); + + } catch (StackOverflowError ex) { + // handles looped inheritance, which will use up all available memory + showMessageDialog(editor, "Looped \"base\" attribute in XML definitions.", "Error Loading " + inputFile.getName(), ERROR_MESSAGE); + + } catch (OutOfMemoryError ome) { + // handles Java heap space issues when loading multiple Roms. + showMessageDialog(editor, "Error loading Image. Out of memeory.", "Error Loading " + inputFile.getName(), ERROR_MESSAGE); + + } + return null; + } + + public void propertyChange(PropertyChangeEvent evnt) + { + SwingWorker source = (SwingWorker) evnt.getSource(); + if (null != source && "state".equals( evnt.getPropertyName() ) + && (source.isDone() || source.isCancelled() ) ) + { + source.removePropertyChangeListener(ECUEditorManager.getECUEditor().getStatusPanel()); + } + } + + @Override + public void done() { + ECUEditor editor = ECUEditorManager.getECUEditor(); + editor.getStatusPanel().setStatus("Ready..."); + setProgress(0); + editor.setCursor(null); + editor.refreshUI(); + System.gc(); + } +} diff --git a/java_console/romraider/src/com/romraider/editor/ecu/ECUEditorManager.java b/java_console/romraider/src/com/romraider/editor/ecu/ECUEditorManager.java new file mode 100644 index 0000000000..a04d9a3216 --- /dev/null +++ b/java_console/romraider/src/com/romraider/editor/ecu/ECUEditorManager.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.editor.ecu; + +import javax.swing.SwingUtilities; + + +public class ECUEditorManager { + private static ECUEditor editor = null; + + private ECUEditorManager() { + throw new UnsupportedOperationException(); + } + + public static ECUEditor getECUEditor() { + if (editor == null) { + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + editor = new ECUEditor(); + } + }); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return editor; + } +} diff --git a/java_console/romraider/src/com/romraider/io/connection/ConnectionManager.java b/java_console/romraider/src/com/romraider/io/connection/ConnectionManager.java new file mode 100644 index 0000000000..2083c6c3b3 --- /dev/null +++ b/java_console/romraider/src/com/romraider/io/connection/ConnectionManager.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.io.connection; + +import com.romraider.logger.ecu.comms.manager.PollingState; + +public interface ConnectionManager { + void send(byte[] request, byte[] response, PollingState pollState); + + byte[] send(byte[] bytes); + + void clearLine(); + + void close(); +} diff --git a/java_console/romraider/src/com/romraider/io/connection/ConnectionProperties.java b/java_console/romraider/src/com/romraider/io/connection/ConnectionProperties.java new file mode 100644 index 0000000000..27606f3a8f --- /dev/null +++ b/java_console/romraider/src/com/romraider/io/connection/ConnectionProperties.java @@ -0,0 +1,36 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.io.connection; + +public interface ConnectionProperties { + int getBaudRate(); + + void setBaudRate(int b); + + int getDataBits(); + + int getStopBits(); + + int getParity(); + + int getConnectTimeout(); + + int getSendTimeout(); +} diff --git a/java_console/romraider/src/com/romraider/io/connection/ConnectionPropertiesImpl.java b/java_console/romraider/src/com/romraider/io/connection/ConnectionPropertiesImpl.java new file mode 100644 index 0000000000..7c00378a8d --- /dev/null +++ b/java_console/romraider/src/com/romraider/io/connection/ConnectionPropertiesImpl.java @@ -0,0 +1,82 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.io.connection; + +public final class ConnectionPropertiesImpl implements ConnectionProperties { + private final int baudRate; + private final int dataBits; + private final int stopBits; + private final int parity; + private final int connectTimeout; + private final int sendTimeout; + + + public ConnectionPropertiesImpl(int baudRate, int dataBits, int stopBits, int parity, int connectTimeout, int sendTimeout) { + this.baudRate = baudRate; + this.dataBits = dataBits; + this.stopBits = stopBits; + this.parity = parity; + this.connectTimeout = connectTimeout; + this.sendTimeout = sendTimeout; + } + + public int getBaudRate() { + return baudRate; + } + + public void setBaudRate(int b) { + + } + + public int getDataBits() { + return dataBits; + } + + public int getStopBits() { + return stopBits; + } + + public int getParity() { + return parity; + } + + public int getConnectTimeout() { + return connectTimeout; + } + + public int getSendTimeout() { + return sendTimeout; + } + + public String toString() { + final String properties = String.format( + "%s[baudRate=%d, dataBits=%d, stopBits=%d, parity=%d, " + + "connectTimeout=%d, sendTimeout=%d]", + getClass().getSimpleName(), + getBaudRate(), + getDataBits(), + getStopBits(), + getParity(), + getConnectTimeout(), + getSendTimeout() + ); + return properties; + } +} diff --git a/java_console/romraider/src/com/romraider/io/serial/port/SerialPortRefreshListener.java b/java_console/romraider/src/com/romraider/io/serial/port/SerialPortRefreshListener.java new file mode 100644 index 0000000000..3260c917c6 --- /dev/null +++ b/java_console/romraider/src/com/romraider/io/serial/port/SerialPortRefreshListener.java @@ -0,0 +1,28 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.io.serial.port; + +import java.util.Set; + +public interface SerialPortRefreshListener { + + void refreshPortList(Set ports, String defaultSelectedPort); + +} diff --git a/java_console/romraider/src/com/romraider/logger/car/util/Constants.java b/java_console/romraider/src/com/romraider/logger/car/util/Constants.java new file mode 100644 index 0000000000..577286c399 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/car/util/Constants.java @@ -0,0 +1,40 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.car.util; + +public enum Constants { + IMPERIAL ("imperial"), + IMPERIAL_UNIT ("mph"), + METRIC ("metric"), + METRIC_UNIT ("km/h"), + KPH_2_MPH ("1.609344"), + TQ_CONSTANT_I ("5252.113122"), + TQ_CONSTANT_M ("9549.296748"); + + private final String value; + + Constants (String value) { + this.value = value; + } + + public String value(){ + return value; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/car/util/SpeedCalculator.java b/java_console/romraider/src/com/romraider/logger/car/util/SpeedCalculator.java new file mode 100644 index 0000000000..06441e5571 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/car/util/SpeedCalculator.java @@ -0,0 +1,44 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.car.util; + +import static com.romraider.logger.car.util.Constants.IMPERIAL_UNIT; +import static com.romraider.logger.car.util.Constants.KPH_2_MPH; +import static com.romraider.logger.car.util.Constants.METRIC_UNIT; + +public class SpeedCalculator { + private static final double K2M = Double.parseDouble(KPH_2_MPH.value()); + + public static double calculateMph(double rpm, double ratio) { + return (rpm / ratio); + } + + public static double calculateKph(double rpm, double ratio) { + return calculateMph(rpm, ratio) * K2M; + } + + public static double calculateRpm(double vs, double ratio, String units) { + double rpm = 0; + if (units.equalsIgnoreCase(IMPERIAL_UNIT.value())) rpm = (vs * ratio); + if (units.equalsIgnoreCase(METRIC_UNIT.value())) rpm = (vs * ratio / K2M); + return rpm; + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/car/util/TorqueCalculator.java b/java_console/romraider/src/com/romraider/logger/car/util/TorqueCalculator.java new file mode 100644 index 0000000000..8a4fcd8cb2 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/car/util/TorqueCalculator.java @@ -0,0 +1,39 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.car.util; + +import static com.romraider.logger.car.util.Constants.IMPERIAL; +import static com.romraider.logger.car.util.Constants.METRIC; +import static com.romraider.logger.car.util.Constants.TQ_CONSTANT_I; +import static com.romraider.logger.car.util.Constants.TQ_CONSTANT_M; + +public class TorqueCalculator { + + public static double calculateTorque(double rpm, double hp, String units) { + double tq = 0; + if (units.equalsIgnoreCase(IMPERIAL.value())) { + tq = hp / rpm * Double.parseDouble(TQ_CONSTANT_I.value()); + } + if (units.equalsIgnoreCase(METRIC.value())) { + tq = hp / rpm * Double.parseDouble(TQ_CONSTANT_M.value()); + } + return tq; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/EcuLoggerExec.java b/java_console/romraider/src/com/romraider/logger/ecu/EcuLoggerExec.java new file mode 100644 index 0000000000..074c424397 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/EcuLoggerExec.java @@ -0,0 +1,47 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu; + +import static javax.swing.WindowConstants.EXIT_ON_CLOSE; + +import com.romraider.swing.LookAndFeelManager; +import com.romraider.util.LogManager; + +public final class EcuLoggerExec { + + private EcuLoggerExec() { + throw new UnsupportedOperationException(); + } + + public static void main(String... args) { + // init debug loging + LogManager.initDebugLogging(); + + // check for dodgy threading - dev only + // RepaintManager.setCurrentManager(new ThreadCheckingRepaintManager(true)); + + // set look and feel + LookAndFeelManager.initLookAndFeel(); + + // start logger + // EcuLogger.startLogger(EXIT_ON_CLOSE, args); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/controller/LoggerController.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/controller/LoggerController.java new file mode 100644 index 0000000000..9ade304f21 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/controller/LoggerController.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.controller; + +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.StatusChangeListener; +import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor; + +public interface LoggerController { + + void setFileLoggerSwitchMonitor(FileLoggerControllerSwitchMonitor monitor); + + void addLogger(String callerId, LoggerData loggerData); + + void removeLogger(String callerId, LoggerData loggerData); + + boolean isStarted(); + + void start(); + + void stop(); + + void addListener(StatusChangeListener listener); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/controller/LoggerControllerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/controller/LoggerControllerImpl.java new file mode 100644 index 0000000000..1ac78986a8 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/controller/LoggerControllerImpl.java @@ -0,0 +1,111 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.controller; + +import static com.romraider.util.ParamChecker.checkNotNull; +import static com.romraider.util.ThreadUtil.runAsDaemon; + +import org.apache.log4j.Logger; + +import com.romraider.logger.ecu.comms.manager.QueryManager; +import com.romraider.logger.ecu.comms.manager.QueryManagerImpl; +import com.romraider.logger.ecu.comms.query.EcuInitCallback; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.MessageListener; +import com.romraider.logger.ecu.ui.StatusChangeListener; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; +import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor; + +public final class LoggerControllerImpl implements LoggerController { + private static final Logger LOGGER = Logger.getLogger(LoggerControllerImpl.class); + private final QueryManager queryManager; + + public LoggerControllerImpl(EcuInitCallback ecuInitCallback, MessageListener messageListener, + DataUpdateHandler... dataUpdateHandlers) { + checkNotNull(ecuInitCallback, messageListener, dataUpdateHandlers); + queryManager = new QueryManagerImpl(ecuInitCallback, messageListener, dataUpdateHandlers); + } + + @Override + public synchronized void addListener(StatusChangeListener listener) { + checkNotNull(listener, "listener"); + queryManager.addListener(listener); + } + + @Override + public void setFileLoggerSwitchMonitor(FileLoggerControllerSwitchMonitor monitor) { + checkNotNull(monitor); + LOGGER.debug("Setting file logger switch monitor: [" + monitor.getEcuSwitch().getId() + "] " + monitor.getEcuSwitch().getName()); + queryManager.setFileLoggerSwitchMonitor(monitor); + } + + @Override + public void addLogger(String callerId, LoggerData loggerData) { + checkNotNull(loggerData); + LOGGER.debug("Adding logger: [" + loggerData.getId() + "] " + loggerData.getName()); + queryManager.addQuery(callerId, loggerData); + } + + @Override + public void removeLogger(String callerId, LoggerData loggerData) { + checkNotNull(loggerData, "ecuParam"); + LOGGER.debug("Removing logger: [" + loggerData.getId() + "] " + loggerData.getName()); + queryManager.removeQuery(callerId, loggerData); + } + + @Override + public synchronized boolean isStarted() { + return queryManager.isRunning(); + } + + @Override + public synchronized void start() { + if (!isStarted()) runAsDaemon(queryManager); + } + + @Override + public synchronized void stop() { + if (isStarted() && queryManager.getThread().isAlive()) { + queryManager.stop(); + try { + LOGGER.debug(String.format( + "%s - Stopping QueryManager: %s", + this.getClass().getSimpleName(), + queryManager.getThread().getName())); + queryManager.getThread().interrupt(); + LOGGER.debug(String.format( + "%s - Waiting for QueryManager %s to terminate", + this.getClass().getSimpleName(), + queryManager.getThread().getName())); + queryManager.getThread().join(5000); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + finally { + LOGGER.debug(String.format( + "%s - QueryManager %s state: %s", + this.getClass().getSimpleName(), + queryManager.getThread().getName(), + queryManager.getThread().getState())); + } + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/LearningTableValues.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/LearningTableValues.java new file mode 100644 index 0000000000..8d51cbbec3 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/LearningTableValues.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.learning; + + +public interface LearningTableValues { + + void execute(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/flkctable/FlkcTableQueryBuilder.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/flkctable/FlkcTableQueryBuilder.java new file mode 100644 index 0000000000..47db997e19 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/flkctable/FlkcTableQueryBuilder.java @@ -0,0 +1,108 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.learning.flkctable; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.romraider.logger.ecu.comms.learning.parameter.Parameter; +import com.romraider.logger.ecu.comms.query.EcuQuery; +import com.romraider.logger.ecu.comms.query.EcuQueryImpl; +import com.romraider.logger.ecu.definition.EcuAddress; +import com.romraider.logger.ecu.definition.EcuAddressImpl; +import com.romraider.logger.ecu.definition.EcuData; +import com.romraider.logger.ecu.definition.EcuDataConvertor; +import com.romraider.logger.ecu.definition.EcuParameterImpl; +import com.romraider.logger.ecu.ui.paramlist.ParameterRow; +import com.romraider.util.HexUtil; + +/** + * Build an EcuQuery for each of the cells in the FLKC RAM table. + */ +public class FlkcTableQueryBuilder { + private static final Logger LOGGER = + Logger.getLogger(FlkcTableQueryBuilder.class); + + public FlkcTableQueryBuilder() { + } + + /** + * Build an EcuQuery for each cell of the FLKC RAM table. Note this + * returns an extra null query for column 0 of each row which is later + * populated with the row header (RPM Ranges) data. + * @param flkc - a ParameterRow item that helps to identify the + * ECU bitness and provide a Converter for the raw data. + * @param flkcAddr - the address in RAM of the start of the table. + * @param rows - the number of rows in the table. + * @param columns - the number of columns in the table. + * @return EcuQueries divided into groups to query each row separately to + * avoid maxing out the ECU send/receive buffer. + */ + public final List> build( + ParameterRow flkc, + int flkcAddr, + int rows, + int columns) { + + final List> flkcQueryRows = new ArrayList>(); + int checksummed = 1; + int dataSize = 1; + if (Parameter.fromValue(flkc.getLoggerData().getId()) == Parameter.E41 || + Parameter.fromValue(flkc.getLoggerData().getId()) == Parameter.E173) { + checksummed = 2; + dataSize = 4; + } + LOGGER.debug( + String.format( + "FLKC Data format rows:%d col:%d checksummed:%d " + + "dataSize:%d FLKC:%s", + rows, columns, checksummed, dataSize, + flkc.getLoggerData().getId())); + + int i = 0; + for (int j = 0; j < rows; j++) { + final List flkcQueryCols = new ArrayList(); + flkcQueryCols.add(null); + for (int k = 0; k < columns; k++) { + String id = "flkc-r" + j + "c" + k; + final String addrStr = + HexUtil.intToHexString( + flkcAddr + (i * dataSize * checksummed)); + LOGGER.debug( + String.format( + "FLKC Data row:%d col:%d addr:%s", + j, k, addrStr)); + final EcuAddress ea = new EcuAddressImpl(addrStr, dataSize, -1); + final EcuParameterImpl epi = + new EcuParameterImpl(id, addrStr, id, ea, + new EcuDataConvertor[] { + flkc.getLoggerData().getSelectedConvertor() + } + ); + flkcQueryCols.add(new EcuQueryImpl((EcuData) epi)); + i++; + } + flkcQueryRows.add(flkcQueryCols); + } + return flkcQueryRows; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/Parameter.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/Parameter.java new file mode 100644 index 0000000000..28300fae84 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/Parameter.java @@ -0,0 +1,88 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.learning.parameter; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; + +/** + * This Emun defines all the possible parameters used to query the Learning + * Table Values of an ECU. + */ +public enum Parameter { + E1("E1"), // IAM 16 bit + E31("E31"), // IAM 32 bit + E12("E12"), // Fine Learning Knock Correction* + E41("E41"), // Fine Learning Knock Correction (4-byte)* + E13("E13"), // AF Learning 1A 16 bit + E14("E14"), // AF Learning 1B 16 bit + E15("E15"), // AF Learning 1C 16 bit + E16("E16"), // AF Learning 1D 16 bit + E44("E44"), // AF Learning 1A 32 bit + E45("E45"), // AF Learning 1B 32 bit + E46("E46"), // AF Learning 1C 32 bit + E47("E47"), // AF Learning 1D 32 bit + E62("E62"), // AF Learning 2A 32 bit + E63("E63"), // AF Learning 2B 32 bit + E64("E64"), // AF Learning 2C 32 bit + E65("E65"), // AF Learning 2D 32 bit + P2("P2"), // ECT + P11("P11"), // IAT + P17("P17"), // Battery Volts + P24("P24"), // ATM + P66("P66"), // AF Learning 3 + P115("P115"), // Learned Throttle Closed Voltage + P118("P118"), // AF Learning 4 + P153("P153"), // Whole Learning value in timing + E173("E173"); // Fine Learning Knock Correction Table Start (4-byte)* + + private static final Map lookup + = new HashMap(); + + static { + for(Parameter s : EnumSet.allOf(Parameter.class)) + lookup.put(s.toString(), s); + } + + private Parameter(final String text) { + this.text = text; + } + + private final String text; + + @Override + public final String toString() { + return text; + } + + /** + * Retrieve the Parameter that has the given value. + * @param value - the value of the Parameter in String format + * @return the Parameter that has the given value or null if undefined. + */ + public static Parameter fromValue(String value) { + Parameter result = null; + if (lookup.containsKey(value)) { + result = lookup.get(value); + } + return result; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/ParameterCrossReference.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/ParameterCrossReference.java new file mode 100644 index 0000000000..94a9a60f6d --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/ParameterCrossReference.java @@ -0,0 +1,64 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.learning.parameter; + +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.E1; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.E31; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P11; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P115; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P118; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P153; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P17; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P2; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P24; +import static com.romraider.logger.ecu.comms.learning.parameter.Parameter.P66; + +import java.util.HashMap; +import java.util.Map; + +/** + * A Map of Parameter and value specific to the Vehicle Information Table. + */ +public class ParameterCrossReference { + final Map map; + + public ParameterCrossReference() { + map = new HashMap(); + map.put(P17, "Battery"); + map.put(P24, "ATM"); + map.put(P11, "IAT"); + map.put(P2, "ECT"); + map.put(E1, "IAM"); + map.put(E31, "IAM"); + map.put(P66, "A/F #3"); + map.put(P118, "A/F #4"); + map.put(P115, "TPS VDC"); + map.put(P153, "Lrn Timing"); + } + +/** + * Retrieve the string value associated with the supplied Parameter. + * @param parameter - Parameter to lookup value for. + * @return the value of the Parameter. + */ + public final String getValue(Parameter parameter) { + return map.get(parameter); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/ParameterIdComparator.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/ParameterIdComparator.java new file mode 100644 index 0000000000..6e8ec7ceb1 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/learning/parameter/ParameterIdComparator.java @@ -0,0 +1,35 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.learning.parameter; + +import java.util.Comparator; + +import com.romraider.logger.ecu.comms.query.EcuQuery; + +/** + * A custom comparator to sort EcuQuery items based on an encapsulated ID field. + */ +public final class ParameterIdComparator implements Comparator { + + public int compare(EcuQuery ecuQuery1, EcuQuery ecuQuery2) { + return ecuQuery1.getLoggerData().getId().compareTo( + ecuQuery2.getLoggerData().getId()); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/PollingState.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/PollingState.java new file mode 100644 index 0000000000..b96253a172 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/PollingState.java @@ -0,0 +1,44 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.manager; + + +public interface PollingState { + + int getCurrentState(); + + void setCurrentState(int i); + + int getLastState(); + + void setLastState(int i); + + boolean isNewQuery(); + + void setNewQuery(boolean state); + + boolean isLastQuery(); + + void setLastQuery(boolean state); + + boolean isFastPoll(); + + void setFastPoll(boolean state); + } diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/PollingStateImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/PollingStateImpl.java new file mode 100644 index 0000000000..ecc7c347ad --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/PollingStateImpl.java @@ -0,0 +1,89 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.manager; + +public final class PollingStateImpl implements PollingState { + private static int currentState; + private static int lastpollState; + private static boolean newQuery; + private static boolean lastQuery; + private static boolean fastPoll; + + public PollingStateImpl() { + setCurrentState(0); + setLastState(0); + setNewQuery(true); + setLastQuery(false); + setFastPoll(false); + } + + public int getCurrentState() { + return currentState; + } + + public void setCurrentState(int i) { + currentState = i; + } + + public int getLastState() { + return lastpollState; + } + + public void setLastState(int i) { + lastpollState = i; + } + + public boolean isNewQuery() { + return newQuery; + } + + public void setNewQuery(boolean state) { + newQuery = state; + } + + public boolean isLastQuery() { + return lastQuery; + } + + public void setLastQuery(boolean state) { + lastQuery = state; + } + + public boolean isFastPoll() { + return fastPoll; + } + + public void setFastPoll(boolean state) { + fastPoll = state; + } + + public String toString() { + final String state = String.format( + "Polling State [isFastPoll=%s, CurrentState=%d, LastState=%d, " + + "isNewQuery=%s, isLastQuery=%s]", + isFastPoll(), + getCurrentState(), + getLastState(), + isNewQuery(), + isLastQuery() + ); + return state; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/QueryManager.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/QueryManager.java new file mode 100644 index 0000000000..6cb67ac0cc --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/QueryManager.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.manager; + +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.StatusChangeListener; +import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor; + +public interface QueryManager extends Runnable { + + void setFileLoggerSwitchMonitor(FileLoggerControllerSwitchMonitor monitor); + + void addQuery(String callerId, LoggerData loggerData); + + void removeQuery(String callerId, LoggerData loggerData); + + boolean isRunning(); + + void stop(); + + void addListener(StatusChangeListener listener); + + Thread getThread(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java new file mode 100644 index 0000000000..6bedbc70e3 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java @@ -0,0 +1,459 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.manager; + +//import static com.romraider.logger.ecu.comms.io.connection.LoggerConnectionFactory.getConnection; +import static com.romraider.logger.ecu.definition.EcuDataType.EXTERNAL; +import static com.romraider.util.ParamChecker.checkNotNull; +import static com.romraider.util.ThreadUtil.runAsDaemon; +import static com.romraider.util.ThreadUtil.sleep; +import static java.lang.System.currentTimeMillis; +import static java.util.Collections.synchronizedList; +import static java.util.Collections.synchronizedMap; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.SwingUtilities; + +import org.apache.log4j.Logger; + +import com.romraider.Settings; +//import com.romraider.logger.ecu.comms.io.connection.LoggerConnection; +import com.romraider.logger.ecu.comms.query.EcuInitCallback; +import com.romraider.logger.ecu.comms.query.EcuQuery; +import com.romraider.logger.ecu.comms.query.EcuQueryImpl; +import com.romraider.logger.ecu.comms.query.ExternalQuery; +import com.romraider.logger.ecu.comms.query.ExternalQueryImpl; +import com.romraider.logger.ecu.comms.query.Query; +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.comms.query.ResponseImpl; +import com.romraider.logger.ecu.definition.EcuData; +import com.romraider.logger.ecu.definition.ExternalData; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.MessageListener; +import com.romraider.logger.ecu.ui.StatusChangeListener; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; +import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor; +import com.romraider.util.SettingsManager; + +public final class QueryManagerImpl implements QueryManager { + private static final Logger LOGGER = Logger.getLogger(QueryManagerImpl.class); + private final List listeners = + synchronizedList(new ArrayList()); + private final Map queryMap = + synchronizedMap(new HashMap()); + private final Map addList = new HashMap(); + private final List removeList = new ArrayList(); + private static final PollingState pollState = new PollingStateImpl(); + private static final Settings settings = SettingsManager.getSettings(); + private static final String ECU = "ECU"; + private static final String TCU = "TCU"; + private static final String EXT = "Externals"; + private final EcuInitCallback ecuInitCallback; + private final MessageListener messageListener; + private final DataUpdateHandler[] dataUpdateHandlers; + private FileLoggerControllerSwitchMonitor monitor; + private EcuQuery fileLoggerQuery; + private Thread queryManagerThread; + private static boolean started; + private static boolean stop; + + public QueryManagerImpl(EcuInitCallback ecuInitCallback, + MessageListener messageListener, + DataUpdateHandler... dataUpdateHandlers) { + checkNotNull(ecuInitCallback, + messageListener, + dataUpdateHandlers); + this.ecuInitCallback = ecuInitCallback; + this.messageListener = messageListener; + this.dataUpdateHandlers = dataUpdateHandlers; + stop = true; + } + + @Override + public synchronized void addListener(StatusChangeListener listener) { + checkNotNull(listener, "listener"); + listeners.add(listener); + } + + @Override + public void setFileLoggerSwitchMonitor(FileLoggerControllerSwitchMonitor monitor) { + checkNotNull(monitor); + this.monitor = monitor; + fileLoggerQuery = new EcuQueryImpl(monitor.getEcuSwitch()); + } + + @Override + public synchronized void addQuery(String callerId, LoggerData loggerData) { + checkNotNull(callerId, loggerData); + //FIXME: This is a hack!! + String queryId = buildQueryId(callerId, loggerData); + if (loggerData.getDataType() == EXTERNAL) { + addList.put(queryId, new ExternalQueryImpl((ExternalData) loggerData)); + } else { + addList.put(queryId, new EcuQueryImpl((EcuData) loggerData)); + pollState.setLastQuery(false); + pollState.setNewQuery(true); + } + } + + @Override + public synchronized void removeQuery(String callerId, LoggerData loggerData) { + checkNotNull(callerId, loggerData); + removeList.add(buildQueryId(callerId, loggerData)); + if (loggerData.getDataType() != EXTERNAL) { + pollState.setNewQuery(true); + } + } + + @Override + public Thread getThread() { + return queryManagerThread; + } + + @Override + public boolean isRunning() { + return started && !stop; + } + + @Override + public void run() { + started = true; + queryManagerThread = Thread.currentThread(); + LOGGER.debug("QueryManager started."); + + try { + stop = false; + while (!stop) { + notifyConnecting(); + if (!settings.isLogExternalsOnly() && + doEcuInit(settings.getDestinationId())) { + + notifyReading(); + runLogger(settings.getDestinationId()); + } else if (settings.isLogExternalsOnly()) { + notifyReading(); + runLogger((byte) -1); + } else { + sleep(1000L); + } + } + } catch (Exception e) { + messageListener.reportError(e); + } finally { + notifyStopped(); + messageListener.reportMessage("Disconnected."); + LOGGER.debug("QueryManager stopped."); + } + } + + private boolean doEcuInit(byte id) { + String target = null; + if (id == 0x10){ + target = ECU; + } + if (id == 0x18){ + target = TCU; + } + + try { +// LoggerConnection connection = +// getConnection(settings.getLoggerProtocol(), +// settings.getLoggerPort(), +// settings.getLoggerConnectionProperties()); + try { + messageListener.reportMessage("Sending " + target + " Init..."); + //connection.ecuInit(ecuInitCallback, id); + messageListener.reportMessage("Sending " + target + " Init...done."); + return true; + } finally { + //connection.close(); + } + } catch (Exception e) { + messageListener.reportMessage("Unable to send " + target + + " init - check cable is connected and ignition is on."); + logError(e); + return false; + } + } + + private void logError(Exception e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Error sending init", e); + } else { + LOGGER.info("Error sending init: " + e.getMessage()); + } + } + + private void runLogger(byte id) { + String target = null; + if (id == -1){ + target = EXT; + } + if (id == 0x10){ + target = ECU; + } + if (id == 0x18){ + target = TCU; + } + TransmissionManager txManager = new TransmissionManagerImpl(); + long start = currentTimeMillis(); + long end = currentTimeMillis(); + int count = 0; + try { + txManager.start(); + boolean lastPollState = settings.isFastPoll(); + while (!stop) { + pollState.setFastPoll(settings.isFastPoll()); + updateQueryList(); + if (queryMap.isEmpty()) { + if (pollState.isLastQuery() && + pollState.getCurrentState() == 0) { + endEcuQueries(txManager); + pollState.setLastState(0); + } + start = System.currentTimeMillis(); + count = 0; + messageListener.reportMessage("Select parameters to be logged..."); + sleep(1000L); + } else { + end = currentTimeMillis() + 1L; // update once every 1msec + final List ecuQueries = + filterEcuQueries(queryMap.values()); + + if (!settings.isLogExternalsOnly()) { + if (!ecuQueries.isEmpty()) { + sendEcuQueries(txManager); + if (!pollState.isFastPoll() && lastPollState) { + endEcuQueries(txManager); + } + if (pollState.isFastPoll()) { + if (pollState.getCurrentState() == 0 && + pollState.isNewQuery()) { + pollState.setCurrentState(1); + pollState.setNewQuery(false); + } + if (pollState.getCurrentState() == 0 && + !pollState.isNewQuery()) { + pollState.setCurrentState(1); + } + if (pollState.getCurrentState() == 1 && + pollState.isNewQuery()) { + pollState.setCurrentState(0); + pollState.setLastState(1); + pollState.setNewQuery(false); + } + if (pollState.getCurrentState() == 1 && + !pollState.isNewQuery()) { + pollState.setLastState(1); + } + pollState.setLastQuery(true); + } + else { + pollState.setCurrentState(0); + pollState.setLastState(0); + pollState.setNewQuery(false); + } + lastPollState = pollState.isFastPoll(); + } + else { + if (pollState.isLastQuery() && + pollState.getLastState() == 1) { + endEcuQueries(txManager); + pollState.setLastState(0); + pollState.setCurrentState(0); + pollState.setNewQuery(true); + } + } + } + sendExternalQueries(); + // waiting until at least 1msec has passed since last query set + while (currentTimeMillis() < end) { + sleep(1L); + } + handleQueryResponse(); + count++; + messageListener.reportMessage("Querying " + target + "..."); + messageListener.reportStats(buildStatsMessage(start, count)); + } + } + } catch (Exception e) { + messageListener.reportError(e); + } finally { + txManager.stop(); + pollState.setCurrentState(0); + pollState.setNewQuery(true); + } + } + + private void sendEcuQueries(TransmissionManager txManager) { + final List ecuQueries = filterEcuQueries(queryMap.values()); + if (fileLoggerQuery != null + && settings.isFileLoggingControllerSwitchActive()) + ecuQueries.add(fileLoggerQuery); + txManager.sendQueries(ecuQueries, pollState); + } + + private void sendExternalQueries() { + final List externalQueries = + filterExternalQueries(queryMap.values()); + for (ExternalQuery externalQuery : externalQueries) { + //FIXME: This is a hack!! + externalQuery.setResponse( + externalQuery.getLoggerData().getSelectedConvertor().convert(null)); + } + } + + private void endEcuQueries(TransmissionManager txManager) { + txManager.endQueries(); + pollState.setLastQuery(false); + } + + private void handleQueryResponse() { + if (settings.isFileLoggingControllerSwitchActive()) + monitor.monitorFileLoggerSwitch(fileLoggerQuery.getResponse()); + final Response response = buildResponse(queryMap.values()); + for (final DataUpdateHandler dataUpdateHandler : dataUpdateHandlers) { + runAsDaemon(new Runnable() { + @Override + public void run() { + dataUpdateHandler.handleDataUpdate(response); + } + }); + } + } + + private Response buildResponse(Collection queries) { + final Response response = new ResponseImpl(); + for (final Query query : queries) { + response.setDataValue(query.getLoggerData(), query.getResponse()); + } + return response; + } + + //FIXME: This is a hack!! + private List filterEcuQueries(Collection queries) { + List filtered = new ArrayList(); + for (Query query : queries) { + if (EcuQuery.class.isAssignableFrom(query.getClass())) { + filtered.add((EcuQuery) query); + } + } + return filtered; + } + + //FIXME: This is a hack!! + private List filterExternalQueries(Collection queries) { + List filtered = new ArrayList(); + for (Query query : queries) { + if (ExternalQuery.class.isAssignableFrom(query.getClass())) { + filtered.add((ExternalQuery) query); + } + } + return filtered; + } + + @Override + public void stop() { + stop = true; + } + + private String buildQueryId(String callerId, LoggerData loggerData) { + return callerId + "_" + loggerData.getName(); + } + + private synchronized void updateQueryList() { + addQueries(); + removeQueries(); + } + + private void addQueries() { + for (String queryId : addList.keySet()) { + queryMap.put(queryId, addList.get(queryId)); + } + addList.clear(); + } + + private void removeQueries() { + for (String queryId : removeList) { + queryMap.remove(queryId); + } + removeList.clear(); + } + + private String buildStatsMessage(long start, int count) { + String state = "Slow-K:"; + if (pollState.isFastPoll()) { + state = "Fast-K:"; + } + if (settings.getTransportProtocol().equals("ISO15765")) { + state = "CAN bus:"; + } + if (settings.isLogExternalsOnly()) { + state = "Externals:"; + } + double duration = (System.currentTimeMillis() - start) / 1000.0; + String result = String.format( + "%s[ %.2f queries/sec, %.2f sec/query ]", + state, + (count) / duration, + duration / (count) + ); + return result; + } + + private void notifyConnecting() { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + for (StatusChangeListener listener : listeners) { + listener.connecting(); + } + } + }); + } + + private void notifyReading() { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + for (StatusChangeListener listener : listeners) { + listener.readingData(); + } + } + }); + } + + private void notifyStopped() { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + for (StatusChangeListener listener : listeners) { + listener.stopped(); + } + } + }); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/TransmissionManager.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/TransmissionManager.java new file mode 100644 index 0000000000..9aa91e0bdf --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/TransmissionManager.java @@ -0,0 +1,35 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.manager; + +import com.romraider.logger.ecu.comms.query.EcuQuery; +import java.util.Collection; + +public interface TransmissionManager { + + void start(); + + void sendQueries(Collection queries, PollingState pollMode); + + void endQueries(); + + void stop(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/TransmissionManagerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/TransmissionManagerImpl.java new file mode 100644 index 0000000000..5518d02ff6 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/manager/TransmissionManagerImpl.java @@ -0,0 +1,76 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.manager; + +//import static com.romraider.logger.ecu.comms.io.connection.LoggerConnectionFactory.getConnection; +import static com.romraider.util.ParamChecker.checkNotNull; +import static org.apache.log4j.Logger.getLogger; + +import java.util.Collection; + +import org.apache.log4j.Logger; + +import com.romraider.Settings; +//import com.romraider.logger.ecu.comms.io.connection.LoggerConnection; +import com.romraider.logger.ecu.comms.query.EcuQuery; +import com.romraider.logger.ecu.exception.NotConnectedException; +import com.romraider.util.SettingsManager; + +public final class TransmissionManagerImpl implements TransmissionManager { + private static final Logger LOGGER = getLogger(TransmissionManagerImpl.class); + // private LoggerConnection connection; + + public TransmissionManagerImpl() { + } + + @Override + public void start() { + try { + Settings settings = SettingsManager.getSettings(); + // connection = getConnection(settings.getLoggerProtocol(), settings.getLoggerPort(), settings.getLoggerConnectionProperties()); + LOGGER.info("TX Manager Started."); + } catch (Throwable e) { + stop(); + } + } + + @Override + public void sendQueries(Collection queries, PollingState pollState) { + checkNotNull(queries, "queries"); + checkNotNull(pollState, "pollState"); +// if (connection == null) throw new NotConnectedException("TransmissionManager must be started before queries can be sent!"); +// connection.sendAddressReads(queries, SettingsManager.getSettings().getDestinationId(), pollState); + } + + @Override + public void endQueries() { +// if (connection == null) throw new NotConnectedException("TransmissionManager must be started before ending queries!"); +// connection.clearLine(); + } + + @Override + public void stop() { +// if (connection != null) { +// endQueries(); +//// connection.close(); +// } + LOGGER.info("TX Manager Stopped."); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuInit.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuInit.java new file mode 100644 index 0000000000..b7d70cf2e5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuInit.java @@ -0,0 +1,28 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +public interface EcuInit { + + String getEcuId(); + + byte[] getEcuInitBytes(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuInitCallback.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuInitCallback.java new file mode 100644 index 0000000000..e8dc0687dc --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuInitCallback.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +public interface EcuInitCallback { + + void callback(EcuInit ecuInit); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuQuery.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuQuery.java new file mode 100644 index 0000000000..a0aad1ab67 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuQuery.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +public interface EcuQuery extends Query { + + String[] getAddresses(); + + byte[] getBytes(); + + String getHex(); + + void setResponse(byte[] bytes); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuQueryImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuQueryImpl.java new file mode 100644 index 0000000000..a337777ba9 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/EcuQueryImpl.java @@ -0,0 +1,75 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +import com.romraider.logger.ecu.definition.EcuData; +import com.romraider.logger.ecu.definition.LoggerData; +import static com.romraider.util.HexUtil.asHex; +import static com.romraider.util.ParamChecker.checkNotNull; + +public final class EcuQueryImpl implements EcuQuery { + private final EcuData ecuData; + private final byte[] bytes; + private final String hex; + private double response; + + public EcuQueryImpl(EcuData ecuData) { + checkNotNull(ecuData); + this.ecuData = ecuData; + bytes = ecuData.getAddress().getBytes(); + hex = asHex(bytes); + } + + public LoggerData getLoggerData() { + return ecuData; + } + + public String[] getAddresses() { + return ecuData.getAddress().getAddresses(); + } + + public byte[] getBytes() { + return bytes; + } + + public String getHex() { + return hex; + } + + public double getResponse() { + return response; + } + + public void setResponse(byte[] bytes) { + this.response = ecuData.getSelectedConvertor().convert(bytes); + } + + public boolean equals(Object object) { + return object instanceof EcuQueryImpl && getHex().equals(((EcuQueryImpl) object).getHex()); + } + + public int hashCode() { + return getHex().hashCode(); + } + + public String toString() { + return "0x" + getHex(); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ExternalQuery.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ExternalQuery.java new file mode 100644 index 0000000000..3a5fd63c5f --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ExternalQuery.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +public interface ExternalQuery extends Query { + + void setResponse(double response); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ExternalQueryImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ExternalQueryImpl.java new file mode 100644 index 0000000000..fa753b2f2f --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ExternalQueryImpl.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +import com.romraider.logger.ecu.definition.ExternalData; +import com.romraider.logger.ecu.definition.LoggerData; +import static com.romraider.util.ParamChecker.checkNotNull; + +public final class ExternalQueryImpl implements ExternalQuery { + private final ExternalData externalData; + private double response; + + public ExternalQueryImpl(ExternalData externalData) { + checkNotNull(externalData); + this.externalData = externalData; + } + + public LoggerData getLoggerData() { + return externalData; + } + + public void setResponse(double response) { + this.response = response; + } + + public double getResponse() { + return response; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/Query.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/Query.java new file mode 100644 index 0000000000..b63a20fd2f --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/Query.java @@ -0,0 +1,30 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +import com.romraider.logger.ecu.definition.LoggerData; + +public interface Query { + + LoggerData getLoggerData(); + + double getResponse(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/Response.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/Response.java new file mode 100644 index 0000000000..a87bda83ba --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/Response.java @@ -0,0 +1,34 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +import com.romraider.logger.ecu.definition.LoggerData; +import java.util.Set; + +public interface Response { + + void setDataValue(LoggerData data, double value); + + Set getData(); + + double getDataValue(LoggerData data); + + long getTimestamp(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ResponseImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ResponseImpl.java new file mode 100644 index 0000000000..b1111565ad --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/ResponseImpl.java @@ -0,0 +1,52 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +import com.romraider.logger.ecu.definition.LoggerData; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +public class ResponseImpl implements Response { + private static final double ZERO = 0.0; + private final Map dataValues = new LinkedHashMap(); + private final long timestamp; + + public ResponseImpl() { + timestamp = System.currentTimeMillis(); + } + + public void setDataValue(LoggerData data, double value) { + dataValues.put(data, value); + } + + public Set getData() { + return dataValues.keySet(); + } + + public double getDataValue(LoggerData data) { + final Double value = dataValues.get(data); + return value == null ? ZERO : value; + } + + public long getTimestamp() { + return timestamp; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/query/SSMEcuInit.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/SSMEcuInit.java new file mode 100644 index 0000000000..abf578c840 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/query/SSMEcuInit.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.query; + +import static com.romraider.util.HexUtil.asHex; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; +import static java.lang.System.arraycopy; + +public final class SSMEcuInit implements EcuInit { + private byte[] ecuInitBytes; + private String ecuId; + + public SSMEcuInit(byte[] ecuInitBytes) { + checkNotNullOrEmpty(ecuInitBytes, "ecuInitBytes"); + this.ecuInitBytes = ecuInitBytes; + byte[] ecuIdBytes = new byte[5]; + arraycopy(ecuInitBytes, 3, ecuIdBytes, 0, 5); + ecuId = asHex(ecuIdBytes); + } + + public String getEcuId() { + return ecuId; + } + + public byte[] getEcuInitBytes() { + return ecuInitBytes; + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/readcodes/ReadCodesManager.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/readcodes/ReadCodesManager.java new file mode 100644 index 0000000000..93d0aa08b5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/readcodes/ReadCodesManager.java @@ -0,0 +1,25 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.readcodes; + + +public interface ReadCodesManager { + int readCodes(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/comms/reset/ResetManager.java b/java_console/romraider/src/com/romraider/logger/ecu/comms/reset/ResetManager.java new file mode 100644 index 0000000000..081c08f654 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/comms/reset/ResetManager.java @@ -0,0 +1,24 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.comms.reset; + +public interface ResetManager { + boolean resetEcu(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/ConvertorUpdateListener.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/ConvertorUpdateListener.java new file mode 100644 index 0000000000..27807af226 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/ConvertorUpdateListener.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface ConvertorUpdateListener { + + void notifyConvertorUpdate(LoggerData updatedLoggerData); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuAddress.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuAddress.java new file mode 100644 index 0000000000..4fcfe94515 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuAddress.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface EcuAddress { + + String[] getAddresses(); + + byte[] getBytes(); + + int getBit(); + + int getLength(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuAddressImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuAddressImpl.java new file mode 100644 index 0000000000..4d0f85cb3f --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuAddressImpl.java @@ -0,0 +1,123 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import static com.romraider.util.HexUtil.asBytes; +import static com.romraider.util.HexUtil.hexToInt; +import static com.romraider.util.HexUtil.intToHexString; +import static com.romraider.util.ParamChecker.checkGreaterThanZero; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; +import java.util.LinkedList; +import java.util.List; + +public final class EcuAddressImpl implements EcuAddress { + private final String[] addresses; + private final byte[] bytes; + private final int bit; + + + public EcuAddressImpl(String address, int length, int bit) { + checkNotNullOrEmpty(address, "address"); + checkGreaterThanZero(length, "length"); + final String[] addrSting = {address}; + this.addresses = buildAddresses(addrSting, length); + this.bytes = getAddressBytes(addresses); + this.bit = bit; + } + + public EcuAddressImpl(String[] address, int length, int bit) { + checkNotNullOrEmpty(address, "address"); + checkGreaterThanZero(length, "length"); + this.addresses = buildAddresses(address, length); + this.bytes = getAddressBytes(addresses); + this.bit = bit; + } + + public EcuAddressImpl(String[] addresses) { + checkNotNullOrEmpty(addresses, "addresses"); + this.addresses = addresses; + this.bytes = getAddressBytes(addresses); + this.bit = -1; + } + + public String[] getAddresses() { + return addresses; + } + + public byte[] getBytes() { + return bytes; + } + + public int getBit() { + return bit; + } + + public int getLength() { + return addresses.length; + } + + private String[] buildAddresses(String[] startAddress, int addressLength) { + final List addresses = new LinkedList(); + if (startAddress.length > addressLength) { + for (int i = 0; i < startAddress.length; i++) { + final int address = hexToInt(startAddress[i]); + addresses.add( + padAddress(intToHexString(address), + startAddress[i].length())); + } + } + else { + int start = hexToInt(startAddress[0]); + for (int i = 0; i < addressLength; i++) { + addresses.add( + padAddress(intToHexString(start + i), + startAddress[0].length())); + } + } + return addresses.toArray(new String[addresses.size()]); + } + + private String padAddress(String address, int length) { + if (address.length() == length) { + return address; + } else { + StringBuilder builder = new StringBuilder(length); + builder.append("0x"); + String s = address.substring(2); + for (int i = 0; i < length - s.length() - 2; i++) { + builder.append('0'); + } + builder.append(s); + return builder.toString(); + } + } + + private byte[] getAddressBytes(String[] addresses) { + byte[] bytes = new byte[0]; + for (String address : addresses) { + byte[] tmp1 = asBytes(address); + byte[] tmp2 = new byte[bytes.length + tmp1.length]; + System.arraycopy(bytes, 0, tmp2, 0, bytes.length); + System.arraycopy(tmp1, 0, tmp2, bytes.length, tmp1.length); + bytes = tmp2; + } + return bytes; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuData.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuData.java new file mode 100644 index 0000000000..f08260f65a --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuData.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface EcuData extends LoggerData { + + EcuAddress getAddress(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataConvertor.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataConvertor.java new file mode 100644 index 0000000000..0d7b696baf --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataConvertor.java @@ -0,0 +1,39 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + + + +public interface EcuDataConvertor { + + double convert(byte[] bytes); + + String format(double value); + + String getUnits(); + + //GaugeMinMax getGaugeMinMax(); + + String getFormat(); + + String getExpression(); + + String getDataType(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataLoader.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataLoader.java new file mode 100644 index 0000000000..843996248c --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataLoader.java @@ -0,0 +1,47 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import com.romraider.io.connection.ConnectionProperties; +import com.romraider.logger.ecu.comms.query.EcuInit; +import java.io.File; +import java.util.List; +import java.util.Map; + +public interface EcuDataLoader { + + void loadEcuDefsFromXml(File ecuDefsFile); + + void loadConfigFromXml(String loggerConfigFilePath, String protocol, String fileLoggingControllerSwitchId, EcuInit ecuInit); + + Map getEcuDefinitionMap(); + + List getEcuParameters(); + + List getEcuSwitches(); + + EcuSwitch getFileLoggingControllerSwitch(); + + ConnectionProperties getConnectionProperties(); + + String getDefVersion(); + + List getEcuCodes(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataType.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataType.java new file mode 100644 index 0000000000..3393360fed --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDataType.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public enum EcuDataType { + PARAMETER, + SWITCH, + EXTERNAL +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDefinition.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDefinition.java new file mode 100644 index 0000000000..b92f43ac1a --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDefinition.java @@ -0,0 +1,35 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import java.io.File; + +public interface EcuDefinition { + + String getEcuId(); + + String getCalId(); + + String getCarString(); + + String getInherits(); + + File getEcuDefFile(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDefinitionImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDefinitionImpl.java new file mode 100644 index 0000000000..c0a36fe752 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDefinitionImpl.java @@ -0,0 +1,67 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; + +import java.io.File; + + +public final class EcuDefinitionImpl implements EcuDefinition { + private final String ecuId; + private final String calId; + private final String carString; + private final String inherits; + private final File ecuDefFile; + + public EcuDefinitionImpl( + String ecuId, String calId, String carString, + String inherits, File ecuDefFile) { + + checkNotNullOrEmpty(ecuId, "ecuId"); + checkNotNullOrEmpty(calId, "calId"); + checkNotNullOrEmpty(carString, "carString"); + this.ecuId = ecuId; + this.calId = calId; + this.carString = carString; + this.inherits = inherits; + this.ecuDefFile = ecuDefFile; + } + + public String getEcuId() { + return ecuId; + } + + public String getCalId() { + return calId; + } + + public String getCarString() { + return carString; + } + + public String getInherits() { + return inherits; + } + + public File getEcuDefFile() { + return ecuDefFile; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDerivedParameterConvertor.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDerivedParameterConvertor.java new file mode 100644 index 0000000000..2e2ed84c61 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDerivedParameterConvertor.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface EcuDerivedParameterConvertor extends EcuDataConvertor { + + void setEcuDatas(EcuData[] ecuDatas); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDerivedParameterImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDerivedParameterImpl.java new file mode 100644 index 0000000000..13cd8974ef --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuDerivedParameterImpl.java @@ -0,0 +1,129 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import static com.romraider.logger.ecu.definition.EcuDataType.PARAMETER; +import static com.romraider.util.ParamChecker.checkNotNull; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; +import java.util.HashSet; +import java.util.Set; + +public final class EcuDerivedParameterImpl implements EcuParameter { + private final String id; + private final String name; + private final String description; + private final EcuDerivedParameterConvertor[] convertors; + private final EcuAddress address; + private final Set listeners = new HashSet(); + private int selectedConvertorIndex; + private boolean selected; + + public EcuDerivedParameterImpl(String id, String name, String description, EcuData[] ecuDatas, + EcuDerivedParameterConvertor[] convertors) { + checkNotNullOrEmpty(id, "id"); + checkNotNullOrEmpty(name, "name"); + checkNotNull(description, "description"); + checkNotNullOrEmpty(ecuDatas, "ecuDatas"); + checkNotNullOrEmpty(convertors, "convertors"); + this.id = id; + this.name = name; + this.description = description; + this.convertors = convertors; + this.address = buildCombinedAddress(ecuDatas); + setEcuDatas(ecuDatas); + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public EcuAddress getAddress() { + return address; + } + + public EcuDataConvertor getSelectedConvertor() { + return convertors[selectedConvertorIndex]; + } + + public EcuDataConvertor[] getConvertors() { + return convertors; + } + + public void selectConvertor(EcuDataConvertor convertor) { + if (convertor != getSelectedConvertor()) { + for (int i = 0; i < convertors.length; i++) { + EcuDerivedParameterConvertor parameterConvertor = convertors[i]; + if (convertor == parameterConvertor) { + selectedConvertorIndex = i; + } + } + notifyUpdateListeners(); + } + } + + public EcuDataType getDataType() { + return PARAMETER; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + public void addConvertorUpdateListener(ConvertorUpdateListener listener) { + checkNotNull(listener, "listener"); + listeners.add(listener); + } + + private EcuAddress buildCombinedAddress(EcuData[] ecuDatas) { + String[] addresses = new String[0]; + for (EcuData ecuData : ecuDatas) { + String[] newAddresses = ecuData.getAddress().getAddresses(); + String[] tmp = new String[addresses.length + newAddresses.length]; + System.arraycopy(addresses, 0, tmp, 0, addresses.length); + System.arraycopy(newAddresses, 0, tmp, addresses.length, newAddresses.length); + addresses = tmp; + } + return new EcuAddressImpl(addresses); + } + + private void setEcuDatas(EcuData[] ecuDatas) { + for (EcuDerivedParameterConvertor convertor : convertors) { + convertor.setEcuDatas(ecuDatas); + } + } + + private void notifyUpdateListeners() { + for (ConvertorUpdateListener listener : listeners) { + listener.notifyConvertorUpdate(this); + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuParameter.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuParameter.java new file mode 100644 index 0000000000..1e9d450ae6 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuParameter.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface EcuParameter extends EcuData { + + void addConvertorUpdateListener(ConvertorUpdateListener listener); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuParameterImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuParameterImpl.java new file mode 100644 index 0000000000..c5c12564aa --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuParameterImpl.java @@ -0,0 +1,109 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import static com.romraider.logger.ecu.definition.EcuDataType.PARAMETER; +import static com.romraider.util.ParamChecker.checkNotNull; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; +import java.util.HashSet; +import java.util.Set; + +public final class EcuParameterImpl implements EcuParameter { + private final String id; + private final String name; + private final String description; + private final EcuAddress address; + private final EcuDataConvertor[] convertors; + private final Set listeners = new HashSet(); + private int selectedConvertorIndex; + private boolean selected; + + public EcuParameterImpl(String id, String name, String description, EcuAddress address, EcuDataConvertor[] convertors) { + checkNotNullOrEmpty(id, "id"); + checkNotNullOrEmpty(name, "name"); + checkNotNull(description, "description"); + checkNotNull(address, "address"); + checkNotNullOrEmpty(convertors, "convertors"); + this.id = id; + this.name = name; + this.description = description; + this.address = address; + this.convertors = convertors; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public EcuAddress getAddress() { + return address; + } + + public EcuDataConvertor getSelectedConvertor() { + return convertors[selectedConvertorIndex]; + } + + public EcuDataConvertor[] getConvertors() { + return convertors; + } + + public void selectConvertor(EcuDataConvertor convertor) { + if (convertor != getSelectedConvertor()) { + for (int i = 0; i < convertors.length; i++) { + EcuDataConvertor dataConvertor = convertors[i]; + if (convertor == dataConvertor) { + selectedConvertorIndex = i; + } + } + notifyUpdateListeners(); + } + } + + public EcuDataType getDataType() { + return PARAMETER; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + public void addConvertorUpdateListener(ConvertorUpdateListener listener) { + checkNotNull(listener, "listener"); + listeners.add(listener); + } + + private void notifyUpdateListeners() { + for (ConvertorUpdateListener listener : listeners) { + listener.notifyConvertorUpdate(this); + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuSwitch.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuSwitch.java new file mode 100644 index 0000000000..703b7f254e --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuSwitch.java @@ -0,0 +1,24 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface EcuSwitch extends EcuData { + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuSwitchImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuSwitchImpl.java new file mode 100644 index 0000000000..90647aa59a --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EcuSwitchImpl.java @@ -0,0 +1,101 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import static com.romraider.logger.ecu.definition.EcuDataType.SWITCH; +import static com.romraider.util.ParamChecker.checkNotNull; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; + +public final class EcuSwitchImpl implements EcuSwitch { + private final String id; + private final String name; + private final String description; + private final EcuAddress address; + private final EcuDataConvertor[] convertors; + private int selectedConvertorIndex; + private boolean fileLogController; + private boolean selected; + + public EcuSwitchImpl(String id, String name, String description, EcuAddress address, EcuDataConvertor[] convertors) { + checkNotNullOrEmpty(id, "id"); + checkNotNullOrEmpty(name, "name"); + checkNotNull(description, "description"); + checkNotNull(address, "address"); + checkNotNullOrEmpty(convertors, "convertors"); + this.id = id; + this.name = name; + this.description = description; + this.address = address; + this.convertors = convertors; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public EcuAddress getAddress() { + return address; + } + + public EcuDataConvertor getSelectedConvertor() { + return convertors[selectedConvertorIndex]; + } + + public EcuDataConvertor[] getConvertors() { + return convertors; + } + + public void selectConvertor(EcuDataConvertor convertor) { + for (int i = 0; i < convertors.length; i++) { + EcuDataConvertor dataConvertor = convertors[i]; + if (convertor == dataConvertor) { + selectedConvertorIndex = i; + } + } + } + + public EcuDataType getDataType() { + return SWITCH; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + public void setFileLogController(boolean fileLogController) { + this.fileLogController = fileLogController; + } + + public boolean isFileLogController() { + return fileLogController; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/EvaluateEcuDefinition.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/EvaluateEcuDefinition.java new file mode 100644 index 0000000000..ef44acdb83 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/EvaluateEcuDefinition.java @@ -0,0 +1,51 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +import java.util.Map; + +import com.romraider.util.ParamChecker; + +/** + * From the ECU Definition Map retrieve the definition for the current ECU ID. + */ +public final class EvaluateEcuDefinition { + public EvaluateEcuDefinition() { + } + + /** + * Retrieve the definition for the current ECU ID. + * @param ecuDefMap - a map of ECU Definitions keyed by ECU ID. + * @param ecuId - the ECU ID to find the ECU Definition for. + * @return an ECU Definition or a New ECU Definition with all but the ECU ID set + * to "unknown". + */ + public final EcuDefinition getDef( + Map ecuDefMap, String ecuId) { + + ParamChecker.checkNotNull(ecuDefMap, "EcuDefinitionMap"); + EcuDefinition ecuDef = ecuDefMap.get(ecuId); + if (ecuDef == null) { + ecuDef = new EcuDefinitionImpl( + ecuId, "unknown", "unknown", "unknown", null); + } + return ecuDef; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/ExternalData.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/ExternalData.java new file mode 100644 index 0000000000..88e2b61841 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/ExternalData.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface ExternalData extends LoggerData { + + void addConvertorUpdateListener(ConvertorUpdateListener listener); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/LoggerData.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/LoggerData.java new file mode 100644 index 0000000000..6073096810 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/LoggerData.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition; + +public interface LoggerData { + + String getId(); + + String getName(); + + String getDescription(); + + EcuDataConvertor getSelectedConvertor(); + + EcuDataConvertor[] getConvertors(); + + void selectConvertor(EcuDataConvertor convertor); + + EcuDataType getDataType(); + + boolean isSelected(); + + void setSelected(boolean selected); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/plugin/PluginFilenameFilter.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/plugin/PluginFilenameFilter.java new file mode 100644 index 0000000000..72cdf6b02f --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/plugin/PluginFilenameFilter.java @@ -0,0 +1,30 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition.plugin; + +import java.io.File; +import java.io.FilenameFilter; + +public final class PluginFilenameFilter implements FilenameFilter { + + public boolean accept(File dir, String filename) { + return filename.endsWith(".plugin"); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionDocumentLoader.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionDocumentLoader.java new file mode 100644 index 0000000000..4435940c9c --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionDocumentLoader.java @@ -0,0 +1,70 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition.xml; + +import java.io.FileInputStream; +import java.io.IOException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +import com.romraider.logger.ecu.definition.EcuDefinition; + +/** + * Parse a given XML definition file into a DOM. + */ +public class EcuDefinitionDocumentLoader { + + private EcuDefinitionDocumentLoader() { + } + + /** + * Parse a given XML definition file into a DOM. + * @param ecuDef - an ECU Definition containing a File to parse. + * @return a DOM. + */ + public static final Document getDocument(EcuDefinition ecuDef) { + final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = null; + try { + builder = dbf.newDocumentBuilder(); + } + catch (ParserConfigurationException e) { + e.printStackTrace(); + } + + Document document = null; + try { + document = builder.parse( + new FileInputStream(ecuDef.getEcuDefFile())); + } + catch (SAXException e) { + e.printStackTrace(); + } + catch (IOException e) { + e.printStackTrace(); + } + return document; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionHandler.java new file mode 100644 index 0000000000..9997036923 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionHandler.java @@ -0,0 +1,256 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition.xml; + +import com.romraider.logger.ecu.definition.EcuDefinition; +import com.romraider.logger.ecu.definition.EcuDefinitionImpl; +import static com.romraider.util.ParamChecker.isNullOrEmpty; + +import org.apache.log4j.Logger; +import org.xml.sax.Attributes; +import org.xml.sax.helpers.DefaultHandler; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +/* + + + CAL ID:A4TC300K + 200 + A4TC300K + 03 + AT + 3614446205 + + +*/ +public final class EcuDefinitionHandler extends DefaultHandler { + private static final Logger LOGGER = Logger.getLogger(EcuDefinitionHandler.class); + private static final String TAG_ROM = "rom"; + private static final String TAG_ROMID = "romid"; + private static final String TAG_CALID = "internalidstring"; + private static final String TAG_ECUID = "ecuid"; + private static final String TAG_CASEID = "caseid"; + private static final String TAG_ADDRESS = "internalidaddress"; + private static final String TAG_YEAR = "year"; + private static final String TAG_MARKET = "market"; + private static final String TAG_MAKE = "make"; + private static final String TAG_MODEL = "model"; + private static final String TAG_SUBMODEL = "submodel"; + private static final String TAG_TRANS = "transmission"; + private static final String TAG_MEMMODEL = "memmodel"; + private static final String TAG_FLASH = "flashmethod"; + private static final String TAG_SIZE = "filesize"; + private static final String TAG_OBSOLETE = "obsolete"; + private static final String ATTR_BASE = "base"; + private Map ecuDefinitionMap = new HashMap(); + private String calId; + private String ecuId; + private String caseId; + private String address; + private String year; + private String market; + private String make; + private String model; + private String submodel; + private String transmission; + private String memmodel; + private String flashmethod; + private String filesize; + private String obsolete; + private String inherit; + private String carString; + private StringBuilder charBuffer; + private File ecuDefsFile; + + public EcuDefinitionHandler(File ecuDefsFile) { + this.ecuDefsFile = ecuDefsFile; + } + + public void startDocument() { + ecuDefinitionMap = new HashMap(); + } + + public void startElement(String uri, String localName, String qName, Attributes attributes) { + if (TAG_ROM.equals(qName)) { + inherit = attributes.getValue(ATTR_BASE); + } + else if (TAG_ROMID.equals(qName)) { + calId = ""; + ecuId = ""; + caseId = ""; + address = ""; + year = ""; + market = ""; + make = ""; + model = ""; + submodel = ""; + transmission = ""; + memmodel = ""; + flashmethod = ""; + filesize = ""; + obsolete = "0"; + carString = ""; + } + charBuffer = new StringBuilder(); + } + + public void characters(char[] ch, int start, int length) { + charBuffer.append(ch, start, length); + } + + public void endElement(String uri, String localName, String qName) { + if (TAG_ROM.equals(qName)) { + inherit = null; + } + else if (TAG_ROMID.equals(qName)) { + if (!isNullOrEmpty(ecuId) && + !isNullOrEmpty(calId) && + !isNullOrEmpty(year) && + !isNullOrEmpty(market) && + !isNullOrEmpty(make) && + !isNullOrEmpty(model) && + !isNullOrEmpty(submodel) && + !isNullOrEmpty(transmission) + ) { + carString = String.format("%s %s %s %s %s %s", + year, market, make, model, submodel, transmission); + ecuDefinitionMap.put(ecuId, + new EcuDefinitionImpl( + ecuId, calId, carString, inherit, ecuDefsFile)); + } + if (!isNullOrEmpty(ecuId) && + !isNullOrEmpty(calId) && + !isNullOrEmpty(address) && + !isNullOrEmpty(year) && + !isNullOrEmpty(market) && + !isNullOrEmpty(make) && + !isNullOrEmpty(model) && + !isNullOrEmpty(submodel) && + !isNullOrEmpty(transmission) && + !isNullOrEmpty(memmodel) && + !isNullOrEmpty(flashmethod) && + !isNullOrEmpty(obsolete) + ) { + LOGGER.debug(romDetail()); + } + } + else if (TAG_CALID.equals(qName)) { + calId = charBuffer.toString(); + } + else if (TAG_ECUID.equals(qName)) { + ecuId = charBuffer.toString(); + } + else if (TAG_CASEID.equals(qName)) { + caseId = charBuffer.toString(); + } + else if (TAG_ADDRESS.equals(qName)) { + address = charBuffer.toString(); + } + else if (TAG_YEAR.equals(qName)) { + year = charBuffer.toString(); + if (!year.isEmpty()) { + try { + if (Integer.parseInt(year) < 90) { + year = "20" + year; + } + } + catch (NumberFormatException e) { + if ((year.contains("/") || year.contains("-")) && + year.length() < 6 ) + year = "20" + year; + } + } + else { + year = "20xx"; + } + } + else if (TAG_MARKET.equals(qName)) { + market = charBuffer.toString(); + } + else if (TAG_MAKE.equals(qName)) { + make = charBuffer.toString(); + } + else if (TAG_MODEL.equals(qName)) { + model = charBuffer.toString(); + } + else if (TAG_SUBMODEL.equals(qName)) { + submodel = charBuffer.toString(); + } + else if (TAG_TRANS.equals(qName)) { + transmission = charBuffer.toString(); + } + else if (TAG_MEMMODEL.equals(qName)) { + memmodel = charBuffer.toString(); + } + else if (TAG_FLASH.equals(qName)) { + flashmethod = charBuffer.toString(); + } + else if (TAG_SIZE.equals(qName)) { + filesize = charBuffer.toString(); + } + else if (TAG_OBSOLETE.equals(qName)) { + obsolete = charBuffer.toString(); + } + } + + public Map getEcuDefinitionMap() { + return ecuDefinitionMap; + } + + public String romDetail() { + return String.format( + "calid='%s'," + + "address='%s'," + + "string='%s'," + + "caseid='%s'," + + "year='%s'," + + "market='%s'," + + "make='%s'," + + "model='%s'," + + "submodel='%s'," + + "transmission='%s'," + + "memmodel='%s'," + + "flash='%s'," + + "filesize='%s'," + + "obsolete='%s'," + + "inherit='%s'" + + "file='%s'", + calId, + address, + calId, + caseId, + year, + market, + make, + model, + submodel, + transmission, + memmodel, + flashmethod, + filesize , + obsolete, + inherit, + ecuDefsFile.getName() + ); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionInheritanceList.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionInheritanceList.java new file mode 100644 index 0000000000..b761292319 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuDefinitionInheritanceList.java @@ -0,0 +1,119 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition.xml; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import com.romraider.logger.ecu.definition.EcuDefinition; + +/** + * Get a List of ROM inheritance Nodes from the given DOM and ECU definition. + */ +public class EcuDefinitionInheritanceList { + + private EcuDefinitionInheritanceList() { + } + + /** + * Get a List of ROM inheritance Nodes + * @param document - the DOM document containing the ECU definition and + * its parents. + * @param ecuDef - ECU definition to start with. + * @return a List of Node starting with the given ECU listing back to the + * base definition. + */ + public static final List getInheritanceList( + Document document, + EcuDefinition ecuDef) { + + final XPathFactory xpf = XPathFactory.newInstance(); + final XPath xpath = xpf.newXPath(); + final List inheritance = new ArrayList(); + inheritance.add(ecuDef.getCalId()); + inheritance.add(ecuDef.getInherits()); + String base = ecuDef.getInherits(); + while (!base.contains("BASE")) { + base = getBaseRomId(xpath, document, base); + inheritance.add(base); + } + final List inheritanceNodes = new ArrayList(); + for (String inheritId : inheritance) { + Node baseNode = getBaseRomIdNode(xpath, document, inheritId); + inheritanceNodes.add(baseNode); + } + return inheritanceNodes; + } + + /** + * Get the CAL ID string of the base inheritance definition. + * @param xpath - the XPath evaluation environment. + * @param document - W3C DOM Document of an ECU definition XML file. + * @param calId - the known CAL ID to find the inheritance for. + * @return the CAL ID from the attribute 'base' in the 'rom' element . + */ + private static final String getBaseRomId( + XPath xpath, Document document, String calId) { + + String romBase = null; + try { + final Node calidNode = (Node) xpath.evaluate( + "/roms/rom/romid[xmlid='" + calId + "']", + document, XPathConstants.NODE); + romBase = calidNode.getParentNode().getAttributes().item(0). + getNodeValue(); + } + catch (XPathExpressionException e) { + e.printStackTrace(); + } + return romBase; + } + + /** + * Get the 'rom' Node which contains the CAL ID string. + * @param xpath - the XPath evaluation environment. + * @param document - W3C DOM Document of an ECU definition XM file. + * @param calId - the known CAL ID to find the inheritance for. + * @return the Node of the 'rom' parent element to the CAL ID. + */ + private static final Node getBaseRomIdNode( + XPath xpath, Document document, String calId) { + + Node romIdNode = null; + try { + romIdNode = (Node) xpath.evaluate( + "/roms/rom/romid[xmlid='" + calId + "']", + document, XPathConstants.NODE); + romIdNode = romIdNode.getParentNode(); + } + catch (XPathExpressionException e) { + e.printStackTrace(); + } + return romIdNode; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuTableDefinitionHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuTableDefinitionHandler.java new file mode 100644 index 0000000000..534d653098 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/definition/xml/EcuTableDefinitionHandler.java @@ -0,0 +1,113 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.definition.xml; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * Parse an ECU Definition XML file and return the attributes of the + * table name supplied. + */ +public final class EcuTableDefinitionHandler { + + private EcuTableDefinitionHandler() { + } + + /** + * Parse a given ECU Definition XML file and return the attributes of the + * table name supplied. + * @param document - W3C DOM Document of an ECU definition XML file. + * @param inheritanceNodeList - a List of Nodes of the 'rom' parents + * to the CAL ID supplied. + * @param tableName - the name of the table to find. + * @return a Map of table and scaling name/value attributes. + */ + public static final Map getTableDefinition( + Document document, + List inheritanceNodeList, + String tableName) { + + final Map table = + new HashMap(); + for (Node inheritIdNode : inheritanceNodeList) { + get2dTableMap(inheritIdNode, tableName, table); + } + return table; + } + + /** + * For the given Node and Table Name populate a Map with the table's + * attributes and the scaling attributes. + * @param xpath - the XPath evaluation environment. + * @param node - the 'rom' Node to root the search within. + * @param tableName - the Table Name to locate. + * @param tableMap2d - a Map to populate with attribute names and values. + */ + private static final void get2dTableMap( + Node node, String tableName, + Map tableMap2d) { + + final XPathFactory xpf = XPathFactory.newInstance(); + final XPath xpath = xpf.newXPath(); + try { + final Node tableNode = (Node) xpath.evaluate( + "table[@name='" + tableName + "']", + node, XPathConstants.NODE); + addAttributesAsMap(tableNode, tableMap2d); + + final Node scalingNode = (Node) xpath.evaluate( + "scaling", + tableNode, XPathConstants.NODE); + addAttributesAsMap(scalingNode, tableMap2d); + } + catch (NullPointerException e) { + } + catch (XPathExpressionException e) { + e.printStackTrace(); + } + } + + /** + * Convert XML attributes to a Map. + * @param node - the Node containing the attributes. + * @param tableMap - the Map to populate with attribute names and values. + */ + private static final void addAttributesAsMap( + Node node, Map tableMap) { + + final NamedNodeMap attrs = node.getAttributes(); + for (int i = 0; i < attrs.getLength(); i++) { + tableMap.put( + attrs.item(i).getNodeName(), + attrs.item(i).getNodeValue()); + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/ConfigurationException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/ConfigurationException.java new file mode 100644 index 0000000000..3c7fa21f5d --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/ConfigurationException.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class ConfigurationException extends RuntimeException { + + private static final long serialVersionUID = 2021993520731842524L; + + public ConfigurationException() { + } + + public ConfigurationException(String string) { + super(string); + } + + public ConfigurationException(String string, Throwable throwable) { + super(string, throwable); + } + + public ConfigurationException(Throwable throwable) { + super(throwable); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/FileLoggerException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/FileLoggerException.java new file mode 100644 index 0000000000..b0142612aa --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/FileLoggerException.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class FileLoggerException extends RuntimeException { + + private static final long serialVersionUID = -7851192938290131460L; + + public FileLoggerException() { + } + + public FileLoggerException(String string) { + super(string); + } + + public FileLoggerException(String string, Throwable throwable) { + super(string, throwable); + } + + public FileLoggerException(Throwable throwable) { + super(throwable); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/InvalidResponseException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/InvalidResponseException.java new file mode 100644 index 0000000000..cb031ef7a4 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/InvalidResponseException.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class InvalidResponseException extends RuntimeException { + + private static final long serialVersionUID = 296093377055913575L; + + public InvalidResponseException() { + } + + public InvalidResponseException(String string) { + super(string); + } + + public InvalidResponseException(String string, Throwable throwable) { + super(string, throwable); + } + + public InvalidResponseException(Throwable throwable) { + super(throwable); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/NotConnectedException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/NotConnectedException.java new file mode 100644 index 0000000000..1fa0d57bea --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/NotConnectedException.java @@ -0,0 +1,39 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class NotConnectedException extends RuntimeException { + private static final long serialVersionUID = -7287379536144468034L; + + public NotConnectedException() { + } + + public NotConnectedException(String string) { + super(string); + } + + public NotConnectedException(String string, Throwable throwable) { + super(string, throwable); + } + + public NotConnectedException(Throwable throwable) { + super(throwable); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/PortNotFoundException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/PortNotFoundException.java new file mode 100644 index 0000000000..54f1ff2934 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/PortNotFoundException.java @@ -0,0 +1,40 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class PortNotFoundException extends RuntimeException { + + private static final long serialVersionUID = -523838685805525387L; + + public PortNotFoundException() { + } + + public PortNotFoundException(String string) { + super(string); + } + + public PortNotFoundException(String string, Throwable throwable) { + super(string, throwable); + } + + public PortNotFoundException(Throwable throwable) { + super(throwable); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/SerialCommunicationException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/SerialCommunicationException.java new file mode 100644 index 0000000000..16954a6f4c --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/SerialCommunicationException.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class SerialCommunicationException extends RuntimeException { + + private static final long serialVersionUID = -3468947970939582263L; + + public SerialCommunicationException() { + } + + public SerialCommunicationException(String msg) { + super(msg); + } + + public SerialCommunicationException(String msg, Throwable cause) { + super(msg, cause); + } + + public SerialCommunicationException(Throwable cause) { + super(cause); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/UnsupportedPortTypeException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/UnsupportedPortTypeException.java new file mode 100644 index 0000000000..353c839acd --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/UnsupportedPortTypeException.java @@ -0,0 +1,40 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class UnsupportedPortTypeException extends RuntimeException { + + private static final long serialVersionUID = 5398746954800909391L; + + public UnsupportedPortTypeException() { + } + + public UnsupportedPortTypeException(String string) { + super(string); + } + + public UnsupportedPortTypeException(String string, Throwable throwable) { + super(string, throwable); + } + + public UnsupportedPortTypeException(Throwable throwable) { + super(throwable); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/exception/UnsupportedProtocolException.java b/java_console/romraider/src/com/romraider/logger/ecu/exception/UnsupportedProtocolException.java new file mode 100644 index 0000000000..4d0a07e0cf --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/exception/UnsupportedProtocolException.java @@ -0,0 +1,41 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.exception; + +public final class UnsupportedProtocolException extends RuntimeException { + + private static final long serialVersionUID = -5005888534387937344L; + + public UnsupportedProtocolException() { + } + + public UnsupportedProtocolException(String string) { + super(string); + } + + public UnsupportedProtocolException(String string, Throwable throwable) { + super(string, throwable); + } + + public UnsupportedProtocolException(Throwable throwable) { + super(throwable); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfile.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfile.java new file mode 100644 index 0000000000..09028e6c6a --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfile.java @@ -0,0 +1,40 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +import com.romraider.logger.ecu.definition.EcuDataConvertor; +import com.romraider.logger.ecu.definition.LoggerData; + +public interface UserProfile { + + boolean contains(LoggerData loggerData); + + boolean isSelectedOnLiveDataTab(LoggerData loggerData); + + boolean isSelectedOnGraphTab(LoggerData loggerData); + + boolean isSelectedOnDashTab(LoggerData loggerData); + + EcuDataConvertor getSelectedConvertor(LoggerData loggerData); + + byte[] getBytes(); + + String getProtocol(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileFileFilter.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileFileFilter.java new file mode 100644 index 0000000000..6f8ac25f94 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileFileFilter.java @@ -0,0 +1,38 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +import com.romraider.swing.GenericFileFilter; +import javax.swing.filechooser.FileFilter; +import java.io.File; + +public final class UserProfileFileFilter extends FileFilter { + + private final FileFilter filter = new GenericFileFilter("ECU Logger User Profiles", "xml"); + + public boolean accept(File file) { + return filter.accept(file); + } + + public String getDescription() { + return filter.getDescription(); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileImpl.java new file mode 100644 index 0000000000..0e4ca5e514 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileImpl.java @@ -0,0 +1,151 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +import com.romraider.Settings; +import com.romraider.logger.ecu.definition.EcuDataConvertor; +import com.romraider.logger.ecu.definition.EcuParameter; +import com.romraider.logger.ecu.definition.EcuSwitch; +import com.romraider.logger.ecu.definition.ExternalData; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.exception.ConfigurationException; +import com.romraider.util.SettingsManager; + +import static com.romraider.util.ParamChecker.checkNotNull; +import static com.romraider.util.ParamChecker.isNullOrEmpty; +import java.util.Map; + +public final class UserProfileImpl implements UserProfile { + private static final String NEW_LINE = System.getProperty("line.separator"); + private final Map params; + private final Map switches; + private final Map external; + private final String protocol; + + public UserProfileImpl( + Map params, + Map switches, + Map external, + String protocol) { + + checkNotNull(params, "params"); + checkNotNull(switches, "switches"); + checkNotNull(external, "external"); + this.params = params; + this.switches = switches; + this.external = external; + this.protocol = protocol; + } + + public boolean contains(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + return getMap(loggerData).keySet().contains(loggerData.getId()); + } + + public boolean isSelectedOnLiveDataTab(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + return contains(loggerData) && getUserProfileItem(loggerData).isLiveDataSelected(); + } + + public boolean isSelectedOnGraphTab(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + return contains(loggerData) && getUserProfileItem(loggerData).isGraphSelected(); + } + + public boolean isSelectedOnDashTab(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + return contains(loggerData) && getUserProfileItem(loggerData).isDashSelected(); + } + + public EcuDataConvertor getSelectedConvertor(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + if (contains(loggerData)) { + String defaultUnits = getUserProfileItem(loggerData).getUnits(); + if (defaultUnits != null && loggerData.getConvertors().length > 1) { + for (EcuDataConvertor convertor : loggerData.getConvertors()) { + if (defaultUnits.equals(convertor.getUnits())) return convertor; + } + throw new ConfigurationException("Unknown default units, '" + defaultUnits + "', specified for [" + loggerData.getId() + "] " + loggerData.getName()); + } + } + return loggerData.getSelectedConvertor(); + } + + public byte[] getBytes() { + return buildXml().getBytes(); + } + + @Override + public String getProtocol() { + return protocol; + } + + private String buildXml() { + final Settings settings = SettingsManager.getSettings(); + StringBuilder builder = new StringBuilder(); + builder.append("").append(NEW_LINE); + builder.append("").append(NEW_LINE).append(NEW_LINE); + builder.append("").append(NEW_LINE); + if (!params.isEmpty()) { + builder.append(" ").append(NEW_LINE); + appendLoggerDataElements(builder, "parameter", params, true); + builder.append(" ").append(NEW_LINE); + } + if (!switches.isEmpty()) { + builder.append(" ").append(NEW_LINE); + appendLoggerDataElements(builder, "switch", switches, false); + builder.append(" ").append(NEW_LINE); + } + if (!external.isEmpty()) { + builder.append(" ").append(NEW_LINE); + // Comment out the next line to disable Externals from being saved + // as there seems to be a bug when a profile is reloaded, the + // Logger tries to connect twice causing one or both to fail. + appendLoggerDataElements(builder, "external", external, true); + builder.append(" ").append(NEW_LINE); + } + builder.append("").append(NEW_LINE); + return builder.toString(); + } + + private void appendLoggerDataElements(StringBuilder builder, String dataType, Map dataMap, boolean showUnits) { + for (String id : dataMap.keySet()) { + UserProfileItem item = dataMap.get(id); + builder.append(" <").append(dataType).append(" id=\"").append(id).append("\""); + if (item.isLiveDataSelected()) builder.append(" livedata=\"selected\""); + if (item.isGraphSelected()) builder.append(" graph=\"selected\""); + if (item.isDashSelected()) builder.append(" dash=\"selected\""); + if (showUnits && !isNullOrEmpty(item.getUnits())) + builder.append(" units=\"").append(item.getUnits()).append("\""); + builder.append("/>").append(NEW_LINE); + } + } + + private UserProfileItem getUserProfileItem(LoggerData loggerData) { + return getMap(loggerData).get(loggerData.getId()); + } + + private Map getMap(LoggerData loggerData) { + if (loggerData instanceof EcuParameter) return params; + else if (loggerData instanceof EcuSwitch) return switches; + else if (loggerData instanceof ExternalData) return external; + else throw new UnsupportedOperationException("Unknown LoggerData type: " + loggerData.getClass()); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileItem.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileItem.java new file mode 100644 index 0000000000..1813c5f978 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileItem.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +public interface UserProfileItem { + + boolean isDashSelected(); + + boolean isGraphSelected(); + + boolean isLiveDataSelected(); + + String getUnits(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileItemImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileItemImpl.java new file mode 100644 index 0000000000..e27507f6e8 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileItemImpl.java @@ -0,0 +1,51 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +public final class UserProfileItemImpl implements UserProfileItem { + private final String units; + private final boolean liveDataSelected; + private final boolean graphSelected; + private final boolean dashSelected; + + public UserProfileItemImpl(String units, boolean liveDataSelected, boolean graphSelected, boolean dashSelected) { + this.units = units; + this.liveDataSelected = liveDataSelected; + this.graphSelected = graphSelected; + this.dashSelected = dashSelected; + } + + public boolean isDashSelected() { + return dashSelected; + } + + public boolean isGraphSelected() { + return graphSelected; + } + + public boolean isLiveDataSelected() { + return liveDataSelected; + } + + public String getUnits() { + return units; + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileLoader.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileLoader.java new file mode 100644 index 0000000000..33b5a9a6c8 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileLoader.java @@ -0,0 +1,26 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +public interface UserProfileLoader { + String BACKUP_PROFILE = "/.RomRaider/profile_backup.xml"; + + UserProfile loadProfile(String filePath); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileLoaderImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileLoaderImpl.java new file mode 100644 index 0000000000..6884432b9b --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/UserProfileLoaderImpl.java @@ -0,0 +1,56 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile; + +import com.romraider.logger.ecu.profile.xml.UserProfileHandler; +import static com.romraider.util.ParamChecker.checkNotNullOrEmpty; +import static com.romraider.util.SaxParserFactory.getSaxParser; +import org.apache.log4j.Logger; +import org.xml.sax.SAXParseException; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +public final class UserProfileLoaderImpl implements UserProfileLoader { + private static final Logger LOGGER = Logger.getLogger(UserProfileLoaderImpl.class); + + public UserProfile loadProfile(String userProfileFilePath) { + checkNotNullOrEmpty(userProfileFilePath, "userProfileFilePath"); + LOGGER.info("Loading profile: " + userProfileFilePath); + try { + InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(userProfileFilePath))); + try { + UserProfileHandler handler = new UserProfileHandler(); + getSaxParser().parse(inputStream, handler); + return handler.getUserProfile(); + } finally { + inputStream.close(); + } + } catch (SAXParseException spe) { + // catch general parsing exception - enough people don't unzip the defs that a better error message is in order + LOGGER.error("Error loading user profile file: " + userProfileFilePath + ". Please make sure the definition file is correct. If it is in a ZIP archive, unzip the file and try again."); + return null; + } catch (Exception e) { + LOGGER.error("Error loading user profile file: " + userProfileFilePath, e); + return null; + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/profile/xml/UserProfileHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/profile/xml/UserProfileHandler.java new file mode 100644 index 0000000000..633e830344 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/profile/xml/UserProfileHandler.java @@ -0,0 +1,79 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.profile.xml; + +import com.romraider.logger.ecu.profile.UserProfile; +import com.romraider.logger.ecu.profile.UserProfileImpl; +import com.romraider.logger.ecu.profile.UserProfileItem; +import com.romraider.logger.ecu.profile.UserProfileItemImpl; +import org.xml.sax.Attributes; +import org.xml.sax.helpers.DefaultHandler; +import java.util.HashMap; +import java.util.Map; + +public final class UserProfileHandler extends DefaultHandler { + private static final String SELECTED = "selected"; + private static final String TAG_PROFILE = "profile"; + private static final String TAG_PARAMETER = "parameter"; + private static final String TAG_SWITCH = "switch"; + private static final String TAG_EXTERNAL = "external"; + private static final String ATTR_PROTOCOL = "protocol"; + private static final String ATTR_ID = "id"; + private static final String ATTR_UNITS = "units"; + private static final String ATTR_LIVE_DATA = "livedata"; + private static final String ATTR_GRAPH = "graph"; + private static final String ATTR_DASH = "dash"; + private Map params; + private Map switches; + private Map external; + private String protocol; + + public void startDocument() { + params = new HashMap(); + switches = new HashMap(); + external = new HashMap(); + } + + public void startElement(String uri, String localName, String qName, Attributes attributes) { + if (TAG_PROFILE.equals(qName)) { + protocol = attributes.getValue(ATTR_PROTOCOL); + } else if (TAG_PARAMETER.equals(qName)) { + params.put(attributes.getValue(ATTR_ID), getUserProfileItem(attributes)); + } else if (TAG_SWITCH.equals(qName)) { + switches.put(attributes.getValue(ATTR_ID), getUserProfileItem(attributes)); + } else if (TAG_EXTERNAL.equals(qName)) { + external.put(attributes.getValue(ATTR_ID), getUserProfileItem(attributes)); + } + } + + public UserProfile getUserProfile() { + return new UserProfileImpl(params, switches, external, protocol); + } + + private UserProfileItem getUserProfileItem(Attributes attributes) { + return new UserProfileItemImpl( + attributes.getValue(ATTR_UNITS), + SELECTED.equalsIgnoreCase(attributes.getValue(ATTR_LIVE_DATA)), + SELECTED.equalsIgnoreCase(attributes.getValue(ATTR_GRAPH)), + SELECTED.equalsIgnoreCase(attributes.getValue(ATTR_DASH)) + ); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/DataRegistrationBroker.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/DataRegistrationBroker.java new file mode 100644 index 0000000000..ba791b1625 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/DataRegistrationBroker.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +import com.romraider.logger.ecu.definition.LoggerData; + +public interface DataRegistrationBroker extends StatusChangeListener { + + void registerLoggerDataForLogging(LoggerData loggerData); + + void deregisterLoggerDataFromLogging(LoggerData loggerData); + + void clear(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/DataRegistrationBrokerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/DataRegistrationBrokerImpl.java new file mode 100644 index 0000000000..d5844449db --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/DataRegistrationBrokerImpl.java @@ -0,0 +1,93 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +import com.romraider.logger.ecu.comms.controller.LoggerController; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandlerManager; +import static com.romraider.util.ParamChecker.checkNotNull; +import static java.util.Collections.synchronizedList; +import java.util.ArrayList; +import java.util.List; + +public final class DataRegistrationBrokerImpl implements DataRegistrationBroker { + private final List registeredLoggerData = synchronizedList(new ArrayList()); + private final LoggerController controller; + private final DataUpdateHandlerManager handlerManager; + private final String id; + + public DataRegistrationBrokerImpl(LoggerController controller, DataUpdateHandlerManager handlerManager) { + checkNotNull(controller, handlerManager); + this.controller = controller; + this.handlerManager = handlerManager; + id = System.currentTimeMillis() + "_" + hashCode(); + } + + public synchronized void registerLoggerDataForLogging(final LoggerData loggerData) { + if (!registeredLoggerData.contains(loggerData)) { + // register param with handlers + handlerManager.registerData(loggerData); + + // add logger + controller.addLogger(id, loggerData); + + // add to registered parameters list + registeredLoggerData.add(loggerData); + } + } + + public synchronized void deregisterLoggerDataFromLogging(LoggerData loggerData) { + if (registeredLoggerData.contains(loggerData)) { + // deregister from dependant objects + deregisterLoggerDataFromDependants(loggerData); + + // remove from registered list + registeredLoggerData.remove(loggerData); + } + } + + public synchronized void clear() { + for (LoggerData loggerData : registeredLoggerData) { + deregisterLoggerDataFromDependants(loggerData); + } + registeredLoggerData.clear(); + } + + public synchronized void connecting() { + } + + public synchronized void readingData() { + } + + public synchronized void loggingData() { + } + + public synchronized void stopped() { + } + + private void deregisterLoggerDataFromDependants(LoggerData loggerData) { + // remove logger + controller.removeLogger(id, loggerData); + + // deregister param from handlers + handlerManager.deregisterData(loggerData); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/EcuDataComparator.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/EcuDataComparator.java new file mode 100644 index 0000000000..60c1fd43a0 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/EcuDataComparator.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +import com.romraider.logger.ecu.definition.LoggerData; +import java.util.Comparator; + +public final class EcuDataComparator implements Comparator { + + public int compare(LoggerData loggerData1, LoggerData loggerData2) { + return loggerData1.getName().compareTo(loggerData2.getName()); + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/MessageListener.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/MessageListener.java new file mode 100644 index 0000000000..1d612e26ec --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/MessageListener.java @@ -0,0 +1,35 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +public interface MessageListener { + + void reportStats(String message); + + void reportMessage(String message); + + void reportMessageInTitleBar(String message); + + void reportError(String error); + + void reportError(Exception e); + + void reportError(String error, Exception e); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/SerialPortComboBox.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/SerialPortComboBox.java new file mode 100644 index 0000000000..cfa40eed63 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/SerialPortComboBox.java @@ -0,0 +1,103 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +import static com.romraider.util.ParamChecker.checkNotNull; + +import java.util.Set; +import java.util.TreeSet; + +import javax.swing.JComboBox; + +import com.romraider.io.serial.port.SerialPortRefreshListener; +import com.romraider.util.SettingsManager; + +public final class SerialPortComboBox extends JComboBox implements SerialPortRefreshListener { + private static final long serialVersionUID = 5693976713268676676L; + + public SerialPortComboBox() { + } + + @Override + public synchronized void refreshPortList(Set ports, String defaultSelectedPort) { + checkNotNull(ports); + boolean changeDetected = ports.isEmpty() || ports.size() != getItemCount(); + if (!changeDetected) { + for (int i = 0; i < getItemCount(); i++) { + String port = (String) getItemAt(i); + if (!ports.contains(port)) { + changeDetected = true; + break; + } + } + if (!changeDetected) { + Set comboPorts = new TreeSet(); + for (int i = 0; i < getItemCount(); i++) { + comboPorts.add((String) getItemAt(i)); + } + for (String port : ports) { + if (!comboPorts.contains(port)) { + changeDetected = true; + break; + } + } + } + } + if (changeDetected) { + String selectedPort = (String) getSelectedItem(); + if (selectedPort == null) { + selectedPort = defaultSelectedPort; + } + removeAllItems(); + if (!ports.isEmpty()) { + for (String port : ports) { + addItem(port); + } + if (selectedPort != null && ports.contains(selectedPort)) { + setSelectedItem(selectedPort); + SettingsManager.getSettings().setLoggerPort(selectedPort); + } else { + setSelectedIndex(0); + SettingsManager.getSettings().setLoggerPort((String) getItemAt(0)); + } + } + } + } + + @Override + public void setSelectedItem(Object object) { + if (contains(object)) { + super.setSelectedItem(object); + } else { + if (getItemCount() >= 1) { + setSelectedIndex(0); + } + } + } + + private boolean contains(Object object) { + for (int i = 0; i < getItemCount(); i++) { + if (getItemAt(i) != null && getItemAt(i).equals(object)) { + return true; + } + } + return false; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/StatusChangeListener.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/StatusChangeListener.java new file mode 100644 index 0000000000..00bce5eff7 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/StatusChangeListener.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +public interface StatusChangeListener { + + void connecting(); + + void readingData(); + + void loggingData(); + + void stopped(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/StatusIndicator.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/StatusIndicator.java new file mode 100644 index 0000000000..5c14803577 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/StatusIndicator.java @@ -0,0 +1,73 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui; + +import static java.awt.BorderLayout.WEST; +import static java.awt.Font.BOLD; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; + +public final class StatusIndicator extends JPanel implements StatusChangeListener { + private static final long serialVersionUID = -3244690866698807677L; + private final JLabel statusLabel = new JLabel(); + private static final String TEXT_CONNECTING = "Connecting "; + private static final String TEXT_READING = "Reading data "; + private static final String TEXT_LOGGING = "Logging to file "; + private static final String TEXT_STOPPED = "Stopped "; + private static final ImageIcon ICON_CONNECTING = new ImageIcon(StatusIndicator.class.getClass().getResource("/graphics/logger_blue.png")); + private static final ImageIcon ICON_READING = new ImageIcon(StatusIndicator.class.getClass().getResource("/graphics/logger_green.png")); + private static final ImageIcon ICON_LOGGING = new ImageIcon(StatusIndicator.class.getClass().getResource("/graphics/logger_recording.png")); + private static final ImageIcon ICON_STOPPED = new ImageIcon(StatusIndicator.class.getClass().getResource("/graphics/logger_stop.png")); + + public StatusIndicator() { + setLayout(new BorderLayout()); + statusLabel.setFont(getFont().deriveFont(BOLD)); + add(statusLabel, WEST); + stopped(); + } + + public void connecting() { + updateStatusLabel(TEXT_CONNECTING, ICON_CONNECTING); + } + + public void readingData() { + updateStatusLabel(TEXT_READING, ICON_READING); + } + + public void loggingData() { + updateStatusLabel(TEXT_LOGGING, ICON_LOGGING); + } + + public void stopped() { + updateStatusLabel(TEXT_STOPPED, ICON_STOPPED); + } + + private void updateStatusLabel(final String text, final ImageIcon icon) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + statusLabel.setText(text); + statusLabel.setIcon(icon); + } + }); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandler.java new file mode 100644 index 0000000000..d9c966db6f --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandler.java @@ -0,0 +1,37 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler; + +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.definition.LoggerData; + +public interface DataUpdateHandler { + + void registerData(LoggerData loggerData); + + void handleDataUpdate(Response response); + + void deregisterData(LoggerData loggerData); + + void cleanUp(); + + void reset(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandlerManager.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandlerManager.java new file mode 100644 index 0000000000..49fa50e8b7 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandlerManager.java @@ -0,0 +1,36 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler; + +import com.romraider.logger.ecu.definition.LoggerData; + +public interface DataUpdateHandlerManager { + + void addHandler(DataUpdateHandler handler); + + void registerData(LoggerData loggerData); + + void deregisterData(LoggerData loggerData); + + void cleanUp(); + + void reset(); + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandlerManagerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandlerManagerImpl.java new file mode 100644 index 0000000000..7f19994bcf --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/DataUpdateHandlerManagerImpl.java @@ -0,0 +1,57 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler; + +import com.romraider.logger.ecu.definition.LoggerData; +import java.util.ArrayList; +import java.util.List; + +public final class DataUpdateHandlerManagerImpl implements DataUpdateHandlerManager { + private final List handlers = new ArrayList(); + + public synchronized void addHandler(DataUpdateHandler handler) { + handlers.add(handler); + } + + public synchronized void registerData(LoggerData loggerData) { + for (DataUpdateHandler handler : handlers) { + handler.registerData(loggerData); + } + } + + public synchronized void deregisterData(LoggerData loggerData) { + for (DataUpdateHandler handler : handlers) { + handler.deregisterData(loggerData); + } + } + + public synchronized void cleanUp() { + for (DataUpdateHandler handler : handlers) { + handler.cleanUp(); + } + } + + public synchronized void reset() { + for (DataUpdateHandler handler : handlers) { + handler.reset(); + } + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLogger.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLogger.java new file mode 100644 index 0000000000..b3012c2402 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLogger.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +public interface FileLogger { + void start(); + + void stop(); + + void writeHeaders(String headers); + + void writeLine(String line, long timestamp); + + boolean isStarted(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchHandler.java new file mode 100644 index 0000000000..051af92be0 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchHandler.java @@ -0,0 +1,25 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +public interface FileLoggerControllerSwitchHandler { + + void handleSwitch(double switchValue); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchMonitor.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchMonitor.java new file mode 100644 index 0000000000..248428d414 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchMonitor.java @@ -0,0 +1,29 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +import com.romraider.logger.ecu.definition.EcuSwitch; + +public interface FileLoggerControllerSwitchMonitor { + + void monitorFileLoggerSwitch(double switchValue); + + EcuSwitch getEcuSwitch(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchMonitorImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchMonitorImpl.java new file mode 100644 index 0000000000..fb62bb5753 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerControllerSwitchMonitorImpl.java @@ -0,0 +1,42 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +import com.romraider.logger.ecu.definition.EcuSwitch; +import static com.romraider.util.ParamChecker.checkNotNull; + +public final class FileLoggerControllerSwitchMonitorImpl implements FileLoggerControllerSwitchMonitor { + private final EcuSwitch fileLoggingSwitch; + private final FileLoggerControllerSwitchHandler handler; + + public FileLoggerControllerSwitchMonitorImpl(EcuSwitch fileLoggingSwitch, FileLoggerControllerSwitchHandler handler) { + checkNotNull(fileLoggingSwitch, handler); + this.fileLoggingSwitch = fileLoggingSwitch; + this.handler = handler; + } + + public void monitorFileLoggerSwitch(double switchValue) { + handler.handleSwitch(switchValue); + } + + public EcuSwitch getEcuSwitch() { + return fileLoggingSwitch; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerImpl.java new file mode 100644 index 0000000000..74018aba3e --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileLoggerImpl.java @@ -0,0 +1,146 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +import static com.romraider.util.ParamChecker.checkNotNull; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.romraider.Settings; +import com.romraider.logger.ecu.exception.FileLoggerException; +import com.romraider.logger.ecu.ui.MessageListener; +import com.romraider.util.FormatFilename; +import com.romraider.util.SettingsManager; + +public final class FileLoggerImpl implements FileLogger { + private static final String NEW_LINE = System.getProperty("line.separator"); + private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); + private final SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS"); + private final MessageListener messageListener; + private boolean started; + private OutputStream os; + private long startTimestamp; + private boolean zero; + + public FileLoggerImpl(MessageListener messageListener) { + checkNotNull(messageListener); + this.messageListener = messageListener; + } + + @Override + public void start() { + if (!started) { + stop(); + try { + String filePath = buildFilePath(); + os = new BufferedOutputStream(new FileOutputStream(filePath)); + messageListener.reportMessageInTitleBar( + "Started logging to file: " + + FormatFilename.getShortName(filePath)); + zero = true; + } catch (Exception e) { + stop(); + throw new FileLoggerException(e); + } + started = true; + } + } + + @Override + public void stop() { + if (os != null) { + try { + os.close(); + messageListener.reportMessageInTitleBar("Stopped logging to file."); + } catch (Exception e) { + throw new FileLoggerException(e); + } + } + started = false; + } + + @Override + public boolean isStarted() { + return started; + } + + @Override + public void writeHeaders(String headers) { + String timeHeader = "Time"; + if (!SettingsManager.getSettings().isFileLoggingAbsoluteTimestamp()) { + timeHeader = timeHeader + " (msec)"; + } + writeText(timeHeader + headers); + } + + @Override + public void writeLine(String line, long timestamp) { + writeText(prependTimestamp(line, timestamp)); + } + + private void writeText(String text) { + try { + os.write(text.getBytes()); + if (!text.endsWith(NEW_LINE)) { + os.write(NEW_LINE.getBytes()); + } + } catch (Exception e) { + stop(); + throw new FileLoggerException(e); + } + } + + private String prependTimestamp(String line, long timestamp) { + String formattedTimestamp; + if (SettingsManager.getSettings().isFileLoggingAbsoluteTimestamp()) { + formattedTimestamp = timestampFormat.format(new Date(timestamp)); + } else { + if (zero) { + formattedTimestamp = "0"; + startTimestamp = System.currentTimeMillis(); + zero = false; + } else { + formattedTimestamp = String.valueOf(System.currentTimeMillis() - startTimestamp); + } + } + return new StringBuilder(formattedTimestamp).append(line).toString(); + } + + private String buildFilePath() { + String logDir = SettingsManager.getSettings().getLoggerOutputDirPath(); + if (!logDir.endsWith(File.separator)) { + logDir += File.separator; + } + logDir += "romraiderlog_"; + Settings settings = SettingsManager.getSettings(); + if (settings.getLogfileNameText() != null + && !settings.getLogfileNameText().isEmpty()) { + logDir += settings.getLogfileNameText() + "_"; + } + logDir += dateFormat.format(new Date()) + ".csv"; + return logDir; + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileUpdateHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileUpdateHandler.java new file mode 100644 index 0000000000..7206f44272 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileUpdateHandler.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +import com.romraider.logger.ecu.ui.StatusChangeListener; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; + +public interface FileUpdateHandler extends DataUpdateHandler { + + void addListener(StatusChangeListener listener); + + void start(); + + void stop(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileUpdateHandlerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileUpdateHandlerImpl.java new file mode 100644 index 0000000000..7795075bf3 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/file/FileUpdateHandlerImpl.java @@ -0,0 +1,212 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.file; + +import static com.romraider.util.ParamChecker.checkNotNull; +import static java.util.Collections.synchronizedList; +import static java.util.Collections.synchronizedMap; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.definition.ConvertorUpdateListener; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.MessageListener; +import com.romraider.logger.ecu.ui.StatusChangeListener; + +public final class FileUpdateHandlerImpl implements FileUpdateHandler, ConvertorUpdateListener { + private final Map loggerDatas = synchronizedMap(new LinkedHashMap()); + private final List listeners = synchronizedList(new ArrayList()); + private final FileLogger fileLogger; + private Line currentLine = new Line(loggerDatas.keySet()); + + public FileUpdateHandlerImpl(MessageListener messageListener) { + fileLogger = new FileLoggerImpl(messageListener); + } + + @Override + public synchronized void addListener(StatusChangeListener listener) { + checkNotNull(listener, "listener"); + listeners.add(listener); + } + + @Override + public synchronized void registerData(LoggerData loggerData) { + if (loggerDatas.keySet().contains(loggerData)) { + loggerDatas.put(loggerData, loggerDatas.get(loggerData) + 1); + } else { + loggerDatas.put(loggerData, 1); + resetLine(); + writeHeaders(); + } + } + + @Override + public synchronized void handleDataUpdate(Response response) { + if (fileLogger.isStarted()) { + for (LoggerData loggerData : response.getData()) { + currentLine.updateParamValue(loggerData, loggerData.getSelectedConvertor().format(response.getDataValue(loggerData))); + } + if (currentLine.isFull()) { + fileLogger.writeLine(currentLine.values(), response.getTimestamp()); + resetLine(); + } + } + } + + @Override + public synchronized void deregisterData(LoggerData loggerData) { + if (loggerDatas.keySet().contains(loggerData) && loggerDatas.get(loggerData) > 1) { + loggerDatas.put(loggerData, loggerDatas.get(loggerData) - 1); + } else { + loggerDatas.remove(loggerData); + resetLine(); + writeHeaders(); + } + } + + @Override + public synchronized void cleanUp() { + if (fileLogger.isStarted()) { + fileLogger.stop(); + } + } + + @Override + public synchronized void reset() { + } + + @Override + public synchronized void notifyConvertorUpdate(LoggerData updatedLoggerData) { + resetLine(); + writeHeaders(); + } + + @Override + public synchronized void start() { + if (!fileLogger.isStarted()) { + fileLogger.start(); + notifyListeners(true); + writeHeaders(); + } + } + + @Override + public synchronized void stop() { + if (fileLogger.isStarted()) { + fileLogger.stop(); + notifyListeners(false); + } + } + + private void resetLine() { + currentLine = new Line(loggerDatas.keySet()); + } + + private void writeHeaders() { + if (fileLogger.isStarted()) { + fileLogger.writeHeaders(currentLine.headers()); + } + } + + private void notifyListeners(boolean loggingToFile) { + for (StatusChangeListener listener : listeners) { + if (loggingToFile) { + listener.loggingData(); + } else { + listener.readingData(); + } + } + } + + private final class Line { + private final Locale userLocale = Locale.getDefault(); + private static final char COMMA = ','; + private static final char SEMICOLON = ';'; + private final Set locales = new HashSet( + Arrays.asList(new String[] { + "be_BY","bg_BG","ca_ES","cs_CZ","da_DK","de_AT","de_CH","de_DE","de_LU", + "el_CY","el_GR","es_AR","es_BO","es_CL","es_CO","es_EC","es_ES","es_PE", + "es_PY","es_UY","es_VE","et_EE","fi_FI","fr_BE","fr_CA","fr_CH","fr_FR", + "fr_LU","hr_HR","hu_HU","in_ID","is_IS","it_CH","it_IT","lt_LT","lv_LV", + "mk_MK","nl_BE","nl_NL","no_NO","no_NO_NY","pl_PL","pt_BR","pt_PT", + "ro_RO","ru_RU","sk_SK","sl_SI","sq_AL","sr_BA","sr_CS","sr_ME","sr_RS", + "sv_SE","tr_TR","uk_UA","vi_VN" + } + )); + private final Map loggerDataValues; + private final char delimiter; + { + if (locales.contains(userLocale.toString())) { + delimiter = SEMICOLON; + } + else { + delimiter = COMMA; + } + } + + public Line(Set loggerDatas) { + this.loggerDataValues = new LinkedHashMap(); + for (LoggerData loggerData : loggerDatas) { + loggerDataValues.put(loggerData, null); + } + } + + public synchronized void updateParamValue(LoggerData loggerData, String value) { + if (loggerDataValues.containsKey(loggerData)) { + loggerDataValues.put(loggerData, value); + } + } + + public synchronized boolean isFull() { + for (LoggerData loggerData : loggerDataValues.keySet()) { + if (loggerDataValues.get(loggerData) == null) { + return false; + } + } + return true; + } + + public synchronized String headers() { + StringBuilder buffer = new StringBuilder(); + for (LoggerData loggerData : loggerDataValues.keySet()) { + buffer.append(delimiter).append(loggerData.getName()).append(" (") + .append(loggerData.getSelectedConvertor().getUnits()).append(')'); + } + return buffer.toString(); + } + + public synchronized String values() { + StringBuilder buffer = new StringBuilder(); + for (LoggerData loggerData : loggerDataValues.keySet()) { + String value = loggerDataValues.get(loggerData); + buffer.append(delimiter).append(value); + } + return buffer.toString(); + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/graph/SpringUtilities.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/graph/SpringUtilities.java new file mode 100644 index 0000000000..26942935a5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/graph/SpringUtilities.java @@ -0,0 +1,222 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.graph; + +import org.apache.log4j.Logger; +import javax.swing.Spring; +import javax.swing.SpringLayout; +import java.awt.Component; +import java.awt.Container; + +/** + * A 1.4 file that provides utility methods for + * creating form- or grid-style layouts with SpringLayout. + * These utilities are used by several programs, such as + * SpringBox and SpringCompactGrid. + */ +public class SpringUtilities { + private static final Logger LOGGER = Logger.getLogger(SpringUtilities.class); + + private SpringUtilities() { + throw new UnsupportedOperationException(); + } + + /** + * A debugging utility that prints to stdout the component's + * minimum, preferred, and maximum sizes. + */ + public static void printSizes(Component c) { + LOGGER.debug("minimumSize = " + c.getMinimumSize()); + LOGGER.debug("preferredSize = " + c.getPreferredSize()); + LOGGER.debug("maximumSize = " + c.getMaximumSize()); + } + + /** + * Aligns the first rows * cols + * components of parent in + * a grid. Each component is as big as the maximum + * preferred width and height of the components. + * The parent is made just big enough to fit them all. + * + * @param rows number of rows + * @param cols number of columns + * @param initialX x location to start the grid at + * @param initialY y location to start the grid at + * @param xPad x padding between cells + * @param yPad y padding between cells + */ + public static void makeGrid(Container parent, + int rows, int cols, + int initialX, int initialY, + int xPad, int yPad) { + SpringLayout layout; + try { + layout = (SpringLayout) parent.getLayout(); + } catch (ClassCastException exc) { + LOGGER.error("The first argument to makeGrid must use SpringLayout."); + return; + } + + Spring xPadSpring = Spring.constant(xPad); + Spring yPadSpring = Spring.constant(yPad); + Spring initialXSpring = Spring.constant(initialX); + Spring initialYSpring = Spring.constant(initialY); + int max = rows * cols; + + //Calculate Springs that are the max of the width/height so that all + //cells have the same size. + Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). + getWidth(); + Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). + getWidth(); + for (int i = 1; i < max; i++) { + SpringLayout.Constraints cons = layout.getConstraints( + parent.getComponent(i)); + + maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); + maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); + } + + //Apply the new width/height Spring. This forces all the + //components to have the same size. + for (int i = 0; i < max; i++) { + SpringLayout.Constraints cons = layout.getConstraints( + parent.getComponent(i)); + + cons.setWidth(maxWidthSpring); + cons.setHeight(maxHeightSpring); + } + + //Then adjust the x/y constraints of all the cells so that they + //are aligned in a grid. + SpringLayout.Constraints lastCons = null; + SpringLayout.Constraints lastRowCons = null; + for (int i = 0; i < max; i++) { + SpringLayout.Constraints cons = layout.getConstraints( + parent.getComponent(i)); + if (i % cols == 0) { //start of new row + lastRowCons = lastCons; + cons.setX(initialXSpring); + } else { //x position depends on previous component + cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), + xPadSpring)); + } + + if (i / cols == 0) { //first row + cons.setY(initialYSpring); + } else { //y position depends on previous row + cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), + yPadSpring)); + } + lastCons = cons; + } + + //Set the parent's size. + SpringLayout.Constraints pCons = layout.getConstraints(parent); + pCons.setConstraint(SpringLayout.SOUTH, + Spring.sum( + Spring.constant(yPad), + lastCons.getConstraint(SpringLayout.SOUTH))); + pCons.setConstraint(SpringLayout.EAST, + Spring.sum( + Spring.constant(xPad), + lastCons.getConstraint(SpringLayout.EAST))); + } + + /* Used by makeCompactGrid. */ + + private static SpringLayout.Constraints getConstraintsForCell( + int row, int col, + Container parent, + int cols) { + SpringLayout layout = (SpringLayout) parent.getLayout(); + Component c = parent.getComponent(row * cols + col); + return layout.getConstraints(c); + } + + /** + * Aligns the first rows * cols + * components of parent in + * a grid. Each component in a column is as wide as the maximum + * preferred width of the components in that column; + * height is similarly determined for each row. + * The parent is made just big enough to fit them all. + * + * @param rows number of rows + * @param cols number of columns + * @param initialX x location to start the grid at + * @param initialY y location to start the grid at + * @param xPad x padding between cells + * @param yPad y padding between cells + */ + public static void makeCompactGrid(Container parent, + int rows, int cols, + int initialX, int initialY, + int xPad, int yPad) { + SpringLayout layout; + try { + layout = (SpringLayout) parent.getLayout(); + } catch (ClassCastException exc) { + LOGGER.error("The first argument to makeCompactGrid must use SpringLayout."); + return; + } + + //Align all cells in each column and make them the same width. + Spring x = Spring.constant(initialX); + for (int c = 0; c < cols; c++) { + Spring width = Spring.constant(0); + for (int r = 0; r < rows; r++) { + width = Spring.max(width, + getConstraintsForCell(r, c, parent, cols). + getWidth()); + } + for (int r = 0; r < rows; r++) { + SpringLayout.Constraints constraints = + getConstraintsForCell(r, c, parent, cols); + constraints.setX(x); + constraints.setWidth(width); + } + x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); + } + + //Align all cells in each row and make them the same height. + Spring y = Spring.constant(initialY); + for (int r = 0; r < rows; r++) { + Spring height = Spring.constant(0); + for (int c = 0; c < cols; c++) { + height = Spring.max(height, + getConstraintsForCell(r, c, parent, cols). + getHeight()); + } + for (int c = 0; c < cols; c++) { + SpringLayout.Constraints constraints = + getConstraintsForCell(r, c, parent, cols); + constraints.setY(y); + constraints.setHeight(height); + } + y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); + } + + //Set the parent's size. + SpringLayout.Constraints pCons = layout.getConstraints(parent); + pCons.setConstraint(SpringLayout.SOUTH, y); + pCons.setConstraint(SpringLayout.EAST, x); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/injector/InjectorUpdateHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/injector/InjectorUpdateHandler.java new file mode 100644 index 0000000000..e7381b82f5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/injector/InjectorUpdateHandler.java @@ -0,0 +1,187 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.injector; + +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; +import com.romraider.logger.ecu.ui.tab.injector.InjectorTab; +import static java.lang.Math.abs; +import static java.lang.System.currentTimeMillis; +import org.apache.log4j.Logger; +import javax.swing.SwingUtilities; +import java.util.Set; + +public final class InjectorUpdateHandler implements DataUpdateHandler { + private static final Logger LOGGER = Logger.getLogger(InjectorUpdateHandler.class); + private static final String PULSE_WIDTH_16 = "E28"; + private static final String PULSE_WIDTH_32 = "E60"; + private static final String ENGINE_LOAD_16 = "E2"; + private static final String ENGINE_LOAD_32 = "E32"; + private InjectorTab injectorTab; + private double lastMafv; + private long lastUpdate; + + public synchronized void registerData(LoggerData loggerData) { + } + + public synchronized void handleDataUpdate(Response response) { + if (injectorTab.isRecordData() + && (containsData(response, PULSE_WIDTH_16, ENGINE_LOAD_16) + || containsData(response, PULSE_WIDTH_32, ENGINE_LOAD_32))) { + boolean valid = true; + + // cl/ol check + if ((containsData(response, "E3") || containsData(response, "E33"))) { + double clOl = -1; + if (containsData(response, "E3")) { + clOl = (int) findValue(response, "E3"); + LOGGER.trace("INJ:[CL/OL:E3]: " + clOl); + } + if (containsData(response, "E33")) { + clOl = (int) findValue(response, "E33"); + LOGGER.trace("INJ:[CL/OL:E33]: " + clOl); + } + valid = injectorTab.isValidClOl(clOl); + LOGGER.trace("INJ:[CL/OL]: " + valid); + } + + // afr check + if (valid && containsData(response, "P58")) { + double afr = findValue(response, "P58"); + LOGGER.trace("INJ:[AFR:P58]: " + afr); + valid = injectorTab.isValidAfr(afr); + LOGGER.trace("INJ:[AFR]: " + valid); + } + + // rpm check + if (valid && containsData(response, "P8")) { + double rpm = findValue(response, "P8"); + LOGGER.trace("INJ:[RPM:P8]: " + rpm); + valid = injectorTab.isValidRpm(rpm); + LOGGER.trace("INJ:[RPM]: " + valid); + } + + // maf check + if (valid && containsData(response, "P12")) { + double maf = findValue(response, "P12"); + LOGGER.trace("INJ:[MAF:P12]: " + maf); + valid = injectorTab.isValidMaf(maf); + LOGGER.trace("INJ:[MAF]: " + valid); + } + + // intake air temp check + if (valid && containsData(response, "P11")) { + double temp = findValue(response, "P11"); + LOGGER.trace("INJ:[IAT:P11]: " + temp); + valid = injectorTab.isValidIntakeAirTemp(temp); + LOGGER.trace("INJ:[IAT]: " + valid); + } + + // coolant temp check + if (valid && containsData(response, "P2")) { + double temp = findValue(response, "P2"); + LOGGER.trace("INJ:[CT:P2]: " + temp); + valid = injectorTab.isValidCoolantTemp(temp); + LOGGER.trace("INJ:[CT]: " + valid); + } + + // dMAFv/dt check + if (valid && containsData(response, "P18")) { + double mafv = findValue(response, "P18"); + long now = currentTimeMillis(); + double mafvChange = abs((mafv - lastMafv) / (now - lastUpdate) * 1000); + LOGGER.trace("INJ:[dMAFv/dt]: " + mafvChange); + valid = injectorTab.isValidMafvChange(mafvChange); + LOGGER.trace("INJ:[dMAFv/dt]: " + valid); + lastMafv = mafv; + lastUpdate = now; + } + + // tip-in throttle check + if (valid && (containsData(response, "E23") || containsData(response, "E54"))) { + double tipIn = -1; + if (containsData(response, "E23")) { + tipIn = findValue(response, "E23"); + LOGGER.trace("INJ:[TIP:E23]: " + tipIn); + } + if (containsData(response, "E54")) { + tipIn = findValue(response, "E54"); + LOGGER.trace("INJ:[TIP:E54]: " + tipIn); + } + valid = injectorTab.isValidTipInThrottle(tipIn); + LOGGER.trace("INJ:[TIP]: " + valid); + } + + if (valid) { + final double pulseWidth = containsData(response, PULSE_WIDTH_16) ? findValue(response, PULSE_WIDTH_16) : findValue(response, PULSE_WIDTH_32); + double load = containsData(response, ENGINE_LOAD_16) ? findValue(response, ENGINE_LOAD_16) : findValue(response, ENGINE_LOAD_32); + double stoichAfr = injectorTab.getFuelStoichAfr(); + double density = injectorTab.getFuelDensity(); + final double fuelcc = load / 2 / stoichAfr * 1000 / density; + LOGGER.trace("Injector Data: " + pulseWidth + "ms, " + fuelcc + "cc"); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + injectorTab.addData(pulseWidth, fuelcc); + } + }); + } + } + } + + private boolean containsData(Response response, String... ids) { + Set datas = response.getData(); + for (String id : ids) { + boolean found = false; + for (LoggerData data : datas) { + if (data.getId().equals(id)) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + } + + private double findValue(Response response, String id) { + for (final LoggerData loggerData : response.getData()) { + if (id.equals(loggerData.getId())) { + return response.getDataValue(loggerData); + } + } + throw new IllegalStateException("Expected data item " + id + " not in response."); + } + + public synchronized void deregisterData(LoggerData loggerData) { + } + + public synchronized void cleanUp() { + } + + public synchronized void reset() { + } + + public void setInjectorTab(InjectorTab injectorTab) { + this.injectorTab = injectorTab; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataRow.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataRow.java new file mode 100644 index 0000000000..39133df72a --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataRow.java @@ -0,0 +1,79 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.livedata; + +import com.romraider.logger.ecu.definition.LoggerData; +import static com.romraider.util.ParamChecker.checkNotNull; + +public final class LiveDataRow { + private static final double ZERO = 0.0; + private final LoggerData loggerData; + private double minValue; + private double maxValue; + private double currentValue; + private boolean updated = false; + + public LiveDataRow(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + this.loggerData = loggerData; + } + + public LoggerData getLoggerData() { + return loggerData; + } + + public String getName() { + return loggerData.getName(); + } + + public String getMinValue() { + return loggerData.getSelectedConvertor().format(minValue); + } + + public String getMaxValue() { + return loggerData.getSelectedConvertor().format(maxValue); + } + + public String getCurrentValue() { + return loggerData.getSelectedConvertor().format(currentValue); + } + + public String getUnits() { + return loggerData.getSelectedConvertor().getUnits(); + } + + public void updateValue(double value) { + currentValue = value; + if (currentValue < minValue || !updated) { + minValue = currentValue; + } + if (currentValue > maxValue || !updated) { + maxValue = currentValue; + } + updated = true; + } + + public void reset() { + minValue = ZERO; + maxValue = ZERO; + currentValue = ZERO; + updated = false; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataTableModel.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataTableModel.java new file mode 100644 index 0000000000..8a2c6baa17 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataTableModel.java @@ -0,0 +1,108 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.livedata; + +import com.romraider.logger.ecu.definition.LoggerData; +import static java.util.Collections.synchronizedList; +import static java.util.Collections.synchronizedMap; +import javax.swing.table.AbstractTableModel; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public final class LiveDataTableModel extends AbstractTableModel { + private static final long serialVersionUID = 3712433453224086342L; + private final String[] columnNames = {"Logger Data", "Min Value", "Current Value", "Max Value", "Units"}; + private final List registeredLoggerData = synchronizedList(new LinkedList()); + private final Map dataRowMap = synchronizedMap(new LinkedHashMap()); + + public synchronized int getRowCount() { + return dataRowMap.size(); + } + + public int getColumnCount() { + return columnNames.length; + } + + public String getColumnName(int col) { + return columnNames[col]; + } + + public boolean isCellEditable(int row, int col) { + return false; + } + + public synchronized Object getValueAt(int row, int col) { + LiveDataRow dataRow = dataRowMap.get(registeredLoggerData.get(row)); + switch (col) { + case 0: + return dataRow.getName(); + case 1: + return dataRow.getMinValue(); + case 2: + return dataRow.getCurrentValue(); + case 3: + return dataRow.getMaxValue(); + case 4: + return dataRow.getUnits(); + default: + return "Error!"; + } + } + + public synchronized void addParam(LoggerData loggerData) { + if (!registeredLoggerData.contains(loggerData)) { + dataRowMap.put(loggerData, new LiveDataRow(loggerData)); + registeredLoggerData.add(loggerData); + fireTableDataChanged(); + } + } + + public synchronized void removeParam(LoggerData loggerData) { + registeredLoggerData.remove(loggerData); + dataRowMap.remove(loggerData); + fireTableDataChanged(); + } + + public synchronized void updateParam(LoggerData loggerData, double value) { + LiveDataRow dataRow = dataRowMap.get(loggerData); + if (dataRow != null) { + dataRow.updateValue(value); + int index = registeredLoggerData.indexOf(loggerData); + fireTableRowsUpdated(index, index); + } + } + + public synchronized void reset() { + for (LiveDataRow liveDataRow : dataRowMap.values()) { + liveDataRow.reset(); + } + fireTableDataChanged(); + } + + public synchronized void resetRow(LoggerData loggerData) { + LiveDataRow liveDataRow = dataRowMap.get(loggerData); + if (liveDataRow != null) { + liveDataRow.reset(); + fireTableDataChanged(); + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataUpdateHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataUpdateHandler.java new file mode 100644 index 0000000000..b054b51b77 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/livedata/LiveDataUpdateHandler.java @@ -0,0 +1,65 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.livedata; + +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.definition.ConvertorUpdateListener; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; +import javax.swing.SwingUtilities; + +public final class LiveDataUpdateHandler implements DataUpdateHandler, ConvertorUpdateListener { + private final LiveDataTableModel dataTableModel; + + public LiveDataUpdateHandler(LiveDataTableModel dataTableModel) { + this.dataTableModel = dataTableModel; + } + + public synchronized void registerData(LoggerData loggerData) { + // add to datatable + dataTableModel.addParam(loggerData); + } + + public synchronized void handleDataUpdate(final Response response) { + for (final LoggerData loggerData : response.getData()) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + dataTableModel.updateParam(loggerData, response.getDataValue(loggerData)); + } + }); + } + } + + public synchronized void deregisterData(LoggerData loggerData) { + // remove from datatable + dataTableModel.removeParam(loggerData); + } + + public synchronized void cleanUp() { + } + + public synchronized void reset() { + dataTableModel.reset(); + } + + public synchronized void notifyConvertorUpdate(LoggerData updatedLoggerData) { + dataTableModel.resetRow(updatedLoggerData); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/table/TableUpdateHandler.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/table/TableUpdateHandler.java new file mode 100644 index 0000000000..f6a1498e2d --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/handler/table/TableUpdateHandler.java @@ -0,0 +1,122 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.handler.table; + +import static com.romraider.util.ParamChecker.isNullOrEmpty; +import static java.util.Collections.synchronizedMap; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; +import com.romraider.maps.Table; +import com.romraider.maps.Table2D; +import com.romraider.maps.Table3D; + +public final class TableUpdateHandler implements DataUpdateHandler { + private static final TableUpdateHandler INSTANCE = new TableUpdateHandler(); + private final Map> tableMap = synchronizedMap(new HashMap>()); + + private TableUpdateHandler() { + tableMap.clear(); + } + + @Override + public void registerData(LoggerData loggerData) { + } + + @Override + public void handleDataUpdate(Response response) { + for (LoggerData loggerData : response.getData()) { + List tables = tableMap.get(loggerData.getId()); + if (tables != null && !tables.isEmpty()) { + String formattedValue = loggerData.getSelectedConvertor().format(response.getDataValue(loggerData)); + for(ListIterator
item = tables.listIterator(); item.hasNext();) { + item.next().highlightLiveData(formattedValue); + } + } + } + } + + @Override + public void deregisterData(LoggerData loggerData) { + } + + @Override + public void cleanUp() { + } + + @Override + public void reset() { + } + + public void registerTable(Table table) { + String logParam = table.getLogParam(); + if (!isNullOrEmpty(logParam)) { + if (!tableMap.containsKey(logParam)) { + tableMap.put(logParam, new ArrayList
()); + } + tableMap.get(logParam).add(table); + } + registerAxes(table); + } + + public void deregisterTable(Table table) { + String logParam = table.getLogParam(); + if (tableMap.containsKey(logParam)) { + List
tables = tableMap.get(logParam); + tables.remove(table); + if (tables.isEmpty()) { + tableMap.remove(logParam); + } + } + deregisterAxes(table); + } + + public static TableUpdateHandler getInstance() { + return INSTANCE; + } + + private void registerAxes(Table table) { + if (table instanceof Table2D) { + registerTable(((Table2D) table).getAxis()); + } + if (table instanceof Table3D) { + registerTable(((Table3D) table).getXAxis()); + registerTable(((Table3D) table).getYAxis()); + } + } + + private void deregisterAxes(Table table) { + if (table instanceof Table2D) { + deregisterTable(((Table2D) table).getAxis()); + } + if (table instanceof Table3D) { + deregisterTable(((Table3D) table).getXAxis()); + deregisterTable(((Table3D) table).getYAxis()); + } + } + +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterListTable.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterListTable.java new file mode 100644 index 0000000000..fa80320829 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterListTable.java @@ -0,0 +1,97 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.paramlist; + +import com.romraider.logger.ecu.definition.EcuData; +import com.romraider.logger.ecu.definition.ExternalData; + +import static com.romraider.util.ParamChecker.isNullOrEmpty; +import javax.swing.JTable; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableRowSorter; + +import java.awt.event.MouseEvent; +import java.util.List; + +public final class ParameterListTable extends JTable { + private static final long serialVersionUID = -8489190548281346227L; + private UnitsComboBoxEditor comboBoxEditor = new UnitsComboBoxEditor(); + private UnitsComboBoxRenderer comboBoxRenderer = new UnitsComboBoxRenderer(); + private final ParameterListTableModel tableModel; + + public ParameterListTable(ParameterListTableModel tableModel) { + super(tableModel); + this.tableModel = tableModel; + this.getTableHeader().setReorderingAllowed(false); + for (int column = 0; column < tableModel.getColumnCount(); column++) { + if (tableModel.getColumnName(2).equalsIgnoreCase("units")) { + setColumnSortable(column, false); + } + else { + setColumnSortable(column, true); + } + } + } + + public TableCellRenderer getCellRenderer(int row, int col) { + return displayComboBox(row, col) ? comboBoxRenderer : super.getCellRenderer(row, col); + } + + public TableCellEditor getCellEditor(int row, int col) { + return displayComboBox(row, col) ? comboBoxEditor : super.getCellEditor(row, col); + } + + public String getToolTipText(MouseEvent mouseEvent) { + List parameterRows = tableModel.getParameterRows(); + if (!isNullOrEmpty(parameterRows)) { + ParameterRow parameterRow = parameterRows.get(rowAtPoint(mouseEvent.getPoint())); + if (parameterRow != null) { + String description = parameterRow.getLoggerData().getDescription(); + if (!isNullOrEmpty(description)) { + return description; + } + } + } + return super.getToolTipText(mouseEvent); + } + + private boolean displayComboBox(int row, int col) { + Object value = getValueAt(row, col); + if (EcuData.class.isAssignableFrom(value.getClass())) { + EcuData ecuData = (EcuData) value; + if (ecuData.getConvertors().length > 1) + return true; + } + if (ExternalData.class.isAssignableFrom(value.getClass())) { + ExternalData externalData = (ExternalData) value; + if (externalData.getConvertors().length > 1) + return true; + } + return false; + } + + private void setColumnSortable(int column, boolean state) { + TableRowSorter sorter = + new TableRowSorter(tableModel); + sorter.setSortable(column, state); + setRowSorter(sorter); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterListTableModel.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterListTableModel.java new file mode 100644 index 0000000000..f62ae4e06b --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterListTableModel.java @@ -0,0 +1,127 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.paramlist; + +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.DataRegistrationBroker; +import static java.util.Collections.synchronizedList; +import static java.util.Collections.synchronizedMap; +import javax.swing.table.AbstractTableModel; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public final class ParameterListTableModel extends AbstractTableModel { + private static final long serialVersionUID = -2556400867696538881L; + private final String[] columnNames; + private final List registeredLoggerData = synchronizedList(new LinkedList()); + private final Map paramRowMap = synchronizedMap(new LinkedHashMap()); + private final DataRegistrationBroker broker; + + public ParameterListTableModel(DataRegistrationBroker broker, String dataType) { + this.broker = broker; + columnNames = new String[]{"Selected?", dataType, "Units"}; + } + + public synchronized int getRowCount() { + return paramRowMap.size(); + } + + public int getColumnCount() { + return columnNames.length; + } + + public String getColumnName(int col) { + return columnNames[col]; + } + + public boolean isCellEditable(int row, int col) { + return col == 0 || col == 2; + } + + public synchronized Object getValueAt(int row, int col) { + ParameterRow paramRow = paramRowMap.get(registeredLoggerData.get(row)); + switch (col) { + case 0: + return paramRow.isSelected(); + case 1: + return paramRow.getLoggerData().getName(); + case 2: + LoggerData loggerData = paramRow.getLoggerData(); + return loggerData.getConvertors().length > 1 ? loggerData : loggerData.getSelectedConvertor().getUnits(); + default: + return "Error!"; + } + } + + public synchronized void setValueAt(Object value, int row, int col) { + ParameterRow paramRow = paramRowMap.get(registeredLoggerData.get(row)); + if (col == 0 && paramRow != null) { + Boolean selected = (Boolean) value; + setSelected(paramRow, selected); + fireTableRowsUpdated(row, row); + } + } + + public Class getColumnClass(int col) { + return getValueAt(0, col).getClass(); + } + + public synchronized void addParam(LoggerData loggerData, boolean selected) { + if (!registeredLoggerData.contains(loggerData)) { + ParameterRow paramRow = new ParameterRow(loggerData); + paramRowMap.put(loggerData, paramRow); + registeredLoggerData.add(loggerData); + setSelected(paramRow, selected); + fireTableDataChanged(); + } + } + + public synchronized void selectParam(LoggerData loggerData, boolean selected) { + if (registeredLoggerData.contains(loggerData)) { + setSelected(paramRowMap.get(loggerData), selected); + fireTableDataChanged(); + } + } + + public synchronized void clear() { + broker.clear(); + paramRowMap.clear(); + registeredLoggerData.clear(); + try { + fireTableDataChanged(); + } + catch (Exception e) { + // Swallow complaints from TableRowSorter when the table is empty + } + } + + public List getParameterRows() { + return new ArrayList(paramRowMap.values()); + } + + private void setSelected(ParameterRow paramRow, boolean selected) { + paramRow.setSelected(selected); + if (selected) broker.registerLoggerDataForLogging(paramRow.getLoggerData()); + else broker.deregisterLoggerDataFromLogging(paramRow.getLoggerData()); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterRow.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterRow.java new file mode 100644 index 0000000000..de17affd3e --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/ParameterRow.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.paramlist; + +import com.romraider.logger.ecu.definition.LoggerData; +import static com.romraider.util.ParamChecker.checkNotNull; + +public final class ParameterRow { + private final LoggerData loggerData; + private boolean selected = false; + + public ParameterRow(LoggerData loggerData) { + checkNotNull(loggerData, "loggerData"); + this.loggerData = loggerData; + } + + public LoggerData getLoggerData() { + return loggerData; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + loggerData.setSelected(selected); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/UnitsComboBoxEditor.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/UnitsComboBoxEditor.java new file mode 100644 index 0000000000..18d9f25d6c --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/UnitsComboBoxEditor.java @@ -0,0 +1,67 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.paramlist; + +import com.romraider.logger.ecu.definition.EcuDataConvertor; +import com.romraider.logger.ecu.definition.LoggerData; + +import javax.swing.AbstractCellEditor; +import javax.swing.JComboBox; +import javax.swing.JTable; +import javax.swing.table.TableCellEditor; +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public final class UnitsComboBoxEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { + private static final long serialVersionUID = -3472910399604360821L; + private static final String EDIT_COMMAND = "EDIT"; + private LoggerData currentEcuData; + + public Object getCellEditorValue() { + return currentEcuData.getSelectedConvertor(); + } + + public Component getTableCellEditorComponent(JTable table, Object ecuData, boolean isSelected, int row, int column) { + currentEcuData = (LoggerData) ecuData; + EcuDataConvertor[] convertors = currentEcuData.getConvertors(); + JComboBox comboBox = new JComboBox(); + for (EcuDataConvertor convertor : convertors) { + comboBox.addItem(convertor); + } + comboBox.setSelectedItem(currentEcuData.getSelectedConvertor()); + comboBox.setEditable(false); + comboBox.setEnabled(true); + comboBox.setActionCommand(EDIT_COMMAND); + comboBox.addActionListener(this); + return comboBox; + } + + public void actionPerformed(ActionEvent actionEvent) { + if (EDIT_COMMAND.equals(actionEvent.getActionCommand())) { + Object source = actionEvent.getSource(); + if (source != null && JComboBox.class.isAssignableFrom(source.getClass())) { + JComboBox comboBox = (JComboBox) source; + currentEcuData.selectConvertor((EcuDataConvertor) comboBox.getSelectedItem()); + fireEditingStopped(); + } + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/UnitsComboBoxRenderer.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/UnitsComboBoxRenderer.java new file mode 100644 index 0000000000..b77f778588 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/paramlist/UnitsComboBoxRenderer.java @@ -0,0 +1,44 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.paramlist; + +import com.romraider.logger.ecu.definition.EcuDataConvertor; +import com.romraider.logger.ecu.definition.LoggerData; + +import javax.swing.JComboBox; +import javax.swing.JTable; +import javax.swing.table.TableCellRenderer; +import java.awt.Component; + +public final class UnitsComboBoxRenderer extends JComboBox implements TableCellRenderer { + + private static final long serialVersionUID = -6288079743431509778L; + + public Component getTableCellRendererComponent(JTable table, Object ecuData, boolean isSelected, boolean hasFocus, int row, int column) { + LoggerData currentEcuData = (LoggerData) ecuData; + EcuDataConvertor[] convertors = currentEcuData.getConvertors(); + JComboBox comboBox = new JComboBox(); + for (EcuDataConvertor convertor : convertors) { + comboBox.addItem(convertor); + } + comboBox.setSelectedItem(currentEcuData.getSelectedConvertor()); + return comboBox; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/playback/PlaybackManager.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/playback/PlaybackManager.java new file mode 100644 index 0000000000..f1f84ed17e --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/playback/PlaybackManager.java @@ -0,0 +1,38 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.playback; + +import java.io.File; + +public interface PlaybackManager { + void load(File file); + + void play(); + + void play(int speed); + + void step(int increment); + + void pause(); + + void stop(); + + void reset(); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/playback/PlaybackManagerImpl.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/playback/PlaybackManagerImpl.java new file mode 100644 index 0000000000..8f5a2b2e06 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/playback/PlaybackManagerImpl.java @@ -0,0 +1,83 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.playback; + +import com.romraider.logger.ecu.comms.query.Response; +import com.romraider.logger.ecu.comms.query.ResponseImpl; +import com.romraider.logger.ecu.definition.LoggerData; +import com.romraider.logger.ecu.ui.handler.DataUpdateHandler; +import static com.romraider.util.ThreadUtil.sleep; +import java.io.File; +import java.util.List; + +//TODO: Finish me. +public final class PlaybackManagerImpl implements PlaybackManager { + private final List loggerDatas; + private final DataUpdateHandler[] dataUpdateHandlers; + + public PlaybackManagerImpl(List loggerDatas, DataUpdateHandler... dataUpdateHandlers) { + this.loggerDatas = loggerDatas; + this.dataUpdateHandlers = dataUpdateHandlers; + } + + public void load(File file) { + // TODO: Finish me! + for (DataUpdateHandler handler : dataUpdateHandlers) { + handler.registerData(loggerDatas.get(10)); + handler.registerData(loggerDatas.get(20)); + handler.registerData(loggerDatas.get(30)); + } + } + + public void play() { + double d = 0.0; + while (true) { + for (DataUpdateHandler handler : dataUpdateHandlers) { + Response response = new ResponseImpl(); + response.setDataValue(loggerDatas.get(10), d); + response.setDataValue(loggerDatas.get(20), d); + response.setDataValue(loggerDatas.get(30), d); + handler.handleDataUpdate(response); + d += 100.0; + } + sleep(100L); + } + } + + public void play(int speed) { + throw new UnsupportedOperationException(); + } + + public void step(int increment) { + throw new UnsupportedOperationException(); + } + + public void pause() { + throw new UnsupportedOperationException(); + } + + public void stop() { + throw new UnsupportedOperationException(); + } + + public void reset() { + throw new UnsupportedOperationException(); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/layout/BetterFlowLayout.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/layout/BetterFlowLayout.java new file mode 100644 index 0000000000..12ac7ab87b --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/layout/BetterFlowLayout.java @@ -0,0 +1,79 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.layout; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Insets; + +public final class BetterFlowLayout extends FlowLayout { + private static final long serialVersionUID = -6784712723817241270L; + + public BetterFlowLayout() { + super(); + } + + public BetterFlowLayout(int align) { + super(align); + } + + public BetterFlowLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } + + @Override + public Dimension preferredLayoutSize(Container target) { + return betterPreferredSize(target); + } + + @Override + public Dimension minimumLayoutSize(Container target) { + return betterPreferredSize(target); + } + + public Dimension betterPreferredSize(Container target) { + synchronized (target.getTreeLock()) { + Insets insets = target.getInsets(); + int maxwidth = target.getWidth() - (insets.left + insets.right + getHgap() * 2); + int nmembers = target.getComponentCount(); + int x = 0, y = insets.top + getVgap(); + int rowh = 0; + for (int i = 0; i < nmembers; i++) { + Component m = target.getComponent(i); + if (m.isVisible()) { + Dimension d = m.getPreferredSize(); + m.setSize(d.width, d.height); + if ((x == 0) || ((x + d.width) <= maxwidth)) { + if (x > 0) x += getHgap(); + x += d.width; + rowh = Math.max(rowh, d.height); + } else { + x = d.width; + y += getVgap() + rowh; + rowh = d.height; + } + } + } + return new Dimension(maxwidth, y + rowh + getVgap()); + } + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/menubar/util/FileHelper.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/menubar/util/FileHelper.java new file mode 100644 index 0000000000..8ae0f2c552 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/menubar/util/FileHelper.java @@ -0,0 +1,91 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.menubar.util; + +import com.romraider.logger.ecu.profile.UserProfile; +import com.romraider.swing.GenericFileFilter; +import static com.romraider.util.ParamChecker.isNullOrEmpty; +import static javax.swing.JFileChooser.DIRECTORIES_ONLY; +import javax.swing.JFileChooser; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +public final class FileHelper { + private static final String USER_HOME_DIR = System.getProperty("user.home"); + + private FileHelper() { + throw new UnsupportedOperationException(); + } + + public static File getFile(String filePath) { + return isNullOrEmpty(filePath) ? new File(USER_HOME_DIR) : new File(filePath); + } + + public static JFileChooser getProfileFileChooser(File lastProfileFile) { + return getFileChooser(lastProfileFile, "ECU Logger User Profiles", "xml"); + } + + public static JFileChooser getDefinitionFileChooser(File lastDefFile) { + return getFileChooser(lastDefFile, "ECU Logger Definitions", "xml"); + } + + public static String saveProfileToFile(UserProfile profile, File destinationFile) throws IOException { + String profileFilePath = destinationFile.getAbsolutePath(); + if (!profileFilePath.endsWith(".xml")) { + profileFilePath += ".xml"; + destinationFile = new File(profileFilePath); + } + FileOutputStream fos = new FileOutputStream(destinationFile); + try { + fos.write(profile.getBytes()); + } finally { + fos.close(); + } + return profileFilePath; + } + + public static JFileChooser getLoggerOutputDirFileChooser(File lastLoggerOutputDir) { + JFileChooser fc; + if (lastLoggerOutputDir.exists() && lastLoggerOutputDir.isDirectory()) { + fc = new JFileChooser(lastLoggerOutputDir.getAbsolutePath()); + } else { + fc = new JFileChooser(); + } + fc.setFileSelectionMode(DIRECTORIES_ONLY); + return fc; + } + + private static JFileChooser getFileChooser(File file, String description, String... extensions) { + JFileChooser fc = getFileChooser(file); + fc.setFileFilter(new GenericFileFilter(description, extensions)); + return fc; + } + + private static JFileChooser getFileChooser(File file) { + if (file.exists() && file.isFile() && file.getParentFile() != null) { + String dir = file.getParentFile().getAbsolutePath(); + JFileChooser fc = new JFileChooser(dir); + fc.setSelectedFile(file); + return fc; + } + return new JFileChooser(); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/AirFuelLearningTableModel.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/AirFuelLearningTableModel.java new file mode 100644 index 0000000000..c3ac2f59ff --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/AirFuelLearningTableModel.java @@ -0,0 +1,79 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.tools.tablemodels; + +import java.util.List; + +import javax.swing.table.DefaultTableModel; + +/** + * Air/Fuel Learning Table Model for Learning Table Values display. Note + * that column 0 is used as a row header. + */ +public final class AirFuelLearningTableModel extends DefaultTableModel { + private static final long serialVersionUID = 8643509881981835534L; + private List> afLearning; + private String[] columnNames = new String[]{" ","A","B","C","D"}; + + @Override + public final int getColumnCount() { + return columnNames.length; + } + + @Override + public final String getColumnName(int column) { + return columnNames[column]; + } + + @Override + public final Object getValueAt(int row, int column) { + if (afLearning != null) { + return afLearning.get(row).get(column); + } + else { + return null; + } + } + + @Override + public final int getRowCount() { + return (afLearning != null) ? afLearning.size() : 0; + } + + @Override + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + @Override + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setColumnHeadings(String[] afRanges) { + if (afRanges.length > 0) { + this.columnNames = afRanges; + } + } + + public final void setAfLearningInfo(List> afLearning) { + this.afLearning = afLearning; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/FineLearningKnockCorrectionTableModel.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/FineLearningKnockCorrectionTableModel.java new file mode 100644 index 0000000000..ed32799f3c --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/FineLearningKnockCorrectionTableModel.java @@ -0,0 +1,92 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.tools.tablemodels; + +import java.util.List; + +import javax.swing.table.DefaultTableModel; + +import com.romraider.logger.ecu.comms.query.EcuQuery; + +/** + * Fine Learning Knock Correction Table Model for Learning Table Values display. + * Note that column 0 is used as a row header + */ +public final class FineLearningKnockCorrectionTableModel extends DefaultTableModel { + private static final long serialVersionUID = -7369506358159217982L; + private List> flkc; + private String[] columnNames = new String[]{" ","A","B","C","D","E"}; + private String[] rowNames = new String[]{"1","2","3","4","5","6","7","8"}; + + @Override + public final int getColumnCount() { + return columnNames.length; + } + + @Override + public final String getColumnName(int column) { + return columnNames[column]; + } + + /** + * Column 0 is used as a row header + */ + @Override + public final Object getValueAt(int row, int column) { + Object result = null; + if (flkc != null) { + result = (column == 0) + ? result = rowNames[row] + : flkc.get(row).get(column).getResponse(); + } + return result; + } + + @Override + public final int getRowCount() { + return (flkc != null) ? flkc.size() : 0; + } + + @Override + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + @Override + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setColumnHeadings(String[] loadRanges) { + if (loadRanges.length > 0) { + this.columnNames = loadRanges; + } + } + + public final void setRomHeadings(String[] rpmRanges) { + if (rpmRanges.length > 0) { + this.rowNames = rpmRanges; + } + } + + public final void setFlkcData(List> flkc) { + this.flkc = flkc; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/ReadCodesTableModel.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/ReadCodesTableModel.java new file mode 100644 index 0000000000..14018a1445 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/ReadCodesTableModel.java @@ -0,0 +1,83 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.tools.tablemodels; + +import java.util.ArrayList; + +import javax.swing.table.DefaultTableModel; + +import com.romraider.logger.ecu.comms.query.EcuQuery; + +public final class ReadCodesTableModel extends DefaultTableModel { + private static final long serialVersionUID = -4229633011594395331L; + private ArrayList dtcSet; + + public final int getColumnCount() { + return 3; + } + + public final String getColumnName(int column) { + switch (column) { + case 0: return "Diagnostic Code Name"; + case 1: return "Temporary"; + case 2: return "Memorized"; + default: return ""; + } + } + + public final Object getValueAt(int row, int column) { + if (dtcSet != null) { + final double result = dtcSet.get(row).getResponse(); + switch (column) { + case 0: + return " " + dtcSet.get(row).getLoggerData().getName(); + case 1: + return (result == 1 || result == 3) + ? new Boolean(true) + : new Boolean(false); + case 2: + return (result == 2 || result == 3) + ? new Boolean(true) + : new Boolean(false); + default: + return null; + } + } + else { + return null; + } + } + + public final int getRowCount() { + return (dtcSet != null) ? dtcSet.size() : 0; + } + + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setDtcList(ArrayList dtcSet) { + this.dtcSet = dtcSet; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/VehicleInformationTableModel.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/VehicleInformationTableModel.java new file mode 100644 index 0000000000..328607831d --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/VehicleInformationTableModel.java @@ -0,0 +1,68 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.tools.tablemodels; + +import java.util.Map; + +import javax.swing.table.DefaultTableModel; + +public final class VehicleInformationTableModel extends DefaultTableModel { + private static final long serialVersionUID = 9214968582253321667L; + private Map vehicleInfo; + + @Override + public final int getColumnCount() { + return vehicleInfo.keySet().size(); + } + + @Override + public final String getColumnName(int column) { + return (String) vehicleInfo.keySet().toArray()[column]; + } + + @Override + public final Object getValueAt(int row, int column) { + if (vehicleInfo != null) { + return vehicleInfo.get(getColumnName(column)); + } + else { + return null; + } + } + + @Override + public final int getRowCount() { + return (vehicleInfo != null) ? 1 : 0; + } + + @Override + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + @Override + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setVehicleInfo(Map vehicleInfo) { + this.vehicleInfo = vehicleInfo; + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/renderers/CentreRenderer.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/renderers/CentreRenderer.java new file mode 100644 index 0000000000..56dcf58f6e --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/renderers/CentreRenderer.java @@ -0,0 +1,50 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.tools.tablemodels.renderers; + +import java.awt.Component; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableCellRenderer; + +public class CentreRenderer implements TableCellRenderer { + private DefaultTableCellRenderer renderer; + + /** + * This class is used to centre align text for the given table. + * @param table - table to have centre aligned values + */ + public CentreRenderer(JTable table) { + renderer = (DefaultTableCellRenderer) + table.getTableHeader().getDefaultRenderer(); + renderer.setHorizontalAlignment(JLabel.CENTER); + } + + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, + boolean hasFocus, int row, int col) { + + return renderer.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, col); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/renderers/LtvCellRenderer.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/renderers/LtvCellRenderer.java new file mode 100644 index 0000000000..038d8dadb2 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/tools/tablemodels/renderers/LtvCellRenderer.java @@ -0,0 +1,89 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.tools.tablemodels.renderers; + +import java.awt.Color; +import java.awt.Component; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.ParseException; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; + +/** + * This class is used to set the Default Table Cell Renderer for String and + * Double object types. The cell will be centred and text coloured according + * to its value above and below zero. + */ + +public class LtvCellRenderer extends DefaultTableCellRenderer { + private static final long serialVersionUID = -171010635742251272L; + private static final DecimalFormat numberFormat = + new DecimalFormat("0.00;-0.00"); + + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, + int row, int column) { + + final Component c = super.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); + + if (c instanceof JLabel) { + final JLabel cell = (JLabel) c; + cell.setHorizontalAlignment(JLabel.CENTER); + cell.setForeground(Color.BLACK); + + if (column > 0) { + if (value instanceof Double) { + cell.setText(numberFormat.format(value)); + setColour(cell, ((Double) value).doubleValue()); + + } + if (value instanceof String) { + final String data = (String) value; + if (data.contains("%")) { + final String numText = data.split(" ")[0]; + double num; + try { + num = NumberFormat.getNumberInstance() + .parse(numText).doubleValue(); + setColour(cell, num); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + } + } + } + return c; + } + + private final void setColour(JLabel cell, double value) { + if (value < 0) { + cell.setForeground(Color.RED); + } + else if (value > 0) { + cell.setForeground(Color.BLUE); + } + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/vertical/VerticalLabelUI.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/vertical/VerticalLabelUI.java new file mode 100644 index 0000000000..3438aa915b --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/vertical/VerticalLabelUI.java @@ -0,0 +1,99 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.vertical; + +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.plaf.basic.BasicLabelUI; +import java.awt.Dimension; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.geom.AffineTransform; + +public final class VerticalLabelUI extends BasicLabelUI { + private static Rectangle PAINT_ICON_R = new Rectangle(); + private static Rectangle PAINT_TEXT_R = new Rectangle(); + private static Rectangle PAINT_VIEW_R = new Rectangle(); + private static Insets PAINT_VIEW_INSETS = new Insets(0, 0, 0, 0); + protected boolean clockwise; + + static { + labelUI = new VerticalLabelUI(false); + } + + public VerticalLabelUI(boolean clockwise) { + super(); + this.clockwise = clockwise; + } + + public Dimension getPreferredSize(JComponent c) { + Dimension dim = super.getPreferredSize(c); + return new Dimension(dim.height, dim.width); + } + + public void paint(Graphics graphics, JComponent component) { + JLabel label = (JLabel) component; + String text = label.getText(); + Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); + + if ((icon == null) && (text == null)) return; + + FontMetrics fm = graphics.getFontMetrics(); + PAINT_VIEW_INSETS = component.getInsets(PAINT_VIEW_INSETS); + PAINT_VIEW_R.x = PAINT_VIEW_INSETS.left; + PAINT_VIEW_R.y = PAINT_VIEW_INSETS.top; + + // Use inverted height & width + PAINT_VIEW_R.height = component.getWidth() - (PAINT_VIEW_INSETS.left + PAINT_VIEW_INSETS.right); + PAINT_VIEW_R.width = component.getHeight() - (PAINT_VIEW_INSETS.top + PAINT_VIEW_INSETS.bottom); + + PAINT_ICON_R.x = PAINT_ICON_R.y = PAINT_ICON_R.width = PAINT_ICON_R.height = 0; + PAINT_TEXT_R.x = PAINT_TEXT_R.y = PAINT_TEXT_R.width = PAINT_TEXT_R.height = 0; + + String clippedText = layoutCL(label, fm, text, icon, PAINT_VIEW_R, PAINT_ICON_R, PAINT_TEXT_R); + int textWidth = fm.stringWidth(clippedText); + + Graphics2D g2 = (Graphics2D) graphics; + AffineTransform tr = g2.getTransform(); + if (clockwise) { + g2.rotate(Math.PI / 2); + g2.translate(component.getHeight() / 2 - textWidth / 2, -component.getWidth()); + } else { + g2.rotate(-Math.PI / 2); + g2.translate(-component.getHeight() / 2 - textWidth / 2, 0); + } + + if (icon != null) icon.paintIcon(component, graphics, PAINT_ICON_R.x, PAINT_ICON_R.y); + + if (text != null) { + int textX = PAINT_TEXT_R.x; + int textY = PAINT_TEXT_R.y + fm.getAscent(); + + if (label.isEnabled()) paintEnabledText(label, graphics, clippedText, textX, textY); + else paintDisabledText(label, graphics, clippedText, textX, textY); + } + + g2.setTransform(tr); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/vertical/VerticalTextIcon.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/vertical/VerticalTextIcon.java new file mode 100644 index 0000000000..ccd693b039 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/swing/vertical/VerticalTextIcon.java @@ -0,0 +1,316 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.swing.vertical; + +import javax.swing.Icon; +import java.awt.Component; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +/** + * VTextIcon is an Icon implementation which draws a short string vertically. + * It's useful for JTabbedPanes with LEFT or RIGHT tabs but can be used in any + * component which supports Icons, such as JLabel or JButton + * You can provide a hint to indicate whether to rotate the string + * to the left or right, or not at all, and it checks to make sure + * that the rotation is legal for the given string + * (for example, Chinese/Japanese/Korean scripts have special rules when + * drawn vertically and should never be rotated) + */ +public final class VerticalTextIcon implements Icon, PropertyChangeListener { + String fLabel; + String[] fCharStrings; // for efficiency, break the fLabel into one-char strings to be passed to drawString + int[] fCharWidths; // Roman characters should be centered when not rotated (Japanese fonts are monospaced) + int[] fPosition; // Japanese half-height characters need to be shifted when drawn vertically + int fWidth, fHeight, fCharHeight, fDescent; // Cached for speed + int fRotation; + Component fComponent; + + static final int POSITION_NORMAL = 0; + static final int POSITION_TOP_RIGHT = 1; + static final int POSITION_FAR_TOP_RIGHT = 2; + + public static final int ROTATE_DEFAULT = 0x00; + public static final int ROTATE_NONE = 0x01; + public static final int ROTATE_LEFT = 0x02; + public static final int ROTATE_RIGHT = 0x04; + + /** + * Creates a VTextIcon for the specified component + * with the specified label. + * It sets the orientation to the default for the string + * + * @see #verifyRotation + */ + public VerticalTextIcon(Component component, String label) { + this(component, label, ROTATE_DEFAULT); + } + + /** + * Creates a VTextIcon for the specified component + * with the specified label. + * It sets the orientation to the provided value if it's legal for the string + * + * @see #verifyRotation + */ + public VerticalTextIcon(Component component, String label, int rotateHint) { + fComponent = component; + fLabel = label; + fRotation = verifyRotation(label, rotateHint); + calcDimensions(); + fComponent.addPropertyChangeListener(this); + } + + /** + * sets the label to the given string, updating the orientation as needed + * and invalidating the layout if the size changes + * + * @see #verifyRotation + */ + public void setLabel(String label) { + fLabel = label; + fRotation = verifyRotation(label, fRotation); // Make sure the current rotation is still legal + recalcDimensions(); + } + + /** + * Checks for changes to the font on the fComponent + * so that it can invalidate the layout if the size changes + */ + public void propertyChange(PropertyChangeEvent e) { + String prop = e.getPropertyName(); + if ("font".equals(prop)) { + recalcDimensions(); + } + } + + /** + * Calculates the dimensions. If they've changed, + * invalidates the component + */ + void recalcDimensions() { + int wOld = getIconWidth(); + int hOld = getIconHeight(); + calcDimensions(); + if (wOld != getIconWidth() || hOld != getIconHeight()) + fComponent.invalidate(); + } + + void calcDimensions() { + FontMetrics fm = fComponent.getFontMetrics(fComponent.getFont()); + fCharHeight = fm.getAscent() + fm.getDescent(); + fDescent = fm.getDescent(); + if (fRotation == ROTATE_NONE) { + int len = fLabel.length(); + char data[] = new char[len]; + fLabel.getChars(0, len, data, 0); + // if not rotated, width is that of the widest char in the string + fWidth = 0; + // we need an array of one-char strings for drawString + fCharStrings = new String[len]; + fCharWidths = new int[len]; + fPosition = new int[len]; + char ch; + for (int i = 0; i < len; i++) { + ch = data[i]; + fCharWidths[i] = fm.charWidth(ch); + if (fCharWidths[i] > fWidth) + fWidth = fCharWidths[i]; + fCharStrings[i] = new String(data, i, 1); + // small kana and punctuation + if (sDrawsInTopRight.indexOf(ch) >= 0) // if ch is in sDrawsInTopRight + fPosition[i] = POSITION_TOP_RIGHT; + else if (sDrawsInFarTopRight.indexOf(ch) >= 0) + fPosition[i] = POSITION_FAR_TOP_RIGHT; + else + fPosition[i] = POSITION_NORMAL; + } + // and height is the font height * the char count, + one extra leading at the bottom + fHeight = fCharHeight * len + fDescent; + } else { + // if rotated, width is the height of the string + fWidth = fCharHeight; + // and height is the width, plus some buffer space + fHeight = fm.stringWidth(fLabel) + 2 * kBufferSpace; + } + } + + /** + * Draw the icon at the specified location. Icon implementations + * may use the Component argument to get properties useful for + * painting, e.g. the foreground or background color. + */ + public void paintIcon(Component c, Graphics g, int x, int y) { + // We don't insist that it be on the same Component + g.setColor(c.getForeground()); + g.setFont(c.getFont()); + if (fRotation == ROTATE_NONE) { + int yPos = y + fCharHeight; + for (int i = 0; i < fCharStrings.length; i++) { + // Special rules for Japanese - "half-height" characters (like ya, yu, yo in combinations) + // should draw in the top-right quadrant when drawn vertically + // - they draw in the bottom-left normally + int tweak; + switch (fPosition[i]) { + case POSITION_NORMAL: + // Roman fonts should be centered. Japanese fonts are always monospaced. + g.drawString(fCharStrings[i], x + ((fWidth - fCharWidths[i]) / 2), yPos); + break; + case POSITION_TOP_RIGHT: + tweak = fCharHeight / 3; // Should be 2, but they aren't actually half-height + g.drawString(fCharStrings[i], x + (tweak / 2), yPos - tweak); + break; + case POSITION_FAR_TOP_RIGHT: + tweak = fCharHeight - fCharHeight / 3; + g.drawString(fCharStrings[i], x + (tweak / 2), yPos - tweak); + break; + } + yPos += fCharHeight; + } + } else if (fRotation == ROTATE_LEFT) { + g.translate(x + fWidth, y + fHeight); + ((Graphics2D) g).rotate(-NINETY_DEGREES); + g.drawString(fLabel, kBufferSpace, -fDescent); + ((Graphics2D) g).rotate(NINETY_DEGREES); + g.translate(-(x + fWidth), -(y + fHeight)); + } else if (fRotation == ROTATE_RIGHT) { + g.translate(x, y); + ((Graphics2D) g).rotate(NINETY_DEGREES); + g.drawString(fLabel, kBufferSpace, -fDescent); + ((Graphics2D) g).rotate(-NINETY_DEGREES); + g.translate(-x, -y); + } + } + + /** + * Returns the icon's width. + * + * @return an int specifying the fixed width of the icon. + */ + public int getIconWidth() { + return fWidth; + } + + /** + * Returns the icon's height. + * + * @return an int specifying the fixed height of the icon. + */ + public int getIconHeight() { + return fHeight; + } + + /** + * verifyRotation + *

+ * returns the best rotation for the string (ROTATE_NONE, ROTATE_LEFT, ROTATE_RIGHT) + *

+ * This is public static so you can use it to test a string without creating a VTextIcon + *

+ * from http://www.unicode.org/unicode/reports/tr9/tr9-3.html + * When setting text using the Arabic script in vertical lines, + * it is more common to employ a horizontal baseline that + * is rotated by 90� counterclockwise so that the characters + * are ordered from top to bottom. Latin text and numbers + * may be rotated 90� clockwise so that the characters + * are also ordered from top to bottom. + *

+ * Rotation rules + * - Roman can rotate left, right, or none - default right (counterclockwise) + * - CJK can't rotate + * - Arabic must rotate - default left (clockwise) + *

+ * from the online edition of _The Unicode Standard, Version 3.0_, file ch10.pdf page 4 + * Ideographs are found in three blocks of the Unicode Standard... + * U+4E00-U+9FFF, U+3400-U+4DFF, U+F900-U+FAFF + *

+ * Hiragana is U+3040-U+309F, katakana is U+30A0-U+30FF + *

+ * from http://www.unicode.org/unicode/faq/writingdirections.html + * East Asian scripts are frequently written in vertical lines + * which run from top-to-bottom and are arrange columns either + * from left-to-right (Mongolian) or right-to-left (other scripts). + * Most characters use the same shape and orientation when displayed + * horizontally or vertically, but many punctuation characters + * will change their shape when displayed vertically. + *

+ * Letters and words from other scripts are generally rotated through + * ninety degree angles so that they, too, will read from top to bottom. + * That is, letters from left-to-right scripts will be rotated clockwise + * and letters from right-to-left scripts counterclockwise, both + * through ninety degree angles. + *

+ * Unlike the bidirectional case, the choice of vertical layout + * is usually treated as a formatting style; therefore, + * the Unicode Standard does not define default rendering behavior + * for vertical text nor provide directionality controls designed to override such behavior + */ + public static int verifyRotation(String label, int rotateHint) { + boolean hasCJK = false; + boolean hasMustRotate = false; // Arabic, etc + + int len = label.length(); + char data[] = new char[len]; + char ch; + label.getChars(0, len, data, 0); + for (int i = 0; i < len; i++) { + ch = data[i]; + if ((ch >= '\u4E00' && ch <= '\u9FFF') || + (ch >= '\u3400' && ch <= '\u4DFF') || + (ch >= '\uF900' && ch <= '\uFAFF') || + (ch >= '\u3040' && ch <= '\u309F') || + (ch >= '\u30A0' && ch <= '\u30FF')) + hasCJK = true; + if ((ch >= '\u0590' && ch <= '\u05FF') || // Hebrew + (ch >= '\u0600' && ch <= '\u06FF') || // Arabic + (ch >= '\u0700' && ch <= '\u074F')) // Syriac + hasMustRotate = true; + } + // If you mix Arabic with Chinese, you're on your own + if (hasCJK) + return DEFAULT_CJK; + + int legal = hasMustRotate ? LEGAL_MUST_ROTATE : LEGAL_ROMAN; + if ((rotateHint & legal) > 0) + return rotateHint; + + // The hint wasn't legal, or it was zero + return hasMustRotate ? DEFAULT_MUST_ROTATE : DEFAULT_ROMAN; + } + + // The small kana characters and Japanese punctuation that draw in the top right quadrant: + // small a, i, u, e, o, tsu, ya, yu, yo, wa (katakana only) ka ke + static final String sDrawsInTopRight = + "\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308E" + // hiragana + "\u30A1\u30A3\u30A5\u30A7\u30A9\u30C3\u30E3\u30E5\u30E7\u30EE\u30F5\u30F6"; // katakana + static final String sDrawsInFarTopRight = "\u3001\u3002"; // comma, full stop + + static final int DEFAULT_CJK = ROTATE_NONE; + static final int LEGAL_ROMAN = ROTATE_NONE | ROTATE_LEFT | ROTATE_RIGHT; + static final int DEFAULT_ROMAN = ROTATE_RIGHT; + static final int LEGAL_MUST_ROTATE = ROTATE_LEFT | ROTATE_RIGHT; + static final int DEFAULT_MUST_ROTATE = ROTATE_LEFT; + + static final double NINETY_DEGREES = Math.toRadians(90.0); + static final int kBufferSpace = 5; +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/Tab.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/Tab.java new file mode 100644 index 0000000000..577650ed1c --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/Tab.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.tab; + +import com.romraider.logger.ecu.definition.EcuParameter; +import com.romraider.logger.ecu.definition.EcuSwitch; +import com.romraider.logger.ecu.definition.ExternalData; +import javax.swing.JPanel; +import java.util.List; + +/** + * Interface for Logger tabs that have the following: + *

+ * Control panel where logging information and constraints are set + * ChartPanel where graph of data is displayed + */ +public interface Tab { + JPanel getPanel(); + + boolean isRecordData(); + + void addData(double xData, double yData); + + void setEcuParams(List params); + + void setEcuSwitches(List switches); + + void setExternalDatas(List external); +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/TableFinder.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/TableFinder.java new file mode 100644 index 0000000000..96467f4549 --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/TableFinder.java @@ -0,0 +1,33 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.tab; + +import com.romraider.maps.Rom; +import com.romraider.maps.Table; +import java.util.List; + +public final class TableFinder { + public static Table findTableStartsWith(Rom rom, String name) { + List

tables = rom.findTables("^" + name + ".*$"); + if (tables.isEmpty()) throw new IllegalStateException("No table found for name: \"" + name + "\""); + if (tables.size() > 1) throw new IllegalStateException("Multiple tables found for name: \"" + name + "\""); + return tables.get(0); + } +} diff --git a/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/injector/InjectorTab.java b/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/injector/InjectorTab.java new file mode 100644 index 0000000000..4d6c898a1e --- /dev/null +++ b/java_console/romraider/src/com/romraider/logger/ecu/ui/tab/injector/InjectorTab.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.logger.ecu.ui.tab.injector; + +import com.romraider.logger.ecu.ui.tab.Tab; + +public interface InjectorTab extends Tab { + + double getFuelStoichAfr(); + + double getFuelDensity(); + + boolean isValidClOl(double value); + + boolean isValidAfr(double value); + + boolean isValidRpm(double value); + + boolean isValidMaf(double value); + + boolean isValidMafvChange(double value); + + boolean isValidCoolantTemp(double value); + + boolean isValidIntakeAirTemp(double value); + + boolean isValidTipInThrottle(double value); + +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/maps/DataCell.java b/java_console/romraider/src/com/romraider/maps/DataCell.java new file mode 100644 index 0000000000..42ebb2d011 --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/DataCell.java @@ -0,0 +1,535 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import static com.romraider.util.ColorScaler.getScaledColor; +import static com.romraider.util.ParamChecker.isNullOrEmpty; +import static javax.swing.BorderFactory.createLineBorder; + +import java.awt.Color; +import java.awt.Font; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.io.Serializable; +import java.text.DecimalFormat; + +import javax.swing.JLabel; +import javax.swing.border.Border; + +import org.apache.log4j.Logger; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.util.JEPUtil; +import com.romraider.util.SettingsManager; + +public class DataCell extends JLabel implements MouseListener, Serializable { + private static final long serialVersionUID = -2904293227148940937L; + private static final Logger LOGGER = Logger.getLogger(DataCell.class); + private final DecimalFormat PERCENT_FORMAT = new DecimalFormat("#,##0.0%"); + private final Font defaultFont = new Font("Arial", Font.BOLD, 12); + int unSelectMask1 = MouseEvent.BUTTON1_DOWN_MASK + MouseEvent.CTRL_DOWN_MASK + MouseEvent.ALT_DOWN_MASK; + int unSelectMask2 = MouseEvent.BUTTON3_DOWN_MASK + MouseEvent.CTRL_DOWN_MASK + MouseEvent.ALT_DOWN_MASK; + + private final Table table; + + private Boolean selected = false; + private Boolean highlighted = false; + private Boolean traced = false; + + private int x = 0; + private int y = 0; + + private double binValue = 0.0; + private double originalValue = 0.0; + private double compareToValue = 0.0; + private String liveValue = Settings.BLANK; + + private final Color defaultBorderColor = new Color(0, 0, 0); + private final Color increaseBorderColor = getSettings().getIncreaseBorder(); + private final Color decreaseBorderColor = getSettings().getDecreaseBorder(); + + private String staticText = null; + + public DataCell(Table table) { + this.table = table; + this.setHorizontalAlignment(CENTER); + this.setVerticalAlignment(CENTER); + this.setFont(defaultFont); + this.setOpaque(true); + this.setVisible(true); + this.addMouseListener(this); + } + + public DataCell(Table table, String staticText) { + this(table); + this.staticText = staticText; + table.setStaticDataTable(true); + } + + public DataCell(Table table, double originalValue, int x, int y) { + this(table); + this.originalValue = originalValue; + this.binValue = originalValue; + this.x = x; + this.y = y; + this.setPreferredSize(getSettings().getCellSize()); + } + + public double getBinValue() { + return binValue; + } + + public double getRealValue() { + return JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue); + } + + public void setRealValue(String input) { + // create parser + try { + double result = 0.0; + if (!"x".equalsIgnoreCase(input)) { + result = JEPUtil.evaluate(table.getCurrentScale().getByteExpression(), Double.parseDouble(input)); + if (table.getStorageType() != Settings.STORAGE_TYPE_FLOAT) { + result = (int) Math.round(result); + } + + if(binValue != result) { + this.setBinValue(result); + } + } + } catch (NumberFormatException e) { + // Do nothing. input is null or not a valid number. + } + } + + public double getCompareValue() { + return binValue - compareToValue; + } + + public double getRealCompareValue() { + return JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue) - JEPUtil.evaluate(table.getCurrentScale().getExpression(), compareToValue); + } + + public double getRealCompareChangeValue() { + double realBinValue = JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue); + double realCompareValue = JEPUtil.evaluate(table.getCurrentScale().getExpression(), compareToValue); + + if(realCompareValue != 0.0) { + // Compare change formula ((V2 - V1) / |V1|). + return ((realBinValue - realCompareValue) / Math.abs(realCompareValue)); + } else { + // Use this to avoid divide by 0 or infinite increase. + return realBinValue - realCompareValue; + } + } + + public Color getCompareColor() { + if(table instanceof Table1D) { + Table1D checkTable = (Table1D)table; + if(checkTable.isAxis() && !getSettings().isColorAxis()) { + return getSettings().getAxisColor(); + } + } + + double compareScale; + if (0.0 == getCompareValue()) { + return Settings.UNCHANGED_VALUE_COLOR; + }else if(table.getMinCompare() == table.getMaxCompare()) { + return getSettings().getMaxColor(); + } else { + compareScale = (getCompareValue() - table.getMinCompare()) / (table.getMaxCompare() - table.getMinCompare()); + } + return getScaledColor(compareScale); + } + + public Color getBinColor() { + if(table instanceof Table1D) { + Table1D checkTable = (Table1D)table; + if(checkTable.isAxis() && !getSettings().isColorAxis()) { + return getSettings().getAxisColor(); + } + } + + if (table.getMaxAllowedBin() < getBinValue()) { + return getSettings().getWarningColor(); + } else if (table.getMinAllowedBin() > getBinValue()) { + return getSettings().getWarningColor(); + } else { + // limits not set, scale based on table values + double colorScale; + if (table.getMaxBin() - table.getMinBin() == 0.0) { + // if all values are the same, color will be middle value + colorScale = .5; + } else { + colorScale = (getBinValue() - table.getMinBin()) / (table.getMaxBin() - table.getMinBin()); + } + + return getScaledColor(colorScale); + } + } + + public void drawCell() { + if(table == null) { + // Table will be null in the static case. + return; + } + + this.invalidate(); + setFont(getSettings().getTableFont()); + setText(getCellText()); + setToolTipText(getCellToolTip()); + setBackground(getCellBackgroundColor()); + setForeground(getCellTextColor()); + setBorder(getCellBorder()); + this.validate(); + table.validate(); + table.repaint(); + } + + private Color getCellBackgroundColor() { + Settings settings = getSettings(); + Color backgroundColor; + + if(highlighted) { + backgroundColor = settings.getHighlightColor(); + } else if(selected) { + backgroundColor = settings.getSelectColor(); + } else if(null == table.getCompareTable()) { + backgroundColor = getBinColor(); + }else { + backgroundColor = getCompareColor(); + } + + return backgroundColor; + } + + private Color getCellTextColor() { + Color textColor; + + if(traced) { + if(!getLiveValue().isEmpty()) { + if(table instanceof Table1D) { + textColor = Settings.scaleTextColor; + } else { + textColor = Settings.liveDataTraceTextColor; + } + } else { + textColor = Settings.scaleTextColor; + } + } else if (highlighted) { + textColor = Settings.highlightTextColor; + } else if (selected) { + textColor = Settings.selectTextColor; + } else { + textColor = Settings.scaleTextColor; + } + + return textColor; + } + + private Border getCellBorder() { + Border border; + if(traced) { + border = createLineBorder(getSettings().getliveValueColor(), 2); + } else { + double checkValue; + + if(null == table.getCompareTable()) { + checkValue= originalValue; + } else { + checkValue = compareToValue; + } + + if (checkValue < binValue) { + border = createLineBorder(increaseBorderColor, 2); + } else if (checkValue > binValue) { + border = createLineBorder(decreaseBorderColor, 2); + } else { + border = createLineBorder(defaultBorderColor, 1); + } + } + + return border; + } + + private String getCellText() { + if(table.isStaticDataTable()) { + return getStaticText(); + } + + DecimalFormat formatter = new DecimalFormat(table.getCurrentScale().getFormat()); + String displayString = ""; + + if (null == table.getCompareTable()) { + displayString = formatter.format(getRealValue()); + } else if (table.getCompareDisplay() == Settings.COMPARE_DISPLAY_ABSOLUTE) { + displayString = formatter.format(getRealCompareValue()); + } else if (table.getCompareDisplay() == Settings.COMPARE_DISPLAY_PERCENT) { + if (getCompareValue() == 0.0) { + displayString = PERCENT_FORMAT.format(0.0); + } else { + displayString = PERCENT_FORMAT.format(getRealCompareChangeValue()); + } + } + + if(traced) { + if(!(table instanceof Table1D)) { + displayString = getLiveValueString(displayString); + } + } + return displayString; + } + + private String getCellToolTip() { + if(table.isStaticDataTable()) { + return getStaticText(); + } + + return Double.toString(getRealValue()); + } + + private String getLiveValue() { + return this.liveValue; + } + + private String getLiveValueString(String currentValue) { + return currentValue + (isNullOrEmpty(getLiveValue()) ? Settings.BLANK : (':' + getLiveValue())); + } + + public void setBinValue(double newBinValue) { + if(binValue == newBinValue) { + return; + } + + double checkedValue = newBinValue; + + // make sure it's in range + if(checkedValue < table.getMinAllowedBin()) { + checkedValue = table.getMinAllowedBin(); + } + + if(checkedValue > table.getMaxAllowedBin()) { + checkedValue = table.getMaxAllowedBin(); + } + + if(binValue == checkedValue) { + return; + } + + // set bin. + binValue = checkedValue; + drawCell(); + } + + @Override + public String toString() { + return getCellText(); + } + + public Boolean isSelected() { + return selected; + } + + public void setSelected(Boolean selected) { + if(!table.isStaticDataTable() && this.selected != selected) { + this.selected = selected; + drawCell(); + } + } + + public void setHighlighted(Boolean highlighted) { + if(!table.isStaticDataTable() && this.highlighted != highlighted) { + this.highlighted = highlighted; + drawCell(); + } + } + + public boolean isHighlighted() { + return highlighted; + } + + @Override + public void mouseEntered(MouseEvent e) { + if(unSelectMask1 == (e.getModifiersEx() & unSelectMask1)) { + clearCell(); + } else if(unSelectMask2 == (e.getModifiersEx() & unSelectMask2)) { + clearCell(); + } else { + table.highlight(x, y); + } + } + + @Override + public void mousePressed(MouseEvent e) { + if (!e.isControlDown()) { + table.clearSelection(); + } + + if (e.isControlDown() && e.isAltDown()) { + clearCell(); + } else { + table.startHighlight(x, y); + } + requestFocus(); + ECUEditorManager.getECUEditor().getTableToolBar().updateTableToolBar(table); + } + + @Override + public void mouseReleased(MouseEvent e) { + table.stopHighlight(); + } + + @Override + public void mouseClicked(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + + private void clearCell() { + if(isHighlighted()) { + setHighlighted(false); + } + if(isSelected()) { + setSelected(false); + } + } + + public void increment(double increment) { + double oldValue = getRealValue(); + + if (table.getCurrentScale().getCoarseIncrement() < 0.0) { + increment = 0.0 - increment; + } + + double incResult = JEPUtil.evaluate(table.getCurrentScale().getByteExpression(), (oldValue + increment)); + if (table.getStorageType() == Settings.STORAGE_TYPE_FLOAT) { + if(binValue != incResult) { + this.setBinValue(incResult); + } + } else { + int roundResult = (int) Math.round(incResult); + if(binValue != roundResult) { + this.setBinValue(roundResult); + } + } + + // make sure table is incremented if change isn't great enough + int maxValue = (int) Math.pow(8, table.getStorageType()); + + if (table.getStorageType() != Settings.STORAGE_TYPE_FLOAT && + oldValue == getRealValue() && + binValue > 0.0 && + binValue < maxValue) { + LOGGER.debug(maxValue + " " + binValue); + increment(increment * 2); + } + } + + public void undo() { + this.setBinValue(originalValue); + } + + public void setRevertPoint() { + this.setOriginalValue(binValue); + this.drawCell(); + } + + public void setOriginalValue(double originalValue) { + this.originalValue = originalValue; + } + + public void setCompareValue(DataCell compareCell) { + if(Settings.DATA_TYPE_BIN == table.getCompareValueType()) + { + if(this.compareToValue == compareCell.binValue) { + return; + } + + this.compareToValue = compareCell.binValue; + } else { + if(this.compareToValue == compareCell.originalValue) { + return; + } + + this.compareToValue = compareCell.originalValue; + } + } + + public void multiply(double factor) { + setBinValue(binValue * factor); + } + + public void setLiveDataTrace(boolean trace) { + if(traced != trace) { + traced = trace; + drawCell(); + } + } + + public void setLiveDataTraceValue(String liveValue) { + if(this.liveValue != liveValue) { + this.liveValue = liveValue; + drawCell(); + } + } + + private Settings getSettings() { + return SettingsManager.getSettings(); + } + + @Override + public boolean equals(Object other) { + if(other == null) { + return false; + } + + if(!(other instanceof DataCell)) { + return false; + } + + DataCell otherCell = (DataCell) other; + + if(this.table.isStaticDataTable() != otherCell.table.isStaticDataTable()) { + return false; + } + + return binValue == otherCell.binValue; + } + + public String getStaticText() { + String displayString = null; + try { + DecimalFormat formatter = new DecimalFormat(table.getCurrentScale().getFormat()); + + double staticDouble = Double.parseDouble(staticText); + displayString = formatter.format(JEPUtil.evaluate(table.getCurrentScale().getExpression(), staticDouble)); + } catch (Exception ex) { + displayString = this.staticText; + } + return displayString; + } + + public void setY(int y) { + this.y = y; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/maps/Rom.java b/java_console/romraider/src/com/romraider/maps/Rom.java new file mode 100644 index 0000000000..5092850db3 --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/Rom.java @@ -0,0 +1,419 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import static com.romraider.maps.RomChecksum.calculateRomChecksum; +import static com.romraider.util.HexUtil.asBytes; +import static com.romraider.util.HexUtil.asHex; +import static javax.swing.JOptionPane.DEFAULT_OPTION; +import static javax.swing.JOptionPane.QUESTION_MESSAGE; +import static javax.swing.JOptionPane.showOptionDialog; + +import java.beans.PropertyVetoException; +import java.io.File; +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Vector; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; + +import org.apache.log4j.Logger; + +import com.romraider.Settings; +import com.romraider.logger.ecu.ui.handler.table.TableUpdateHandler; +import com.romraider.swing.CategoryTreeNode; +import com.romraider.swing.JProgressPane; +import com.romraider.swing.TableFrame; +import com.romraider.swing.TableTreeNode; +import com.romraider.util.SettingsManager; +import com.romraider.xml.InvalidTableNameException; +import com.romraider.xml.TableNotFoundException; + +public class Rom extends DefaultMutableTreeNode implements Serializable { + private static final long serialVersionUID = 7865405179738828128L; + private static final Logger LOGGER = Logger.getLogger(Rom.class); + private RomID romID = new RomID(); + private String fileName = ""; + private File fullFileName = new File("."); + private final Vector tableNodes = new Vector(); + private byte[] binData; + private boolean isAbstract = false; + + public Rom() { + tableNodes.clear(); + } + + public void refreshDisplayedTables() { + // Remove all nodes from the ROM tree node. + super.removeAllChildren(); + + Settings settings = SettingsManager.getSettings(); + + // Add nodes to ROM tree. + for (TableTreeNode tableTreeNode : tableNodes) { + TableFrame tableFrame = tableTreeNode.getFrame(); + Table table = tableFrame.getTable(); + + if (settings.isDisplayHighTables() || settings.getUserLevel() >= table.getUserLevel()) { + boolean categoryExists = false; + + for (int j = 0; j < getChildCount(); j++) { + if (getChildAt(j).toString().equals(table.getCategory())) { + // add to appropriate category + getChildAt(j).add(tableTreeNode); + categoryExists = true; + break; + } + } + + if (!categoryExists) { // if category does not already exist, create it + CategoryTreeNode categoryNode = new CategoryTreeNode(table.getCategory()); + categoryNode.add(tableTreeNode); + this.add(categoryNode); + } + } + } + } + + public void addTable(Table table) { + boolean found = false; + String frameTitle = this.getFileName()+" - "+table.getName(); + + for (int i = 0; i < tableNodes.size(); i++) { + if (tableNodes.get(i).getTable().equals(table)) { + tableNodes.remove(i); + tableNodes.add(i, new TableTreeNode(new TableFrame(frameTitle, table))); + found = true; + break; + } + } + if (!found) { + tableNodes.add(new TableTreeNode(new TableFrame(frameTitle, table))); + } + } + + public void addTableByName(Table table) { + boolean found = false; + String frameTitle = this.getFileName()+" - "+table.getName(); + + for (int i = 0; i < tableNodes.size(); i++) { + if (tableNodes.get(i).getTable().getName().equalsIgnoreCase(table.getName())) { + tableNodes.remove(i); + tableNodes.add(i, new TableTreeNode(new TableFrame(frameTitle, table))); + found = true; + break; + } + } + if (!found) { + tableNodes.add(new TableTreeNode(new TableFrame(frameTitle, table))); + } + } + + public void removeTable(Table table) { + for(int i = 0; i < tableNodes.size(); i++) { + if(tableNodes.get(i).getTable().equals(table)) { + tableNodes.remove(i); + return; + } + } + } + + public void removeTableByName(Table table) { + for(int i = 0; i < tableNodes.size(); i++) { + if(tableNodes.get(i).getTable().getName().equalsIgnoreCase(table.getName())) { + tableNodes.remove(i); + return; + } + } + } + + public Table getTableByName(String tableName) throws TableNotFoundException, InvalidTableNameException { + if(null == tableName || tableName.isEmpty()) { + throw new InvalidTableNameException(); + } + + for (TableTreeNode tableNode : tableNodes) { + if (tableNode.getTable().getName().equalsIgnoreCase(tableName)) { + return tableNode.getTable(); + } + } + throw new TableNotFoundException(); + } + + public List
findTables(String regex) { + List
result = new ArrayList
(); + for (TableTreeNode tableNode : tableNodes) { + String name = tableNode.getTable().getName(); + if (name.matches(regex)) result.add(tableNode.getTable()); + } + return result; + } + + public void populateTables(byte[] binData, JProgressPane progress) { + this.binData = binData; + for (int i = 0; i < tableNodes.size(); i++) { + + // update progress + int currProgress = (int) (i / (double) tableNodes.size() * 40); + progress.update("Populating tables...", 50 + currProgress); + + Table table = tableNodes.get(i).getTable(); + try { + // if storageaddress has not been set (or is set to 0) omit table + if (table.getStorageAddress() != 0) { + try { + table.populateTable(binData, this.getRomID().getRamOffset()); + TableUpdateHandler.getInstance().registerTable(table); + + if (null != table.getName() && table.getName().equalsIgnoreCase("Checksum Fix")){ + setEditStamp(binData, table.getStorageAddress()); + } + } catch (ArrayIndexOutOfBoundsException ex) { + + LOGGER.error(table.getName() + + " type " + table.getType() + " start " + + table.getStorageAddress() + " " + binData.length + " filesize", ex); + + // table storage address extends beyond end of file + JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(table), "Storage address for table \"" + table.getName() + + "\" is out of bounds.\nPlease check ECU definition file.", "ECU Definition Error", JOptionPane.ERROR_MESSAGE); + tableNodes.removeElementAt(i); + i--; + } catch (IndexOutOfBoundsException iex) { + LOGGER.error(table.getName() + + " type " + table.getType() + " start " + + table.getStorageAddress() + " " + binData.length + " filesize", iex); + + // table storage address extends beyond end of file + JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(table), "Storage address for table \"" + table.getName() + + "\" is out of bounds.\nPlease check ECU definition file.", "ECU Definition Error", JOptionPane.ERROR_MESSAGE); + tableNodes.removeElementAt(i); + i--; + } + + } else { + tableNodes.removeElementAt(i); + // decrement i because length of vector has changed + i--; + } + + } catch (NullPointerException ex) { + LOGGER.error("Error Populating Table", ex); + JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(table), "There was an error loading table " + table.getName(), "ECU Definition Error", JOptionPane.ERROR_MESSAGE); + tableNodes.removeElementAt(i); + i--; + } + } + } + + private void setEditStamp(byte[] binData, int address) { + byte[] stampData = new byte[4]; + System.arraycopy(binData, address+204, stampData, 0, stampData.length); + String stamp = asHex(stampData); + if (stamp.equalsIgnoreCase("FFFFFFFF")) { + romID.setEditStamp(""); + } + else { + StringBuilder niceStamp = new StringBuilder(stamp); + niceStamp.replace(6, 9, String.valueOf(0xFF & stampData[3])); + niceStamp.insert(6, " v"); + niceStamp.insert(4, "-"); + niceStamp.insert(2, "-"); + niceStamp.insert(0, "20"); + romID.setEditStamp(niceStamp.toString()); + } + } + + public void setRomID(RomID romID) { + this.romID = romID; + } + + public RomID getRomID() { + return romID; + } + + public String getRomIDString() { + return romID.getXmlid(); + } + + @Override + public String toString() { + String output = ""; + output = output + "\n---- Rom ----" + romID.toString(); + for (int i = 0; i < tableNodes.size(); i++) { + output = output + tableNodes.get(i).getTable(); + } + output = output + "\n---- End Rom ----"; + + return output; + } + + public String getFileName() { + return fileName; + } + + public Vector
getTables() { + Vector
tables = new Vector
(); + for(TableTreeNode tableNode : tableNodes) { + tables.add(tableNode.getTable()); + } + return tables; + } + + public Vector getTableNodes() { + return this.tableNodes; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public byte[] saveFile() { + final List checksumTables = new ArrayList(); + for (TableTreeNode tableNode : tableNodes) { + tableNode.getTable().saveFile(binData); + if (tableNode.getTable().getName().contains("Checksum Fix")) { + checksumTables.add(tableNode); + } + } + + if (checksumTables.size() == 1) { + final TableTreeNode checksum = checksumTables.get(0); + byte count = binData[checksum.getTable().getStorageAddress() + 207]; + if (count == -1) { + count = 1; + } + else { + count++; + } + String currentDate = new SimpleDateFormat("yyMMdd").format(new Date()); + String stamp = String.format("%s%02x", currentDate, count); + byte[] romStamp = asBytes(stamp); + System.arraycopy( + romStamp, + 0, + binData, + checksum.getTable().getStorageAddress() + 204, + 4); + setEditStamp(binData, checksum.getTable().getStorageAddress()); + } + + for (TableTreeNode checksum : checksumTables) { + if (!checksum.getTable().isLocked()) { + calculateRomChecksum( + binData, + checksum.getTable().getStorageAddress(), + checksum.getTable().getDataSize() + ); + } + else if (checksum.getTable().isLocked() && + !checksum.getTable().isButtonSelected()) { + + Object[] options = {"Yes", "No"}; + final String message = String.format( + "One or more ROM image Checksums is invalid. " + + "Calculate new Checksums?%n" + + "(NOTE: this will only fix the Checksums it will NOT repair a corrupt ROM image)"); + int answer = showOptionDialog( + SwingUtilities.windowForComponent(checksum.getTable()), + message, + "Checksum Fix", + DEFAULT_OPTION, + QUESTION_MESSAGE, + null, + options, + options[0]); + if (answer == 0) { + calculateRomChecksum( + binData, + checksum.getTable().getStorageAddress(), + checksum.getTable().getDataSize() + ); + } + } + } + return binData; + } + + public void clearData() { + super.removeAllChildren(); + + // Hide and dispose all frames. + for(TableTreeNode tableTreeNode : tableNodes) { + TableFrame frame = tableTreeNode.getFrame(); + frame.setVisible(false); + try { + frame.setClosed(true); + } catch (PropertyVetoException e) { + ; // Do nothing. + } + frame.dispose(); + } + + tableNodes.clear(); + binData = null; + } + + public int getRealFileSize() { + return binData.length; + } + + public File getFullFileName() { + return fullFileName; + } + + public void setFullFileName(File fullFileName) { + this.fullFileName = fullFileName; + this.setFileName(fullFileName.getName()); + for (TableTreeNode tableNode : tableNodes) { + String frameTitle = this.getFileName() + " - " + tableNode.getTable().getName(); + tableNode.getFrame().setTitle(frameTitle); + } + } + + public boolean isAbstract() { + return isAbstract; + } + + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public void refreshTableCompareMenus() { + for(TableTreeNode tableNode : getTableNodes()) { + tableNode.getFrame().refreshSimilarOpenTables(); + } + } + + @Override + public DefaultMutableTreeNode getChildAt(int i) { + return (DefaultMutableTreeNode) super.getChildAt(i); + } + + @Override + public DefaultMutableTreeNode getLastChild() { + return (DefaultMutableTreeNode) super.getLastChild(); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/maps/RomChecksum.java b/java_console/romraider/src/com/romraider/maps/RomChecksum.java new file mode 100644 index 0000000000..adf90c796f --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/RomChecksum.java @@ -0,0 +1,81 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import static com.romraider.xml.RomAttributeParser.parseByteValue; +import static com.romraider.xml.RomAttributeParser.parseIntegerValue; + +import com.romraider.Settings; + +public class RomChecksum { + + public static void calculateRomChecksum(byte[] input, int storageAddress, int dataSize) { + for (int i = storageAddress; i < storageAddress + dataSize; i+=12) { + byte[] newSum = calculateChecksum(input, + (int)parseByteValue(input, 0, i , 4, true), + (int)parseByteValue(input, 0, i+4, 4, true)); + System.arraycopy(newSum, 0, input, i + 8, 4); + } + } + + public static int validateRomChecksum(byte[] input, int storageAddress, int dataSize) { + int result = 0; + int[] results = new int[dataSize / 12]; + int j = 0; + for (int i = storageAddress; i < storageAddress + dataSize; i+=12) { + int startAddr = (int)parseByteValue(input, 0, i , 4, true); + int endAddr = (int)parseByteValue(input, 0, i+4, 4, true); + int diff = (int)parseByteValue(input, 0, i+8, 4, true); + if (j == 0 && + startAddr == 0 && + endAddr == 0 && + diff == Settings.CHECK_TOTAL) { + return result = -1; // -1, all checksums disabled if the first one is disabled + } + else { + results[j] = validateChecksum(input, startAddr, endAddr, diff); + } + j++; + } + for (j = 0; j < (dataSize / 12); j++) { + if (results[j] != 0) { + return j + 1; // position of invalid checksum + } + } + return result; // 0, all checksums are valid + } + + private static int validateChecksum(byte[] input, int startAddr, int endAddr, int diff) { + int byteSum = 0; + for (int i=startAddr; i scales = new Vector(); + protected Scale curScale; + + protected int storageAddress; + protected int storageType; + protected boolean signed; + protected int endian; + protected boolean flip; + protected DataCell[] data = new DataCell[0]; + protected boolean beforeRam = false; + protected int ramOffset = 0; + protected BorderLayout borderLayout = new BorderLayout(); + protected GridLayout centerLayout = new GridLayout(1, 1, 0, 0); + protected JPanel centerPanel = new JPanel(centerLayout); + protected JLabel tableLabel; + protected int verticalOverhead = 103; + protected int horizontalOverhead = 2; + protected int cellHeight = (int) getSettings().getCellSize().getHeight(); + protected int cellWidth = (int) getSettings().getCellSize().getWidth(); + protected int minHeight = 100; + protected int minWidthNoOverlay = 465; + protected int minWidthOverlay = 700; + protected int highlightX; + protected int highlightY; + protected boolean highlight = false; + protected int userLevel = 0; + protected boolean locked = false; + + protected String logParam = Settings.BLANK; + protected boolean overlayLog = false; + + protected CopyTableWorker copyTableWorker; + protected CopySelectionWorker copySelectionWorker; + + protected double minAllowedBin = 0.0; + protected double maxAllowedBin = 0.0; + + protected double maxBin; + protected double minBin; + + protected double maxCompare = 0.0; + protected double minCompare = 0.0; + + protected int compareDisplay = Settings.COMPARE_DISPLAY_ABSOLUTE; + protected int compareValueType = Settings.DATA_TYPE_BIN; + + protected boolean staticDataTable = false; + protected String liveAxisValue = Settings.BLANK; + protected int liveDataIndex = 0; + + private Table compareTable = null; + + public Table() { + scales.clear(); + scales.add(new Scale()); + + this.setLayout(borderLayout); + this.add(centerPanel, BorderLayout.CENTER); + centerPanel.setVisible(true); + + // key binding actions + Action rightAction = new AbstractAction() { + private static final long serialVersionUID = 1042884198300385041L; + + @Override + public void actionPerformed(ActionEvent e) { + cursorRight(); + } + }; + Action leftAction = new AbstractAction() { + private static final long serialVersionUID = -4970441255677214171L; + + @Override + public void actionPerformed(ActionEvent e) { + cursorLeft(); + } + }; + Action downAction = new AbstractAction() { + private static final long serialVersionUID = -7898502951121825984L; + + @Override + public void actionPerformed(ActionEvent e) { + cursorDown(); + } + }; + Action upAction = new AbstractAction() { + private static final long serialVersionUID = 6937621541727666631L; + + @Override + public void actionPerformed(ActionEvent e) { + cursorUp(); + } + }; + Action incCoarseAction = new AbstractAction() { + private static final long serialVersionUID = -8308522736529183148L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().incrementCoarse(); + } + }; + Action decCoarseAction = new AbstractAction() { + private static final long serialVersionUID = -7407628920997400915L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().decrementCoarse(); + } + }; + Action incFineAction = new AbstractAction() { + private static final long serialVersionUID = 7261463425941761433L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().incrementFine(); + } + }; + Action decFineAction = new AbstractAction() { + private static final long serialVersionUID = 8929400237520608035L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().decrementFine(); + } + }; + Action num0Action = new AbstractAction() { + private static final long serialVersionUID = -6310984176739090034L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('0'); + } + }; + Action num1Action = new AbstractAction() { + private static final long serialVersionUID = -6187220355403883499L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('1'); + } + }; + Action num2Action = new AbstractAction() { + private static final long serialVersionUID = -8745505977907325720L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('2'); + } + }; + Action num3Action = new AbstractAction() { + private static final long serialVersionUID = 4694872385823448942L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('3'); + } + }; + Action num4Action = new AbstractAction() { + private static final long serialVersionUID = 4005741329254221678L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('4'); + } + }; + Action num5Action = new AbstractAction() { + private static final long serialVersionUID = -5846094949106279884L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('5'); + } + }; + Action num6Action = new AbstractAction() { + private static final long serialVersionUID = -5338656374925334150L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('6'); + } + }; + Action num7Action = new AbstractAction() { + private static final long serialVersionUID = 1959983381590509303L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('7'); + } + }; + Action num8Action = new AbstractAction() { + private static final long serialVersionUID = 7442763278699460648L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('8'); + } + }; + Action num9Action = new AbstractAction() { + private static final long serialVersionUID = 7475171864584215094L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('9'); + } + }; + Action numPointAction = new AbstractAction() { + private static final long serialVersionUID = -4729135055857591830L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('.'); + } + }; + Action copyAction = new AbstractAction() { + private static final long serialVersionUID = -6978981449261938672L; + + @Override + public void actionPerformed(ActionEvent e) { + copySelection(); + } + }; + Action pasteAction = new AbstractAction() { + private static final long serialVersionUID = 2026817603236490899L; + + @Override + public void actionPerformed(ActionEvent e) { + paste(); + } + }; + Action interpolate = new AbstractAction() { + private static final long serialVersionUID = -2350912575392447149L; + + @Override + public void actionPerformed(ActionEvent e) { + interpolate(); + } + }; + Action verticalInterpolate = new AbstractAction() { + private static final long serialVersionUID = -2350912575392447149L; + + @Override + public void actionPerformed(ActionEvent e) { + verticalInterpolate(); + } + }; + Action horizontalInterpolate = new AbstractAction() { + private static final long serialVersionUID = -6346750245035640773L; + + @Override + public void actionPerformed(ActionEvent e) { + horizontalInterpolate(); + } + }; + Action multiplyAction = new AbstractAction() { + private static final long serialVersionUID = -2350912575392447149L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().multiply(); + } + }; + Action numNegAction = new AbstractAction() { + private static final long serialVersionUID = -6346750245035640773L; + + @Override + public void actionPerformed(ActionEvent e) { + getToolbar().focusSetValue('-'); + } + }; + + // set input mapping + InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW); + + KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0); + KeyStroke left = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0); + KeyStroke up = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0); + KeyStroke down = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0); + KeyStroke decrement = KeyStroke.getKeyStroke('-'); + KeyStroke increment = KeyStroke.getKeyStroke('+'); + KeyStroke decrement2 = KeyStroke.getKeyStroke("control DOWN"); + KeyStroke increment2 = KeyStroke.getKeyStroke("control UP"); + KeyStroke decrement3 = KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, KeyEvent.CTRL_DOWN_MASK); + KeyStroke increment3 = KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, KeyEvent.CTRL_DOWN_MASK); + KeyStroke decrement4 = KeyStroke.getKeyStroke("control shift DOWN"); + KeyStroke increment4 = KeyStroke.getKeyStroke("control shift UP"); + KeyStroke num0 = KeyStroke.getKeyStroke('0'); + KeyStroke num1 = KeyStroke.getKeyStroke('1'); + KeyStroke num2 = KeyStroke.getKeyStroke('2'); + KeyStroke num3 = KeyStroke.getKeyStroke('3'); + KeyStroke num4 = KeyStroke.getKeyStroke('4'); + KeyStroke num5 = KeyStroke.getKeyStroke('5'); + KeyStroke num6 = KeyStroke.getKeyStroke('6'); + KeyStroke num7 = KeyStroke.getKeyStroke('7'); + KeyStroke num8 = KeyStroke.getKeyStroke('8'); + KeyStroke num9 = KeyStroke.getKeyStroke('9'); + KeyStroke mulKey = KeyStroke.getKeyStroke('*'); + KeyStroke mulKeys = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK); + KeyStroke numPoint = KeyStroke.getKeyStroke('.'); + KeyStroke copy = KeyStroke.getKeyStroke("control C"); + KeyStroke paste = KeyStroke.getKeyStroke("control V"); + KeyStroke interp = KeyStroke.getKeyStroke("shift I"); + KeyStroke vinterp = KeyStroke.getKeyStroke("shift V"); + KeyStroke hinterp = KeyStroke.getKeyStroke("shift H"); + KeyStroke numNeg = KeyStroke.getKeyStroke('-'); + + im.put(right, "right"); + im.put(left, "left"); + im.put(up, "up"); + im.put(down, "down"); + im.put(increment, "incCoarseAction"); + im.put(decrement, "decCoarseAction"); + im.put(increment2, "incCoarseAction"); + im.put(decrement2, "decCoarseAction"); + im.put(increment3, "incFineAction"); + im.put(decrement3, "decFineAction"); + im.put(increment4, "incFineAction"); + im.put(decrement4, "decFineAction"); + im.put(num0, "num0Action"); + im.put(num1, "num1Action"); + im.put(num2, "num2Action"); + im.put(num3, "num3Action"); + im.put(num4, "num4Action"); + im.put(num5, "num5Action"); + im.put(num6, "num6Action"); + im.put(num7, "num7Action"); + im.put(num8, "num8Action"); + im.put(num9, "num9Action"); + im.put(numPoint, "numPointAction"); + im.put(copy, "copyAction"); + im.put(paste, "pasteAction"); + im.put(interp, "interpolate"); + im.put(vinterp, "verticalInterpolate"); + im.put(hinterp, "horizontalInterpolate"); + im.put(mulKey, "mulAction"); + im.put(mulKeys, "mulAction"); + im.put(numNeg, "numNeg"); + + getActionMap().put(im.get(right), rightAction); + getActionMap().put(im.get(left), leftAction); + getActionMap().put(im.get(up), upAction); + getActionMap().put(im.get(down), downAction); + getActionMap().put(im.get(increment), incCoarseAction); + getActionMap().put(im.get(decrement), decCoarseAction); + getActionMap().put(im.get(increment2), incCoarseAction); + getActionMap().put(im.get(decrement2), decCoarseAction); + getActionMap().put(im.get(increment3), incFineAction); + getActionMap().put(im.get(decrement3), decFineAction); + getActionMap().put(im.get(increment4), incFineAction); + getActionMap().put(im.get(decrement4), decFineAction); + getActionMap().put(im.get(num0), num0Action); + getActionMap().put(im.get(num1), num1Action); + getActionMap().put(im.get(num2), num2Action); + getActionMap().put(im.get(num3), num3Action); + getActionMap().put(im.get(num4), num4Action); + getActionMap().put(im.get(num5), num5Action); + getActionMap().put(im.get(num6), num6Action); + getActionMap().put(im.get(num7), num7Action); + getActionMap().put(im.get(num8), num8Action); + getActionMap().put(im.get(num9), num9Action); + getActionMap().put(im.get(numPoint), numPointAction); + getActionMap().put(im.get(mulKey), multiplyAction); + getActionMap().put(im.get(mulKeys), multiplyAction); + getActionMap().put(im.get(copy), copyAction); + getActionMap().put(im.get(paste), pasteAction); + getActionMap().put(im.get(interp), interpolate); + getActionMap().put(im.get(vinterp), verticalInterpolate); + getActionMap().put(im.get(hinterp), horizontalInterpolate); + getActionMap().put(im.get(numNeg), numNegAction); + + this.setInputMap(WHEN_FOCUSED, im); + } + + public DataCell[] getData() { + return data; + } + + public void setData(DataCell[] data) { + this.data = data; + } + + public void populateTable(byte[] input, int romRamOffset) throws ArrayIndexOutOfBoundsException, IndexOutOfBoundsException { + // temporarily remove lock + boolean tempLock = locked; + locked = false; + + if (!beforeRam) { + this.ramOffset = romRamOffset; + } + + for (int i = 0; i < data.length; i++) { + if (data[i] == null) { + double dataValue = 0.0; + + // populate data cells + if (storageType == Settings.STORAGE_TYPE_FLOAT) { //float storage type + byte[] byteValue = new byte[4]; + byteValue[0] = input[getStorageAddress() + i * 4 - ramOffset]; + byteValue[1] = input[getStorageAddress() + i * 4 - ramOffset + 1]; + byteValue[2] = input[getStorageAddress() + i * 4 - ramOffset + 2]; + byteValue[3] = input[getStorageAddress() + i * 4 - ramOffset + 3]; + dataValue = RomAttributeParser.byteToFloat(byteValue, endian); + + } else { // integer storage type + dataValue = RomAttributeParser.parseByteValue(input, + endian, + getStorageAddress() + i * storageType - ramOffset, + storageType, + signed); + } + + data[i] = new DataCell(this, dataValue, 0, i); + data[i].setPreferredSize(new Dimension(cellWidth, cellHeight)); + centerPanel.add(data[i]); + + // show locked cell + if (tempLock) { + data[i].setForeground(Color.GRAY); + } + } + } + + // reset locked status + locked = tempLock; + calcCellRanges(); + } + + public int getType() { + return type; + } + + public DataCell getDataCell(int location) { + return data[location]; + } + + public void setType(int type) { + this.type = type; + } + + @Override + public String getName() { + if(null == name || name.isEmpty()) { + StringBuilder sb = new StringBuilder(); + sb.append(Settings.DEFAULT_TABLE_NAME); + + if(0 != this.getStorageAddress()) { + sb.append(" ("+this.getStorageAddress() + ")"); + } + + if(null != this.getLogParam() && !this.getLogParam().isEmpty()) { + sb.append(" - " + this.getLogParam()); + } + + return sb.toString(); + } + return name; + } + + @Override + public void setName(String name) { + if(null != name && !name.isEmpty()) { + this.name = name; + } + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Scale getCurrentScale() { + return this.curScale; + } + + public Scale getScale(String scaleName) throws NameNotFoundException { + for (Scale scale : scales) { + if (scale.getName().equalsIgnoreCase(scaleName)) { + return scale; + } + } + return new Scale(); + } + + public Vector getScales() { + return scales; + } + + public void addScale(Scale scale) { + // look for scale, replace or add new + for (int i = 0; i < scales.size(); i++) { + if (scales.get(i).getName().equalsIgnoreCase(scale.getName())) { + scales.remove(i); + break; + } + } + scales.add(scale); + + if(null == curScale) { + this.curScale = scale; + } + + if(SettingsManager.getSettings().getDefaultScale().equalsIgnoreCase(scale.getName())) { + this.curScale = scale; + } + + validateScaling(); + } + + public int getStorageAddress() { + return storageAddress; + } + + public void setStorageAddress(int storageAddress) { + this.storageAddress = storageAddress; + } + + public int getStorageType() { + return storageType; + } + + public void setStorageType(int storageType) { + this.storageType = storageType; + calcValueRange(); + } + + public boolean isSignedData() { + return signed; + } + + public void setSignedData(boolean signed) { + this.signed = signed; + } + + public int getEndian() { + return endian; + } + + public void setEndian(int endian) { + this.endian = endian; + } + + public void setDataSize(int size) { + data = new DataCell[size]; + } + + public int getDataSize() { + return data.length; + } + + public boolean getFlip() { + return flip; + } + + public void setFlip(boolean flip) { + this.flip = flip; + } + + public void setLogParam(String logParam) { + this.logParam = logParam; + } + + public String getLogParam() { + return logParam; + } + + @Override + public String toString() { + /*String output = "\n ---- Table " + name + " ----" + + scale + + "\n Category: " + category + + "\n Type: " + type + + "\n Description: " + description + + "\n Storage Address: " + Integer.toHexString(storageAddress) + + "\n Storage Type: " + storageType + + "\n Endian: " + endian + + "\n Flip: " + flip + + "\n ---- End Table " + name + " ----"; + for (int i = 0; i < data.length; i++) { + if (data[i] != null) { + output = output + "\nData: " + data[i]; + } + } + + return output;*/ + return getName(); + } + + @Override + public boolean equals(Object other) { + try { + if(null == other) { + return false; + } + + if(other == this) { + return true; + } + + if(!(other instanceof Table)) { + return false; + } + + Table otherTable = (Table)other; + + if( (null == this.getName() && null == otherTable.getName()) + || (this.getName().isEmpty() && otherTable.getName().isEmpty()) ) { + ;// Skip name compare if name is null or empty. + } else { + if(!this.getName().equalsIgnoreCase(otherTable.getName())) { + return false; + } + } + + if(this.data.length != otherTable.data.length) + { + return false; + } + + if(this.data.equals(otherTable.data)) + { + return true; + } + + // Compare Bin Values + for(int i=0 ; i < this.data.length ; i++) { + if(! this.data[i].equals(otherTable.data[i])) { + return false; + } + } + + return true; + } catch(Exception ex) { + // TODO: Log Exception. + return false; + } + } + + public double getMaxAllowedBin() { + return maxAllowedBin; + } + + public double getMinAllowedBin() { + return minAllowedBin; + } + + public double getMaxAllowedReal() { + return JEPUtil.evaluate(getCurrentScale().getExpression(), getMaxAllowedBin()); + } + + public double getMinAllowedReal() { + return JEPUtil.evaluate(getCurrentScale().getExpression(), getMinAllowedBin()); + } + + private void calcValueRange() { + if (getStorageType() != Settings.STORAGE_TYPE_FLOAT) { + if (isSignedData()) { + switch (getStorageType()) { + case 1: + minAllowedBin = Byte.MIN_VALUE; + maxAllowedBin = Byte.MAX_VALUE; + break; + case 2: + minAllowedBin = Short.MIN_VALUE; + maxAllowedBin = Short.MAX_VALUE; + break; + case 4: + minAllowedBin = Integer.MIN_VALUE; + maxAllowedBin = Integer.MAX_VALUE; + break; + } + } + else { + maxAllowedBin = (Math.pow(256, getStorageType()) - 1); + minAllowedBin = 0.0; + } + } else { + maxAllowedBin = Float.MAX_VALUE; + + if(isSignedData()) { + minAllowedBin = 0.0; + } else { + minAllowedBin = -Float.MAX_VALUE; + } + } + } + + public void calcCellRanges() { + double binMax = data[0].getBinValue(); + double binMin = data[0].getBinValue(); + + double compareMax = data[0].getCompareValue(); + double compareMin = data[0].getCompareValue(); + + for(DataCell cell : data) { + // Calc bin + if(binMax < cell.getBinValue()) { + binMax = cell.getBinValue(); + } + if(binMin > cell.getBinValue()) { + binMin = cell.getBinValue(); + } + + // Calc compare + double compareValue = cell.getCompareValue(); + if(compareMax < compareValue) { + compareMax = compareValue; + } + if(compareMin > compareValue) { + compareMin = compareValue; + } + } + setMaxBin(binMax); + setMinBin(binMin); + setMaxCompare(compareMax); + setMinCompare(compareMin); + } + + public double getMaxBin() { + return this.maxBin; + } + + public double getMinBin() { + return this.minBin; + } + + public double getMaxReal() { + return JEPUtil.evaluate(getCurrentScale().getExpression(), getMaxBin()); + } + + public double getMinReal() { + return JEPUtil.evaluate(getCurrentScale().getExpression(), getMinBin()); + } + + public void setMaxBin(double maxBin) { + this.maxBin = maxBin; + } + + public void setMinBin(double minBin) { + this.minBin = minBin; + } + + public double getMaxCompare() { + return this.maxCompare; + } + + public void setMaxCompare(double maxCompare) { + this.maxCompare = maxCompare; + } + + public double getMinCompare() { + return this.minCompare; + } + + public void setMinCompare(double minCompare) { + this.minCompare = minCompare; + } + + public void drawTable() { + for(DataCell cell : data) { + if(null != cell) { + cell.drawCell(); + } + } + } + + public Dimension getFrameSize() { + int height = verticalOverhead + cellHeight; + int width = horizontalOverhead + data.length * cellWidth; + if (height < minHeight) { + height = minHeight; + } + int minWidth = isLiveDataSupported() ? minWidthOverlay : minWidthNoOverlay; + if (width < minWidth) { + width = minWidth; + } + return new Dimension(width, height); + } + + public void increment(double increment) { + if (!locked && !(userLevel > getSettings().getUserLevel())) { + for (DataCell cell : data) { + if (cell.isSelected()) { + cell.increment(increment); + } + } + } else if (userLevel > getSettings().getUserLevel()) { + JOptionPane.showMessageDialog(this, "This table can only be modified by users with a userlevel of \n" + + userLevel + " or greater. Click View->User Level to change your userlevel.", + "Table cannot be modified", + JOptionPane.INFORMATION_MESSAGE); + } + } + + public void multiply(double factor) { + if (!locked && !(userLevel > getSettings().getUserLevel())) { + for (DataCell cell : data) { + if (cell.isSelected()) { + cell.multiply(factor); + } + } + } else if (userLevel > getSettings().getUserLevel()) { + JOptionPane.showMessageDialog(this, "This table can only be modified by users with a userlevel of \n" + + userLevel + " or greater. Click View->User Level to change your userlevel.", + "Table cannot be modified", + JOptionPane.INFORMATION_MESSAGE); + } + } + + public void setRealValue(String realValue) { + if (!locked && userLevel <= getSettings().getUserLevel()) { + for(DataCell cell : data) { + if (cell.isSelected()) { + cell.setRealValue(realValue); + } + } + } else if (userLevel > getSettings().getUserLevel()) { + JOptionPane.showMessageDialog(this, "This table can only be modified by users with a userlevel of \n" + + userLevel + " or greater. Click View->User Level to change your userlevel.", + "Table cannot be modified", + JOptionPane.INFORMATION_MESSAGE); + } + } + + public void clearSelection() { + clearSelectedData(); + } + + public void clearSelectedData() { + for (DataCell cell : data) { + if(cell.isSelected()) { + cell.setSelected(false); + } + } + } + + public void startHighlight(int x, int y) { + this.highlightY = y; + this.highlightX = x; + highlight = true; + highlight(x, y); + } + + public void highlight(int x, int y) { + if (highlight) { + for (int i = 0; i < data.length; i++) { + if ((i >= highlightY && i <= y) || (i <= highlightY && i >= y)) { + data[i].setHighlighted(true); + } else { + data[i].setHighlighted(false); + } + } + } + } + + public void stopHighlight() { + highlight = false; + // loop through, selected and un-highlight + for (DataCell cell : data) { + if (cell.isHighlighted()) { + cell.setHighlighted(false); + if(!cell.isSelected()) { + cell.setSelected(true); + } + } + } + } + + public abstract void cursorUp(); + + public abstract void cursorDown(); + + public abstract void cursorLeft(); + + public abstract void cursorRight(); + + public void setRevertPoint() { + for (DataCell cell : data) { + cell.setRevertPoint(); + } + } + + public void undoAll() { + clearLiveDataTrace(); + for (DataCell cell : data) { + cell.undo(); + } + } + + public void undoSelected() { + clearLiveDataTrace(); + for (DataCell cell : data) { + // reset current value to original value + if (cell.isSelected()) { + cell.undo(); + } + } + } + + public byte[] saveFile(byte[] binData) { + if (userLevel <= getSettings().getUserLevel() && (userLevel < 5 || getSettings().isSaveDebugTables()) ) { + for (int i = 0; i < data.length; i++) { + // determine output byte values + byte[] output; + if (storageType != Settings.STORAGE_TYPE_FLOAT) { + // convert byte values + output = RomAttributeParser.parseIntegerValue((int) data[i].getBinValue(), endian, storageType); + for (int z = 0; z < storageType; z++) { // insert into file + binData[i * storageType + z + getStorageAddress() - ramOffset] = output[z]; + } + + } else { // float + // convert byte values + output = RomAttributeParser.floatToByte((float) data[i].getBinValue(), endian); + for (int z = 0; z < 4; z++) { // insert in to file + binData[i * 4 + z + getStorageAddress() - ramOffset] = output[z]; + } + } + } + } + return binData; + } + + public boolean isBeforeRam() { + return beforeRam; + } + + public void setBeforeRam(boolean beforeRam) { + this.beforeRam = beforeRam; + } + + @Override + public void addKeyListener(KeyListener listener) { + super.addKeyListener(listener); + for (DataCell cell : data) { + for (int z = 0; z < storageType; z++) { + cell.addKeyListener(listener); + } + } + } + + public void selectCellAt(int y) { + if(y >= 0 && y < data.length) { + clearSelection(); + data[y].setSelected(true); + highlightY = y; + ECUEditorManager.getECUEditor().getTableToolBar().updateTableToolBar(this); + } + } + + public void copySelection() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(this); + + if(null != ancestorWindow) { + ancestorWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + + ECUEditorManager.getECUEditor().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + copySelectionWorker = new CopySelectionWorker(this); + copySelectionWorker.execute(); + } + + public StringBuffer getTableAsString() { + StringBuffer output = new StringBuffer(Settings.BLANK); + for (int i = 0; i < data.length; i++) { + output.append(data[i].getRealValue()); + if (i < data.length - 1) { + output.append(Settings.TAB); + } + } + return output; + } + + public void copyTable() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(this); + if(null != ancestorWindow) { + ancestorWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + ECUEditorManager.getECUEditor().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + copyTableWorker = new CopyTableWorker(this); + copyTableWorker.execute(); + } + + public String getCellAsString(int index) { + return data[index].getText(); + } + + public void pasteValues(String[] input) { + //set real values + for (int i = 0; i < input.length; i++) { + try { + Double.parseDouble(input[i]); + data[i].setRealValue(input[i]); + } catch (NumberFormatException ex) { /* not a number, do nothing */ } + } + } + + public void paste() { + // TODO: This sounds like desearialize. + + StringTokenizer st = new StringTokenizer(Settings.BLANK); + try { + String input = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor); + st = new StringTokenizer(input); + } catch (UnsupportedFlavorException ex) { /* wrong paste type -- do nothing */ + } catch (IOException ex) { + } + + String pasteType = st.nextToken(); + + if ("[Table1D]".equalsIgnoreCase(pasteType)) { // copied entire table + int i = 0; + while (st.hasMoreTokens()) { + String currentToken = st.nextToken(); + try { + if (!data[i].getText().equalsIgnoreCase(currentToken)) { + data[i].setRealValue(currentToken); + } + } catch (ArrayIndexOutOfBoundsException ex) { /* table larger than target, ignore*/ } + i++; + } + } else if ("[Selection1D]".equalsIgnoreCase(pasteType)) { // copied selection + if (data[highlightY].isSelected()) { + int i = 0; + while (st.hasMoreTokens()) { + try { + data[highlightY + i].setRealValue(st.nextToken()); + } catch (ArrayIndexOutOfBoundsException ex) { /* paste larger than target, ignore */ } + i++; + } + } + } + } + + public void verticalInterpolate() { + horizontalInterpolate(); + } + + public void horizontalInterpolate() { + int[] coords = { getDataSize(), 0}; + DataCell[] tableData = getData(); + + int y; + for (y = 0; y < getDataSize(); y++) { + if (tableData[y].isSelected()) { + if (y < coords[0]) + coords[0] = y; + if (y > coords[1]) + coords[1] = y; + } + } + if (coords[1] - coords[0] > 1) { + double diff = (tableData[coords[0]].getRealValue() - tableData[coords[1]].getRealValue()) / (coords[1] - coords[0]); + if (Math.abs(diff) > 0) { + for (y = coords[0] + 1; y < coords[1]; y++) + data[y].setRealValue(String.valueOf(tableData[y - 1].getRealValue() - diff)); + } + } + } + + public void interpolate() { + horizontalInterpolate(); + } + + public void validateScaling() { + if (type != Settings.TABLE_SWITCH) { + + // make sure a scale is present + if (scales.isEmpty()) { + scales.add(new Scale()); + } + + for(Scale scale : scales) { + double startValue = 5; + double toReal = JEPUtil.evaluate(scale.getExpression(), startValue); // convert real world value of "5" + double endValue = JEPUtil.evaluate(scale.getByteExpression(), toReal); + + // if real to byte doesn't equal 5, report conflict + if (Math.abs(endValue - startValue) > .001) { + + JPanel panel = new JPanel(); + panel.setLayout(new GridLayout(4, 1)); + panel.add(new JLabel("The real value and byte value conversion expressions for table " + getName() + " are invalid.")); + panel.add(new JLabel("To real value: " + scale.getExpression())); + panel.add(new JLabel("To byte: " + scale.getByteExpression())); + + JCheckBox check = new JCheckBox("Always display this message", true); + check.setHorizontalAlignment(JCheckBox.RIGHT); + panel.add(check); + + check.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + getSettings().setCalcConflictWarning(((JCheckBox) e.getSource()).isSelected()); + } + } + ); + + JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(this), panel, + "Warning", JOptionPane.ERROR_MESSAGE); + } + } + } + } + + public void populateCompareValues(Table otherTable) { + if(null == otherTable) { + return; + } + + DataCell[] compareData = otherTable.getData(); + if(data.length != compareData.length) { + return; + } + + clearLiveDataTrace(); + + int i = 0; + for(DataCell cell : data) { + cell.setCompareValue(compareData[i]); + i++; + } + + calcCellRanges(); + drawTable(); + } + + public void setCompareDisplay(int compareDisplay) { + this.compareDisplay = compareDisplay; + drawTable(); + } + + public int getCompareDisplay() { + return this.compareDisplay; + } + + public void setCompareValueType(int compareValueType) { + this.compareValueType = compareValueType; + drawTable(); + } + + public int getCompareValueType() { + return this.compareValueType; + } + + public int getUserLevel() { + return userLevel; + } + + public void setUserLevel(int userLevel) { + this.userLevel = userLevel; + if (userLevel > 5) { + userLevel = 5; + } else if (userLevel < 1) { + userLevel = 1; + } + } + + public void setScaleByName(String scaleName) throws NameNotFoundException { + for(Scale scale : scales) { + if(scale.getName().equalsIgnoreCase(scaleName)) { + Scale currentScale = getCurrentScale(); + if(currentScale == null || !currentScale.equals(scale)) { + this.setCurrentScale(scale); + } + return; + } + } + + throw new NameNotFoundException(); + } + + public void setCurrentScale(Scale curScale) { + this.curScale = curScale; + updateTableLabel(); + drawTable(); + } + + public Settings getSettings() + { + return SettingsManager.getSettings(); + } + + public TableToolBar getToolbar() + { + return ECUEditorManager.getECUEditor().getTableToolBar(); + } + + public boolean isLocked() { + return locked; + } + + public void setLocked(boolean locked) { + this.locked = locked; + } + + public void setOverlayLog(boolean overlayLog) { + this.overlayLog = overlayLog; + if (overlayLog) { + clearLiveDataTrace(); + } + } + + public boolean getOverlayLog() + { + return this.overlayLog; + } + + public double getLiveAxisValue() { + try { + return Double.parseDouble(liveAxisValue); + } catch (NumberFormatException e) { + return 0.0; + } + } + + public abstract boolean isLiveDataSupported(); + + public abstract boolean isButtonSelected(); + + public void highlightLiveData(String liveVal) { + if (getOverlayLog()) { + double liveValue = 0.0; + try{ + liveValue = Double.parseDouble(liveVal); + } catch(NumberFormatException nex) { + return; + } + + int startIdx = data.length; + for (int i = 0; i < data.length; i++) { + double currentValue = data[i].getRealValue(); + if (liveValue == currentValue) { + startIdx = i; + break; + } else if (liveValue < currentValue){ + startIdx = i-1; + break; + } + } + + setLiveDataIndex(startIdx); + DataCell cell = data[getLiveDataIndex()]; + cell.setLiveDataTrace(true); + cell.setLiveDataTraceValue(liveVal); + getToolbar().setLiveDataValue(liveVal); + } + } + + public void updateLiveDataHighlight() { + if (getOverlayLog()) { + data[getLiveDataIndex()].setLiveDataTrace(true); + } + } + + public int getLiveDataIndex() { + return liveDataIndex; + } + + public void setLiveDataIndex(int index) { + if (index < 0) { + index = 0; + } + if (index >= data.length) { + index = data.length - 1; + } + this.liveDataIndex = index; + } + + public void clearLiveDataTrace() { + for (DataCell cell : data) { + cell.setLiveDataTrace(false); + } + } + + public String getLogParamString() { + return getName()+ ":" + getLogParam(); + } + + public Table getCompareTable() { + return compareTable; + } + + public void setCompareTable(Table compareTable) { + this.compareTable = compareTable; + } + + public void updateTableLabel() { + if(null == name || name.isEmpty()) { + ;// Do not update label. + } else if(null == getCurrentScale () || "0x" == getCurrentScale().getUnit()) { + // static or no scale exists. + tableLabel.setText(getName()); + } else { + tableLabel.setText(getName() + " (" + getCurrentScale().getUnit() + ")"); + } + } + + public void colorCells() { + calcCellRanges(); + drawTable(); + } + + public void refreshCompare() { + populateCompareValues(getCompareTable()); + } + + public boolean isStaticDataTable() { + return staticDataTable; + } + + public void setStaticDataTable(boolean staticDataTable) { + this.staticDataTable = staticDataTable; + } +} + +class CopySelectionWorker extends SwingWorker { + Table table; + + public CopySelectionWorker(Table table) { + this.table = table; + } + + @Override + protected Void doInBackground() throws Exception { + // find bounds of selection + // coords[0] = x min, y min, x max, y max + String newline = System.getProperty("line.separator"); + String output = "[Selection1D]" + newline; + boolean copy = false; + int[] coords = new int[2]; + coords[0] = table.getDataSize(); + + for (int i = 0; i < table.getDataSize(); i++) { + if (table.getData()[i].isSelected()) { + if (i < coords[0]) { + coords[0] = i; + copy = true; + } + if (i > coords[1]) { + coords[1] = i; + copy = true; + } + } + } + //make a string of the selection + for (int i = coords[0]; i <= coords[1]; i++) { + if (table.getData()[i].isSelected()) { + output = output + table.getData()[i].getText(); + } else { + output = output + "x"; // x represents non-selected cell + } + if (i < coords[1]) { + output = output + "\t"; + } + } + //copy to clipboard + if (copy) { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(output), null); + } + return null; + } + + @Override + public void done() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(table); + if(null != ancestorWindow) { + ancestorWindow.setCursor(null); + } + table.setCursor(null); + ECUEditorManager.getECUEditor().setCursor(null); + } +} + +class CopyTableWorker extends SwingWorker { + Table table; + + public CopyTableWorker(Table table) { + this.table = table; + } + + @Override + protected Void doInBackground() throws Exception { + String tableHeader = table.getSettings().getTableHeader(); + StringBuffer output = new StringBuffer(tableHeader); + output.append(table.getTableAsString()); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(String.valueOf(output)), null); + return null; + } + + @Override + public void done() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(table); + if(null != ancestorWindow) { + ancestorWindow.setCursor(null); + } + table.setCursor(null); + ECUEditorManager.getECUEditor().setCursor(null); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/maps/Table1D.java b/java_console/romraider/src/com/romraider/maps/Table1D.java new file mode 100644 index 0000000000..21a11ebb52 --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/Table1D.java @@ -0,0 +1,306 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import java.awt.BorderLayout; + +import javax.swing.JLabel; + +import com.romraider.Settings; + +public class Table1D extends Table { + private static final long serialVersionUID = -8747180767803835631L; + private Table axisParent = null; + + public Table1D() { + super(); + } + + public void setAxisParent(Table axisParent) { + this.axisParent = axisParent; + } + + public Table getAxisParent() { + return axisParent; + } + + public void addStaticDataCell(DataCell input) { + for(int i = 0; i < data.length; i++) { + if(data[i] == null) { + data[i] = input; + data[i].setY(i); + break; + } + } + } + + @Override + public void populateTable(byte[] input, int romRamOffset) throws ArrayIndexOutOfBoundsException, IndexOutOfBoundsException { + centerLayout.setRows(1); + centerLayout.setColumns(this.getDataSize()); + + super.populateTable(input, romRamOffset); + + // add to table + for (int i = 0; i < this.getDataSize(); i++) { + centerPanel.add(this.getDataCell(i)); + } + + if(null == name || name.isEmpty()) { + ;// Do not add label. + } else if(null == getCurrentScale () || "0x" == getCurrentScale().getUnit()) { + // static or no scale exists. + tableLabel = new JLabel(getName(), JLabel.CENTER); + add(tableLabel, BorderLayout.NORTH); + } else { + tableLabel = new JLabel(getName() + " (" + getCurrentScale().getUnit() + ")", JLabel.CENTER); + add(tableLabel, BorderLayout.NORTH); + } + } + + @Override + public String toString() { + return super.toString() + " (1D)"; + } + + @Override + public void cursorUp() { + if (type == Settings.TABLE_Y_AXIS) { + if (highlightY > 0 && data[highlightY].isSelected()) { + selectCellAt(highlightY - 1); + } + } else if (type == Settings.TABLE_X_AXIS) { + // Y axis is on top.. nothing happens + } else if (type == Settings.TABLE_1D) { + // no where to move up to + } + } + + @Override + public void cursorDown() { + if (type == Settings.TABLE_Y_AXIS) { + if (getAxisParent().getType() == Settings.TABLE_3D) { + if (highlightY < getDataSize() - 1 && data[highlightY].isSelected()) { + selectCellAt(highlightY + 1); + } + } else if (getAxisParent().getType() == Settings.TABLE_2D) { + if (data[highlightY].isSelected()) { + getAxisParent().selectCellAt(highlightY); + } + } + } else if (type == Settings.TABLE_X_AXIS && data[highlightY].isSelected()) { + ((Table3D) getAxisParent()).selectCellAt(highlightY, this); + } else if (type == Settings.TABLE_1D) { + // no where to move down to + } + } + + @Override + public void cursorLeft() { + if (type == Settings.TABLE_Y_AXIS) { + // X axis is on left.. nothing happens + if (getAxisParent().getType() == Settings.TABLE_2D) { + if (data[highlightY].isSelected()) { + selectCellAt(highlightY - 1); + } + } + } else if (type == Settings.TABLE_X_AXIS && data[highlightY].isSelected()) { + if (highlightY > 0) { + selectCellAt(highlightY - 1); + } + } else if (type == Settings.TABLE_1D && data[highlightY].isSelected()) { + if (highlightY > 0) { + selectCellAt(highlightY - 1); + } + } + } + + @Override + public void cursorRight() { + if (type == Settings.TABLE_Y_AXIS && data[highlightY].isSelected()) { + if (getAxisParent().getType() == Settings.TABLE_3D) { + ((Table3D) getAxisParent()).selectCellAt(highlightY, this); + } else if (getAxisParent().getType() == Settings.TABLE_2D) { + selectCellAt(highlightY + 1); + } + } else if (type == Settings.TABLE_X_AXIS && data[highlightY].isSelected()) { + if (highlightY < getDataSize() - 1) { + selectCellAt(highlightY + 1); + } + } else if (type == Settings.TABLE_1D && data[highlightY].isSelected()) { + if (highlightY < getDataSize() - 1) { + selectCellAt(highlightY + 1); + } + } + } + + @Override + public void clearSelection() { + // Call to the axis parent. The axis parent should then call to clear this data. + getAxisParent().clearSelection(); + } + + @Override + public void startHighlight(int x, int y) { + Table axisParent = getAxisParent(); + axisParent.clearSelectedData(); + + if(axisParent instanceof Table3D) { + Table3D table3D = (Table3D) axisParent; + if(getType() == Settings.TABLE_X_AXIS) { + table3D.getYAxis().clearSelectedData(); + } else if (getType() == Settings.TABLE_Y_AXIS) { + table3D.getXAxis().clearSelectedData(); + } + } else if (axisParent instanceof Table2D) { + ((Table2D) axisParent).getAxis().clearSelectedData(); + } + + + super.startHighlight(x, y); + } + + @Override + public String getCellAsString(int index) { + return data[index].getText(); + } + + @Override + public void highlightLiveData(String liveVal) { + if (getOverlayLog()) { + double liveValue = 0.0; + try{ + liveValue = Double.parseDouble(liveVal); + } catch(NumberFormatException nex) { + return; + } + + int startIdx = data.length; + for (int i = 0; i < data.length; i++) { + double currentValue = 0.0; + if(isStaticDataTable() && null != data[i].getStaticText()) { + try { + currentValue = Double.parseDouble(data[i].getStaticText()); + } catch(NumberFormatException nex) { + return; + } + } else { + currentValue = data[i].getRealValue(); + } + + if (liveValue == currentValue) { + startIdx = i; + break; + } else if (liveValue < currentValue){ + startIdx = i-1; + break; + } + } + + setLiveDataIndex(startIdx); + DataCell cell = data[getLiveDataIndex()]; + cell.setLiveDataTrace(true); + cell.setLiveDataTraceValue(liveVal); + getToolbar().setLiveDataValue(liveVal); + } + getAxisParent().updateLiveDataHighlight(); + } + + @Override + public boolean isLiveDataSupported() { + return false; + } + + @Override + public boolean isButtonSelected() { + return true; + } + + public boolean isAxis() { + return getType() == Settings.TABLE_X_AXIS || + getType() == Settings.TABLE_Y_AXIS || isStaticDataTable(); + } + + @Override + public boolean equals(Object other) { + try { + if(null == other) { + return false; + } + + if(other == this) { + return true; + } + + if(!(other instanceof Table1D)) { + return false; + } + + Table1D otherTable = (Table1D)other; + + if(this.isAxis() != otherTable.isAxis()) { + return false; + } + + if(this.data.length != otherTable.data.length) + { + return false; + } + + if(this.data.equals(otherTable.data)) + { + return true; + } + + // Compare Bin Values + for(int i=0 ; i < this.data.length ; i++) { + if(! this.data[i].equals(otherTable.data[i])) { + return false; + } + } + + return true; + } catch(Exception ex) { + // TODO: Log Exception. + return false; + } + } + + @Override + public void updateTableLabel() { + this.getAxisParent().updateTableLabel(); + } + + @Override + public StringBuffer getTableAsString() { + if(isStaticDataTable()) { + StringBuffer output = new StringBuffer(Settings.BLANK); + for (int i = 0; i < data.length; i++) { + output.append(data[i].getStaticText()); + if (i < data.length - 1) { + output.append(Settings.TAB); + } + } + return output; + } else { + return super.getTableAsString(); + } + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/maps/Table2D.java b/java_console/romraider/src/com/romraider/maps/Table2D.java new file mode 100644 index 0000000000..7b91b89fa9 --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/Table2D.java @@ -0,0 +1,509 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import static com.romraider.util.ParamChecker.isNullOrEmpty; + +import java.awt.BorderLayout; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.event.KeyListener; +import java.io.IOException; +import java.util.StringTokenizer; + +import javax.naming.NameNotFoundException; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; +import javax.swing.SwingWorker; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.util.SettingsManager; + +public class Table2D extends Table { + private static final long serialVersionUID = -7684570967109324784L; + private Table1D axis = new Table1D(); + private JLabel axisLabel; + + private CopyTable2DWorker copyTable2DWorker; + private CopySelection2DWorker copySelection2DWorker; + + public Table2D() { + super(); + verticalOverhead += 18; + } + + public Table1D getAxis() { + return axis; + } + + public void setAxis(Table1D axis) { + this.axis = axis; + axis.setAxisParent(this); + } + + @Override + public String toString() { + return super.toString() + " (2D)";// + axis; + } + + @Override + public void populateCompareValues(Table otherTable) { + if(null == otherTable || !(otherTable instanceof Table2D)) { + return; + } + + Table2D compareTable2D = (Table2D) otherTable; + if(data.length != compareTable2D.data.length || + axis.data.length != compareTable2D.axis.data.length) { + return; + } + + super.populateCompareValues(otherTable); + axis.populateCompareValues(compareTable2D.getAxis()); + } + + @Override + public void refreshCompare() { + populateCompareValues(getCompareTable()); + axis.refreshCompare(); + } + + @Override + public StringBuffer getTableAsString() { + StringBuffer output = new StringBuffer(Settings.BLANK); + output.append(axis.getTableAsString()); + output.append(Settings.NEW_LINE); + output.append(super.getTableAsString()); + return output; + } + + @Override + public Dimension getFrameSize() { + int height = verticalOverhead + cellHeight * 2; + int width = horizontalOverhead + data.length * cellWidth; + if (height < minHeight) { + height = minHeight; + } + int minWidth = isLiveDataSupported() ? minWidthOverlay : minWidthNoOverlay; + if (width < minWidth) { + width = minWidth; + } + return new Dimension(width, height); + } + + @Override + public void populateTable(byte[] input, int romRamOffset) throws ArrayIndexOutOfBoundsException, IndexOutOfBoundsException { + centerLayout.setRows(2); + centerLayout.setColumns(this.getDataSize()); + + try { + axis.populateTable(input, romRamOffset); + super.populateTable(input, romRamOffset); + } catch (ArrayIndexOutOfBoundsException ex) { + throw new ArrayIndexOutOfBoundsException(); + } + + // add to table + for (int i = 0; i < this.getDataSize(); i++) { + centerPanel.add(axis.getDataCell(i)); + } + if (flip) { + for (int i = this.getDataSize() - 1; i >= 0; i--) { + centerPanel.add(this.getDataCell(i)); + } + } else { + for (int i = 0; i < this.getDataSize(); i++) { + centerPanel.add(this.getDataCell(i)); + } + } + + if(null == axis.getName() || axis.getName().isEmpty() || "" == axis.getName()) { + ;// Do not add label. + } else if(null == axis.getCurrentScale() || "0x" == axis.getCurrentScale().getUnit()) { + // static or no scale exists. + axisLabel = new JLabel(axis.getName(), JLabel.CENTER); + add(axisLabel, BorderLayout.NORTH); + } else { + axisLabel = new JLabel(axis.getName() + " (" + axis.getCurrentScale().getUnit() + ")", JLabel.CENTER); + add(axisLabel, BorderLayout.NORTH); + } + + tableLabel = new JLabel(getCurrentScale().getUnit(), JLabel.CENTER); + add(tableLabel, BorderLayout.SOUTH); + repaint(); + } + + @Override + public void updateTableLabel() { + if(null == axis.getName() || axis.getName().length() < 1 || "" == axis.getName()) { + ;// Do not update label. + } else if(null == axis.getCurrentScale() || "0x" == axis.getCurrentScale().getUnit()) { + // static or no scale exists. + axisLabel.setText(axis.getName()); + } else { + axisLabel.setText(axis.getName() + " (" + axis.getCurrentScale().getUnit() + ")"); + } + + tableLabel.setText(getCurrentScale().getUnit()); + } + + @Override + public void clearSelection() { + axis.clearSelectedData(); + clearSelectedData(); + } + + @Override + public void setRevertPoint() { + super.setRevertPoint(); + axis.setRevertPoint(); + } + + @Override + public void undoAll() { + super.undoAll(); + axis.undoAll(); + } + + @Override + public byte[] saveFile(byte[] binData) { + binData = super.saveFile(binData); + binData = axis.saveFile(binData); + return binData; + } + + @Override + public void addKeyListener(KeyListener listener) { + super.addKeyListener(listener); + axis.addKeyListener(listener); + } + + @Override + public void cursorUp() { + if (data[highlightY].isSelected()) { + axis.selectCellAt(highlightY); + } + } + + @Override + public void drawTable() { + super.drawTable(); + axis.drawTable(); + } + + @Override + public void cursorDown() { + axis.cursorDown(); + } + + @Override + public void cursorLeft() { + if (highlightY > 0 && data[highlightY].isSelected()) { + selectCellAt(highlightY - 1); + } else { + axis.cursorLeft(); + } + } + + @Override + public void cursorRight() { + if (highlightY < data.length - 1 && data[highlightY].isSelected()) { + selectCellAt(highlightY + 1); + } else { + axis.cursorRight(); + } + } + + @Override + public void startHighlight(int x, int y) { + axis.clearSelectedData(); + super.startHighlight(x, y); + } + + @Override + public void copySelection() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(this); + if(null != ancestorWindow) { + ancestorWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + ECUEditorManager.getECUEditor().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + super.copySelection(); + copySelection2DWorker = new CopySelection2DWorker(this); + copySelection2DWorker.execute(); + } + + @Override + public void copyTable() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(this); + if(null != ancestorWindow) { + ancestorWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + ECUEditorManager.getECUEditor().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + copyTable2DWorker = new CopyTable2DWorker(this); + copyTable2DWorker.execute(); + } + + @Override + public void paste() { + StringTokenizer st = new StringTokenizer(""); + String input = ""; + try { + input = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor); + st = new StringTokenizer(input); + } catch (UnsupportedFlavorException ex) { /* wrong paste type -- do nothing */ + } catch (IOException ex) { + } + + String pasteType = st.nextToken(); + + if (pasteType.equalsIgnoreCase("[Table2D]")) { // Paste table + String axisValues = "[Table1D]" + Settings.NEW_LINE + st.nextToken(Settings.NEW_LINE); + String dataValues = "[Table1D]" + Settings.NEW_LINE + st.nextToken(Settings.NEW_LINE); + + // put axis in clipboard and paste + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(axisValues), null); + axis.paste(); + // put datavalues in clipboard and paste + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(dataValues), null); + super.paste(); + // reset clipboard + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(input), null); + + } else if (pasteType.equalsIgnoreCase("[Selection1D]")) { // paste selection + if (data[highlightY].isSelected()) { + super.paste(); + } else { + axis.paste(); + } + } + } + + @Override + public void interpolate() { + super.interpolate(); + this.getAxis().interpolate(); + } + + @Override + public void verticalInterpolate() { + super.verticalInterpolate(); + this.getAxis().verticalInterpolate(); + } + + @Override + public void horizontalInterpolate() { + super.horizontalInterpolate(); + this.getAxis().horizontalInterpolate(); + } + + @Override + public boolean isLiveDataSupported() { + return !isNullOrEmpty(axis.getLogParam()); + } + + @Override + public boolean isButtonSelected() { + return true; + } + + @Override + public void clearLiveDataTrace() { + super.clearLiveDataTrace(); + axis.clearLiveDataTrace(); + } + + @Override + public void updateLiveDataHighlight() { + if (getOverlayLog()) { + data[axis.getLiveDataIndex()].setLiveDataTrace(true); + } + } + + @Override + public String getLogParamString() { + StringBuilder sb = new StringBuilder(); + sb.append(axis.getLogParamString()+ ", "); + sb.append(getName()+ ":" + getLogParam()); + return sb.toString(); + } + + @Override + public void setOverlayLog(boolean overlayLog) { + super.setOverlayLog(overlayLog); + axis.setOverlayLog(overlayLog); + if (overlayLog) { + axis.clearLiveDataTrace(); + } + } + + @Override + public void setCompareDisplay(int compareDisplay) { + super.setCompareDisplay(compareDisplay); + axis.setCompareDisplay(compareDisplay); + } + + @Override + public void setCompareValueType(int compareValueType) { + super.setCompareValueType(compareValueType); + axis.setCompareValueType(compareValueType); + } + + @Override + public void setCurrentScale(Scale curScale) { + if(SettingsManager.getSettings().isScaleHeadersAndData() && !axis.isStaticDataTable()) { + try { + this.axis.setScaleByName(curScale.getName()); + } catch (NameNotFoundException e) { + try { + this.axis.setScaleByName(SettingsManager.getSettings().getDefaultScale()); + } catch (NameNotFoundException e1) { + } + } + } + this.curScale = curScale; + updateTableLabel(); + drawTable(); + } + + @Override + public boolean equals(Object other) { + try { + if(null == other) { + return false; + } + + if(other == this) { + return true; + } + + if(!(other instanceof Table2D)) { + return false; + } + + Table2D otherTable = (Table2D)other; + + if( (null == this.getName() && null == otherTable.getName()) + || (this.getName().isEmpty() && otherTable.getName().isEmpty()) ) { + ;// Skip name compare if name is null or empty. + } else if (!this.getName().equalsIgnoreCase(otherTable.getName())) { + return false; + } + + if(!this.axis.equals(otherTable.axis)) { + return false; + } + + if(this.data.length != otherTable.data.length) + { + return false; + } + + if(this.data.equals(otherTable.data)) + { + return true; + } + + // Compare Bin Values + for(int i = 0 ; i < this.data.length ; i++) { + if(! this.data[i].equals(otherTable.data[i])) { + return false; + } + } + + return true; + } catch(Exception ex) { + // TODO: Log Exception. + return false; + } + } + + @Override + public void repaint() { + super.repaint(); + if(null != axis) { + axis.repaint(); + } + } +} + +class CopySelection2DWorker extends SwingWorker { + Table2D table; + Table extendedTable; + + public CopySelection2DWorker(Table2D table) + { + this.table = table; + } + + @Override + protected Void doInBackground() throws Exception { + table.getAxis().copySelection(); + return null; + } + + @Override + public void done() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(table); + if(null != ancestorWindow) { + ancestorWindow.setCursor(null); + } + table.setCursor(null); + ECUEditorManager.getECUEditor().setCursor(null); + } +} + +class CopyTable2DWorker extends SwingWorker { + Table2D table; + + public CopyTable2DWorker(Table2D table) + { + this.table = table; + } + + @Override + protected Void doInBackground() throws Exception { + String tableHeader = table.getSettings().getTable2DHeader(); + StringBuffer output = new StringBuffer(tableHeader); + output.append(table.getTableAsString()); + + //copy to clipboard + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(output.toString()), null); + return null; + + } + + @Override + public void done() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(table); + if(null != ancestorWindow) { + ancestorWindow.setCursor(null); + } + table.setCursor(null); + ECUEditorManager.getECUEditor().setCursor(null); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/maps/Table3D.java b/java_console/romraider/src/com/romraider/maps/Table3D.java new file mode 100644 index 0000000000..25e02550b8 --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/Table3D.java @@ -0,0 +1,1142 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import static com.romraider.util.ParamChecker.isNullOrEmpty; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.event.KeyListener; +import java.io.IOException; +import java.util.StringTokenizer; + +import javax.naming.NameNotFoundException; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.SwingWorker; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.logger.ecu.ui.swing.vertical.VerticalLabelUI; +import com.romraider.util.SettingsManager; +import com.romraider.xml.RomAttributeParser; + +public class Table3D extends Table { + + private static final long serialVersionUID = 3103448753263606599L; + private Table1D xAxis = new Table1D(); + private Table1D yAxis = new Table1D(); + private JLabel xAxisLabel; + private JLabel yAxisLabel; + + @SuppressWarnings("hiding") + DataCell[][] data = new DataCell[1][1]; + private boolean swapXY = false; + private boolean flipX = false; + private boolean flipY = false; + + CopyTable3DWorker copyTable3DWorker; + CopySelection3DWorker copySelection3DWorker; + + public Table3D() { + super(); + verticalOverhead += 39; + horizontalOverhead += 10; + } + + public Table1D getXAxis() { + return xAxis; + } + + public void setXAxis(Table1D xAxis) { + this.xAxis = xAxis; + xAxis.setAxisParent(this); + } + + public Table1D getYAxis() { + return yAxis; + } + + public void setYAxis(Table1D yAxis) { + this.yAxis = yAxis; + yAxis.setAxisParent(this); + } + + public boolean getSwapXY() { + return swapXY; + } + + public void setSwapXY(boolean swapXY) { + this.swapXY = swapXY; + } + + public boolean getFlipX() { + return flipX; + } + + public void setFlipX(boolean flipX) { + this.flipX = flipX; + } + + public boolean getFlipY() { + return flipY; + } + + public void setFlipY(boolean flipY) { + this.flipY = flipY; + } + + public void setSizeX(int size) { + data = new DataCell[size][data[0].length]; + centerLayout.setColumns(size + 1); + } + + public int getSizeX() { + return data.length; + } + + public void setSizeY(int size) { + data = new DataCell[data.length][size]; + centerLayout.setRows(size + 1); + } + + public int getSizeY() { + return data[0].length; + } + + @Override + public void drawTable() { + for(DataCell[] column : data) { + for(DataCell cell : column) { + if(null != cell) { + cell.drawCell(); + } + } + } + xAxis.drawTable(); + yAxis.drawTable(); + } + + @Override + public void populateTable(byte[] input, int romRamOffset) throws NullPointerException, ArrayIndexOutOfBoundsException, IndexOutOfBoundsException { + // fill first empty cell + centerPanel.add(new JLabel()); + if (!beforeRam) { + this.ramOffset = romRamOffset; + } + + // temporarily remove lock + boolean tempLock = locked; + locked = false; + + // populate axiis + try { + xAxis.populateTable(input, romRamOffset); + yAxis.populateTable(input, romRamOffset); + } catch (ArrayIndexOutOfBoundsException ex) { + throw new ArrayIndexOutOfBoundsException(); + } + + for (int x = 0; x < xAxis.getDataSize(); x++) { + centerPanel.add(xAxis.getDataCell(x)); + } + + int offset = 0; + + int iMax = swapXY ? xAxis.getDataSize() : yAxis.getDataSize(); + int jMax = swapXY ? yAxis.getDataSize() : xAxis.getDataSize(); + for (int i = 0; i < iMax; i++) { + for (int j = 0; j < jMax; j++) { + + int x = flipY ? jMax - j - 1 : j; + int y = flipX ? iMax - i - 1 : i; + if (swapXY) { + int z = x; + x = y; + y = z; + } + + + double cellBinValue; + + // populate data cells + if (storageType == Settings.STORAGE_TYPE_FLOAT) { //float storage type + byte[] byteValue = new byte[4]; + byteValue[0] = input[getStorageAddress() + offset * 4 - ramOffset]; + byteValue[1] = input[getStorageAddress() + offset * 4 - ramOffset + 1]; + byteValue[2] = input[getStorageAddress() + offset * 4 - ramOffset + 2]; + byteValue[3] = input[getStorageAddress() + offset * 4 - ramOffset + 3]; + cellBinValue = RomAttributeParser.byteToFloat(byteValue, endian); + + } else { // integer storage type + cellBinValue = RomAttributeParser.parseByteValue(input, + endian, + getStorageAddress() + offset * storageType - ramOffset, + storageType, + signed); + } + + // show locked cell + if (tempLock) { + data[x][y].setForeground(Color.GRAY); + } + + data[x][y] = new DataCell(this, cellBinValue, x, y); + offset++; + } + } + + for (int y = 0; y < yAxis.getDataSize(); y++) { + centerPanel.add(yAxis.getDataCell(y)); + for (int x = 0; x < xAxis.getDataSize(); x++) { + centerPanel.add(data[x][y]); + } + } + + // reset locked status + locked = tempLock; + + GridLayout topLayout = new GridLayout(2, 1); + JPanel topPanel = new JPanel(topLayout); + this.add(topPanel, BorderLayout.NORTH); + topPanel.add(new JLabel(getName(), JLabel.CENTER), BorderLayout.NORTH); + + if(null == xAxis.getName() || xAxis.getName().length() < 1 || "" == xAxis.getName()) { + ;// Do not add label. + } else if(null == xAxis.getCurrentScale() || "0x" == xAxis.getCurrentScale().getUnit()) { + // static or no scale exists. + xAxisLabel = new JLabel(xAxis.getName(), JLabel.CENTER); + topPanel.add(xAxisLabel, BorderLayout.NORTH); + } else { + xAxisLabel = new JLabel(xAxis.getName() + " (" + xAxis.getCurrentScale().getUnit() + ")", JLabel.CENTER); + topPanel.add(xAxisLabel, BorderLayout.NORTH); + } + + yAxisLabel = null; + if(null == yAxis.getName() || yAxis.getName().length() < 1 || "" == yAxis.getName()) { + ;// Do not add label. + } else if(null == yAxis.getCurrentScale() || "0x" == yAxis.getCurrentScale().getUnit()) { + // static or no scale exists. + yAxisLabel = new JLabel(yAxis.getName()); + } else { + yAxisLabel = new JLabel(yAxis.getName() + " (" + yAxis.getCurrentScale().getUnit() + ")"); + } + + yAxisLabel.setUI(new VerticalLabelUI(false)); + add(yAxisLabel, BorderLayout.WEST); + + tableLabel = new JLabel(getCurrentScale().getUnit(), JLabel.CENTER); + add(tableLabel, BorderLayout.SOUTH); + + calcCellRanges(); + } + + @Override + public void updateTableLabel() { + if(null == xAxis.getName() || xAxis.getName().length() < 1 || "" == xAxis.getName()) { + ;// Do not update label. + } else if(null == xAxis.getCurrentScale() || "0x" == xAxis.getCurrentScale().getUnit()) { + // static or no scale exists. + xAxisLabel.setText(xAxis.getName()); + } else { + xAxisLabel.setText(xAxis.getName() + " (" + xAxis.getCurrentScale().getUnit() + ")"); + } + + if(null == yAxis.getName() || yAxis.getName().length() < 1 || "" == yAxis.getName()) { + ;// Do not update label. + } else if(null == yAxis.getCurrentScale() || "0x" == yAxis.getCurrentScale().getUnit()) { + // static or no scale exists. + yAxisLabel.setText(yAxis.getName()); + } else { + yAxisLabel.setText(yAxis.getName() + " (" + yAxis.getCurrentScale().getUnit() + ")"); + } + + tableLabel.setText(getCurrentScale().getUnit()); + } + + @Override + public void calcCellRanges() { + double binMax = data[0][0].getBinValue(); + double binMin = data[0][0].getBinValue(); + + double compareMax = data[0][0].getCompareValue(); + double compareMin = data[0][0].getCompareValue(); + + for(DataCell[] column : data) { + for(DataCell cell : column) { + // Calc bin + if(binMax < cell.getBinValue()) { + binMax = cell.getBinValue(); + } + if(binMin > cell.getBinValue()) { + binMin = cell.getBinValue(); + } + + // Calc compare + double compareValue = cell.getCompareValue(); + if(compareMax < compareValue) { + compareMax = compareValue; + } + if(compareMin > compareValue) { + compareMin = compareValue; + } + } + } + setMaxBin(binMax); + setMinBin(binMin); + setMaxCompare(compareMax); + setMinCompare(compareMin); + } + + @Override + public StringBuffer getTableAsString() { + StringBuffer output = new StringBuffer(Settings.BLANK); + + output.append(xAxis.getTableAsString()); + output.append(Settings.NEW_LINE); + + for (int y = 0; y < getSizeY(); y++) { + output.append(yAxis.data[y].getRealValue()); + output.append(Settings.TAB); + + for (int x = 0; x < getSizeX(); x++) { + output.append(data[x][y].getRealValue()); + if (x < getSizeX() - 1) { + output.append(Settings.TAB); + } + } + + if (y < getSizeY() - 1) { + output.append(Settings.NEW_LINE); + } + } + + return output; + } + + @Override + public void populateCompareValues(Table otherTable) { + if(null == otherTable || !(otherTable instanceof Table3D)) { + return; + } + + Table3D compareTable3D = (Table3D) otherTable; + if(data.length != compareTable3D.data.length || + data[0].length != compareTable3D.data[0].length || + xAxis.getDataSize() != compareTable3D.xAxis.getDataSize() || + yAxis.getDataSize() != compareTable3D.yAxis.getDataSize()) { + return; + } + + clearLiveDataTrace(); + + int x=0; + for (DataCell[] column : data) { + int y = 0; + for(DataCell cell : column) { + cell.setCompareValue(compareTable3D.data[x][y]); + y++; + } + x++; + } + + xAxis.populateCompareValues(compareTable3D.getXAxis()); + yAxis.populateCompareValues(compareTable3D.getYAxis()); + + calcCellRanges(); + drawTable(); + } + + @Override + public void refreshCompare() { + populateCompareValues(getCompareTable()); + xAxis.refreshCompare(); + yAxis.refreshCompare(); + } + + @Override + public Dimension getFrameSize() { + int height = verticalOverhead + cellHeight * data[0].length; + int width = horizontalOverhead + data.length * cellWidth; + if (height < minHeight) { + height = minHeight; + } + int minWidth = isLiveDataSupported() ? minWidthOverlay : minWidthNoOverlay; + if (width < minWidth) { + width = minWidth; + } + return new Dimension(width, height); + } + + @Override + public String toString() { + return super.toString() + " (3D)";/* + + "\n Flip X: " + flipX + + "\n Size X: " + data.length + + "\n Flip Y: " + flipY + + "\n Size Y: " + data[0].length + + "\n Swap X/Y: " + swapXY + + xAxis + + yAxis;*/ + } + + @Override + public void increment(double increment) { + if (!locked) { + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + if (data[x][y].isSelected()) { + data[x][y].increment(increment); + } + } + } + } + } + + @Override + public void multiply(double factor) { + if (!locked) { + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + if (data[x][y].isSelected()) { + data[x][y].multiply(factor); + } + } + } + } + } + + @Override + public void clearSelection() { + xAxis.clearSelectedData(); + yAxis.clearSelectedData(); + clearSelectedData(); + } + + @Override + public void clearSelectedData() { + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + data[x][y].setSelected(false); + } + } + } + + @Override + public void highlight(int xCoord, int yCoord) { + if (highlight) { + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + if (((y >= highlightY && y <= yCoord) || + (y <= highlightY && y >= yCoord)) && + ((x >= highlightX && x <= xCoord) || + (x <= highlightX && x >= xCoord))) { + data[x][y].setHighlighted(true); + } else { + data[x][y].setHighlighted(false); + } + } + } + } + } + + @Override + public void stopHighlight() { + highlight = false; + // loop through, selected and un-highlight + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + if (data[x][y].isHighlighted()) { + data[x][y].setSelected(true); + data[x][y].setHighlighted(false); + } + } + } + } + + @Override + public void setRevertPoint() { + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + data[x][y].setRevertPoint(); + } + } + yAxis.setRevertPoint(); + xAxis.setRevertPoint(); + } + + @Override + public void undoAll() { + clearLiveDataTrace(); + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + data[x][y].undo(); + } + } + yAxis.undoAll(); + xAxis.undoAll(); + } + + @Override + public void undoSelected() { + clearLiveDataTrace(); + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + if (data[x][y].isSelected()) { + data[x][y].undo(); + } + } + } + } + + + @Override + public byte[] saveFile(byte[] binData) { + if ( userLevel <= getSettings().getUserLevel() && (userLevel < 5 || getSettings().isSaveDebugTables()) ) { + binData = xAxis.saveFile(binData); + binData = yAxis.saveFile(binData); + int offset = 0; + + int iMax = swapXY ? xAxis.getDataSize() : yAxis.getDataSize(); + int jMax = swapXY ? yAxis.getDataSize() : xAxis.getDataSize(); + for (int i = 0; i < iMax; i++) { + for (int j = 0; j < jMax; j++) { + + int x = flipY ? jMax - j - 1 : j; + int y = flipX ? iMax - i - 1 : i; + if (swapXY) { + int z = x; + x = y; + y = z; + } + + // determine output byte values + byte[] output; + if (storageType != Settings.STORAGE_TYPE_FLOAT) { + output = RomAttributeParser.parseIntegerValue((int) data[x][y].getBinValue(), endian, storageType); + for (int z = 0; z < storageType; z++) { + binData[offset * storageType + z + getStorageAddress() - ramOffset] = output[z]; + } + } else { // float + output = RomAttributeParser.floatToByte((float) data[x][y].getBinValue(), endian); + for (int z = 0; z < 4; z++) { + binData[offset * 4 + z + getStorageAddress() - ramOffset] = output[z]; + } + } + + + offset++; + } + } + } + return binData; + } + + @Override + public void setRealValue(String realValue) { + if (!locked && !(userLevel > getSettings().getUserLevel()) ) { + for(DataCell[] column : data) { + for(DataCell cell : column) { + if(cell.isSelected()) { + cell.setRealValue(realValue); + } + } + } + } else if (userLevel > getSettings().getUserLevel()) { + JOptionPane.showMessageDialog(this, "This table can only be modified by users with a userlevel of \n" + + userLevel + " or greater. Click View->User Level to change your userlevel.", + "Table cannot be modified", + JOptionPane.INFORMATION_MESSAGE); + } + xAxis.setRealValue(realValue); + yAxis.setRealValue(realValue); + } + + @Override + public void addKeyListener(KeyListener listener) { + xAxis.addKeyListener(listener); + yAxis.addKeyListener(listener); + for (int x = 0; x < this.getSizeX(); x++) { + for (int y = 0; y < this.getSizeY(); y++) { + data[x][y].addKeyListener(listener); + } + } + } + + public void selectCellAt(int y, Table1D axisType) { + if (axisType.getType() == Settings.TABLE_Y_AXIS) { + selectCellAt(0, y); + } else { // y axis + selectCellAt(y, 0); + } + ECUEditorManager.getECUEditor().getTableToolBar().updateTableToolBar(this); + } + + public void deSelectCellAt(int x, int y) { + clearSelection(); + data[x][y].setSelected(false); + highlightX = x; + highlightY = y; + } + + public void selectCellAt(int x, int y) { + clearSelection(); + data[x][y].setSelected(true); + highlightX = x; + highlightY = y; + } + + public void selectCellAtWithoutClear(int x, int y) { + data[x][y].setSelected(true); + highlightX = x; + highlightY = y; + } + + @Override + public void cursorUp() { + if (highlightY > 0 && data[highlightX][highlightY].isSelected()) { + selectCellAt(highlightX, highlightY - 1); + } else if (data[highlightX][highlightY].isSelected()) { + xAxis.selectCellAt(highlightX); + } else { + xAxis.cursorUp(); + yAxis.cursorUp(); + } + } + + @Override + public void cursorDown() { + if (highlightY < getSizeY() - 1 && data[highlightX][highlightY].isSelected()) { + selectCellAt(highlightX, highlightY + 1); + } else { + xAxis.cursorDown(); + yAxis.cursorDown(); + } + } + + @Override + public void cursorLeft() { + if (highlightX > 0 && data[highlightX][highlightY].isSelected()) { + selectCellAt(highlightX - 1, highlightY); + } else if (data[highlightX][highlightY].isSelected()) { + yAxis.selectCellAt(highlightY); + } else { + xAxis.cursorLeft(); + yAxis.cursorLeft(); + } + } + + @Override + public void cursorRight() { + if (highlightX < getSizeX() - 1 && data[highlightX][highlightY].isSelected()) { + selectCellAt(highlightX + 1, highlightY); + } else { + xAxis.cursorRight(); + yAxis.cursorRight(); + } + } + + @Override + public void startHighlight(int x, int y) { + xAxis.clearSelectedData(); + yAxis.clearSelectedData(); + super.startHighlight(x, y); + } + + @Override + public void copySelection() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(this); + if(null != ancestorWindow) { + ancestorWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + ECUEditorManager.getECUEditor().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + copySelection3DWorker = new CopySelection3DWorker(this); + copySelection3DWorker.execute(); + + } + + @Override + public void copyTable() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(this); + if(null != ancestorWindow) { + ancestorWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + ECUEditorManager.getECUEditor().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + copyTable3DWorker = new CopyTable3DWorker(this); + copyTable3DWorker.execute(); + } + + @Override + public void paste() { + StringTokenizer st = new StringTokenizer(""); + String input = ""; + try { + input = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor); + st = new StringTokenizer(input); + } catch (UnsupportedFlavorException ex) { /* wrong paste type -- do nothing */ + } catch (IOException ex) { + } + + String pasteType = st.nextToken(); + + if ("[Table3D]".equalsIgnoreCase(pasteType)) { // Paste table + String newline = System.getProperty("line.separator"); + String xAxisValues = "[Table1D]" + newline + st.nextToken(newline); + + // build y axis and data values + StringBuffer yAxisValues = new StringBuffer("[Table1D]" + newline + st.nextToken("\t")); + StringBuffer dataValues = new StringBuffer("[Table3D]" + newline + st.nextToken("\t") + st.nextToken(newline)); + while (st.hasMoreTokens()) { + yAxisValues.append("\t").append(st.nextToken("\t")); + dataValues.append(newline).append(st.nextToken("\t")).append(st.nextToken(newline)); + } + + // put x axis in clipboard and paste + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(xAxisValues), null); + xAxis.paste(); + // put y axis in clipboard and paste + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(String.valueOf(yAxisValues)), null); + yAxis.paste(); + // put datavalues in clipboard and paste + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(String.valueOf(dataValues)), null); + pasteValues(); + // reset clipboard + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(input), null); + + } else if ("[Selection3D]".equalsIgnoreCase(pasteType)) { // paste selection + pasteValues(); + } else if ("[Selection1D]".equalsIgnoreCase(pasteType)) { // paste selection + xAxis.paste(); + yAxis.paste(); + } + } + + public void pasteValues() { + StringTokenizer st = new StringTokenizer(""); + String newline = System.getProperty("line.separator"); + try { + String input = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor); + st = new StringTokenizer(input); + } catch (UnsupportedFlavorException ex) { /* wrong paste type -- do nothing */ + } catch (IOException ex) { + } + + String pasteType = st.nextToken(); + + // figure paste start cell + int startX = 0; + int startY = 0; + // if pasting a table, startX and Y at 0, else highlight is start + if ("[Selection3D]".equalsIgnoreCase(pasteType)) { + startX = highlightX; + startY = highlightY; + } + + // set values + for (int y = startY; y < getSizeY(); y++) { + if (st.hasMoreTokens()) { + StringTokenizer currentLine = new StringTokenizer(st.nextToken(newline)); + for (int x = startX; x < getSizeX(); x++) { + if (currentLine.hasMoreTokens()) { + String currentToken = currentLine.nextToken(); + + try { + if (!data[x][y].getText().equalsIgnoreCase(currentToken)) { + data[x][y].setRealValue(currentToken); + } + } catch (ArrayIndexOutOfBoundsException ex) { /* copied table is larger than current table*/ } + } + } + } + } + } + + @Override + public void verticalInterpolate() { + int[] coords = { getSizeX(), getSizeY(), 0, 0}; + DataCell[][] tableData = get3dData(); + + int x, y; + for (x = 0; x < getSizeX(); x++) { + for (y = 0; y < getSizeY(); y++) { + if (tableData[x][y].isSelected()) { + if (x < coords[0]) + coords[0] = x; + if (x > coords[2]) + coords[2] = x; + if (y < coords[1]) + coords[1] = y; + if (y > coords[3]) + coords[3] = y; + } + } + } + if (coords[3] - coords[1] > 1) { + double diff; + for (y = coords[0]; y <= coords[2]; y++) { + diff = (tableData[y][coords[1]].getRealValue() - tableData[y][coords[3]].getRealValue()) / (coords[3] - coords[1]); + if (Math.abs(diff) > 0) { + for (x = coords[1] + 1; x < coords[3]; x++) + tableData[y][x].setRealValue(String.valueOf(tableData[y][x - 1].getRealValue() - diff)); + } + } + } + // Interpolate y axis in case the y axis in selected. + this.getYAxis().verticalInterpolate(); + } + + @Override + public void horizontalInterpolate() { + int[] coords = { getSizeX(), getSizeY(), 0, 0 }; + DataCell[][] tableData = get3dData(); + + int x, y; + for (x = 0; x < getSizeX(); x++) { + for (y = 0; y < getSizeY(); y++) { + if (tableData[x][y].isSelected()) { + if (x < coords[0]) + coords[0] = x; + if (x > coords[2]) + coords[2] = x; + if (y < coords[1]) + coords[1] = y; + if (y > coords[3]) + coords[3] = y; + } + } + } + if (coords[2] - coords[0] > 1) { + double diff; + for (x = coords[1]; x <= coords[3]; x++) { + diff = (tableData[coords[0]][x].getRealValue() - tableData[coords[2]][x].getRealValue()) / (coords[2] - coords[0]); + if (Math.abs(diff) > 0) { + for (y = coords[0] + 1; y < coords[2]; y++) + tableData[y][x].setRealValue(String.valueOf(tableData[y - 1][x].getRealValue() - diff)); + } + } + } + // Interpolate x axis in case the x axis in selected. + this.getXAxis().horizontalInterpolate(); + } + + @Override + public void interpolate() { + verticalInterpolate(); + horizontalInterpolate(); + } + + @Override + public boolean isLiveDataSupported() { + return !isNullOrEmpty(xAxis.getLogParam()) && !isNullOrEmpty(yAxis.getLogParam()); + } + + @Override + public boolean isButtonSelected() { + return true; + } + + @Override + public void highlightLiveData(String liveValue) { + if (getOverlayLog()) { + int x = xAxis.getLiveDataIndex(); + int y = yAxis.getLiveDataIndex(); + DataCell cell = data[x][y]; + cell.setLiveDataTrace(true); + cell.setLiveDataTraceValue(liveValue); + getToolbar().setLiveDataValue(liveValue); + } + } + + @Override + public void updateLiveDataHighlight() { + if (getOverlayLog()) { + int x = xAxis.getLiveDataIndex(); + int y = yAxis.getLiveDataIndex(); + data[x][y].setLiveDataTrace(true); + } + } + + @Override + public void clearLiveDataTrace() { + xAxis.clearLiveDataTrace(); + yAxis.clearLiveDataTrace(); + for (int x = 0; x < getSizeX(); x++) { + for (int y = 0; y < getSizeY(); y++) { + data[x][y].setLiveDataTrace(false); + } + } + } + + public DataCell[][] get3dData() { + return data; + } + + @Override + public void setCompareDisplay(int compareDisplay) { + super.setCompareDisplay(compareDisplay); + xAxis.setCompareDisplay(compareDisplay); + yAxis.setCompareDisplay(compareDisplay); + } + + @Override + public void setCompareValueType(int compareValueType) { + super.setCompareValueType(compareValueType); + xAxis.setCompareValueType(compareValueType); + yAxis.setCompareValueType(compareValueType); + } + + @Override + public void setCurrentScale(Scale curScale) { + if(SettingsManager.getSettings().isScaleHeadersAndData()) { + if(!xAxis.isStaticDataTable()) { + try { + this.xAxis.setScaleByName(curScale.getName()); + } catch (NameNotFoundException e) { + try { + this.xAxis.setScaleByName(SettingsManager.getSettings().getDefaultScale()); + } catch (NameNotFoundException e1) { + } + } + } + if(!yAxis.isStaticDataTable()) { + try { + this.yAxis.setScaleByName(curScale.getName()); + } catch (NameNotFoundException e) { + try { + this.yAxis.setScaleByName(SettingsManager.getSettings().getDefaultScale()); + } catch (NameNotFoundException e1) { + } + } + } + } + this.curScale = curScale; + updateTableLabel(); + drawTable(); + } + + @Override + public String getLogParamString() { + StringBuilder sb = new StringBuilder(); + sb.append(xAxis.getLogParamString()+", "); + sb.append(yAxis.getLogParamString()+", "); + sb.append(getName()+ ":" + getLogParam()); + return sb.toString(); + } + + @Override + public void setOverlayLog(boolean overlayLog) { + super.setOverlayLog(overlayLog); + xAxis.setOverlayLog(overlayLog); + yAxis.setOverlayLog(overlayLog); + if (overlayLog) { + xAxis.clearLiveDataTrace(); + yAxis.clearLiveDataTrace(); + } + } + + @Override + public boolean equals(Object other) { + try { + if(null == other) { + return false; + } + + if(other == this) { + return true; + } + + if(!(other instanceof Table3D)) { + return false; + } + + Table3D otherTable = (Table3D)other; + + if( (null == this.getName() && null == otherTable.getName()) + || (this.getName().isEmpty() && otherTable.getName().isEmpty()) ) { + ;// Skip name compare if name is null or empty. + } else if(!this.getName().equalsIgnoreCase(otherTable.getName())) { + return false; + } + + if(! this.xAxis.equals(otherTable.xAxis)) { + return false; + } + + if(! this.yAxis.equals(otherTable.yAxis)) { + return false; + } + + if(this.data.length != otherTable.data.length || this.data[0].length != otherTable.data[0].length) + { + return false; + } + + if(this.data.equals(otherTable.data)) + { + return true; + } + + // Compare Bin Values + for(int i = 0 ; i < this.data.length ; i++) { + for(int j = 0; j < this.data[i].length ; j++) { + if(! this.data[i][j].equals(otherTable.data[i][j]) ) { + return false; + } + } + } + + return true; + } catch(Exception ex) { + // TODO: Log Exception. + return false; + } + } + + @Override + public void repaint() { + super.repaint(); + + if(null != xAxis) { + xAxis.repaint(); + } + + if(null != yAxis) { + yAxis.repaint(); + } + } +} + +class CopySelection3DWorker extends SwingWorker { + Table3D table; + + public CopySelection3DWorker(Table3D table) + { + this.table = table; + } + + @Override + protected Void doInBackground() throws Exception { + // find bounds of selection + // coords[0] = x min, y min, x max, y max + boolean copy = false; + int[] coords = new int[4]; + coords[0] = table.getSizeX(); + coords[1] = table.getSizeY(); + + for (int x = 0; x < table.getSizeX(); x++) { + for (int y = 0; y < table.getSizeY(); y++) { + if (table.get3dData()[x][y].isSelected()) { + if (x < coords[0]) { + coords[0] = x; + copy = true; + } + if (x > coords[2]) { + coords[2] = x; + copy = true; + } + if (y < coords[1]) { + coords[1] = y; + copy = true; + } + if (y > coords[3]) { + coords[3] = y; + copy = true; + } + } + } + } + // make string of selection + if (copy) { + String newline = System.getProperty("line.separator"); + StringBuffer output = new StringBuffer("[Selection3D]" + newline); + for (int y = coords[1]; y <= coords[3]; y++) { + for (int x = coords[0]; x <= coords[2]; x++) { + if (table.get3dData()[x][y].isSelected()) { + output.append(table.get3dData()[x][y].getText()); + } else { + output.append("x"); // x represents non-selected cell + } + if (x < coords[2]) { + output.append("\t"); + } + } + if (y < coords[3]) { + output.append(newline); + } + //copy to clipboard + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(String.valueOf(output)), null); + } + } else { + table.getXAxis().copySelection(); + table.getYAxis().copySelection(); + } + return null; + } + + @Override + public void done() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(table); + if(null != ancestorWindow) { + ancestorWindow.setCursor(null); + } + table.setCursor(null); + ECUEditorManager.getECUEditor().setCursor(null); + } +} + +class CopyTable3DWorker extends SwingWorker { + Table3D table; + + public CopyTable3DWorker(Table3D table) + { + this.table = table; + } + + @Override + protected Void doInBackground() throws Exception { + String tableHeader = table.getSettings().getTable3DHeader(); + StringBuffer output = new StringBuffer(tableHeader); + output.append(table.getTableAsString()); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(String.valueOf(output)), null); + return null; + } + + @Override + public void done() { + Window ancestorWindow = SwingUtilities.getWindowAncestor(table); + if(null != ancestorWindow){ + ancestorWindow.setCursor(null); + } + table.setCursor(null); + ECUEditorManager.getECUEditor().setCursor(null); + } +} diff --git a/java_console/romraider/src/com/romraider/maps/TableSwitch.java b/java_console/romraider/src/com/romraider/maps/TableSwitch.java new file mode 100644 index 0000000000..52b9e0c366 --- /dev/null +++ b/java_console/romraider/src/com/romraider/maps/TableSwitch.java @@ -0,0 +1,388 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.maps; + +import static com.romraider.maps.RomChecksum.validateRomChecksum; +import static com.romraider.util.ByteUtil.indexOfBytes; +import static com.romraider.util.HexUtil.asBytes; +import static javax.swing.JOptionPane.ERROR_MESSAGE; +import static javax.swing.JOptionPane.INFORMATION_MESSAGE; +import static javax.swing.JOptionPane.WARNING_MESSAGE; +import static javax.swing.JOptionPane.showMessageDialog; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.Insets; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.swing.AbstractButton; +import javax.swing.ButtonGroup; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextArea; + +import com.romraider.Settings; + +public class TableSwitch extends Table { + + private static final long serialVersionUID = -4887718305447362308L; + private final ButtonGroup buttonGroup = new ButtonGroup(); + private final Map switchStates = new HashMap(); + private int dataSize = 0; + + public TableSwitch() { + super(); + storageType = 1; + type = Settings.TABLE_SWITCH; + locked = true; + removeAll(); + setLayout(new BorderLayout()); + } + + @Override + public void setDataSize(int size) { + if (dataSize == 0) dataSize = size; + } + + @Override + public int getDataSize() { + return dataSize; + } + + @Override + public void populateTable(byte[] input, int romRamOffset) throws ArrayIndexOutOfBoundsException, IndexOutOfBoundsException { + JPanel radioPanel = new JPanel(new GridLayout(0, 1)); + radioPanel.add(new JLabel(" " + getName())); + for (String stateName : switchStates.keySet()) { + JRadioButton button = new JRadioButton(stateName); + buttonGroup.add(button); + radioPanel.add(button); + } + add(radioPanel, BorderLayout.CENTER); + + // Validate the ROM image checksums. + // if the result is >0: position of failed checksum + // if the result is 0: all the checksums matched + // if the result is -1: all the checksums have been previously disabled + if (super.getName().contains("Checksum Fix")) { + int result = validateRomChecksum(input, getStorageAddress(), dataSize); + String message = String.format( + "Checksum No. %d is invalid in table: %s%n" + + "The ROM image may be corrupt or it has been %n" + + "hex edited manually.%n" + + "The checksum can be corrected when the ROM is saved.", + result, super.getName()); + if (result > 0) { + showMessageDialog(this, + message, + "ERROR - Checksums Failed", + WARNING_MESSAGE); + setButtonsUnselected(buttonGroup); + } + else if (result == -1){ + message = "All Checksums are disabled."; + showMessageDialog(this, + message, + "Warning - Checksum Status", + INFORMATION_MESSAGE); + getButtonByText(buttonGroup, "on").setSelected(true); + } + else { + getButtonByText(buttonGroup, "off").setSelected(true); + locked = false; + } + return; + } + + // Validate XML switch definition data against the ROM data to select + // the appropriate switch setting or throw an error if there is a + // mismatch and disable this table's editing ability. + if (!beforeRam) { + this.ramOffset = romRamOffset; + } + Map sourceStatus = new HashMap(); + for (String stateName : switchStates.keySet()) { + byte[] sourceData = new byte[dataSize]; + System.arraycopy( + input, + storageAddress - ramOffset, + sourceData, + 0, + dataSize); + int compareResult = indexOfBytes(sourceData, getValues(stateName)); + if (compareResult == -1) { + getButtonByText(buttonGroup, stateName).setSelected(false); + } + else { + getButtonByText(buttonGroup, stateName).setSelected(true); + } + sourceStatus.put(stateName, compareResult); + } + + for (String source : sourceStatus.keySet()) { + if (sourceStatus.get(source) != -1) { + locked = false; + break; + } + } + + if (locked) { + String mismatch = String.format("Table: %s%nTable editing has been disabled.%nDefinition file or ROM image may be corrupt.", super.getName()); + showMessageDialog(this, + mismatch, + "ERROR - Data Mismatch", + ERROR_MESSAGE); + setButtonsUnselected(buttonGroup); + } + } + + @Override + public void setName(String name) { + super.setName(name); + } + + @Override + public int getType() { + return Settings.TABLE_SWITCH; + } + + @Override + public void setDescription(String description) { + super.setDescription(description); + JTextArea descriptionArea = new JTextArea(description); + descriptionArea.setOpaque(false); + descriptionArea.setEditable(false); + descriptionArea.setWrapStyleWord(true); + descriptionArea.setLineWrap(true); + descriptionArea.setMargin(new Insets(0,5,5,5)); + + add(descriptionArea, BorderLayout.SOUTH); + } + + @Override + public byte[] saveFile(byte[] input) { + if (!super.getName().contains("Checksum Fix")) { + if (!locked) { + JRadioButton selectedButton = getSelectedButton(buttonGroup); + System.arraycopy( + switchStates.get(selectedButton.getText()), + 0, + input, + getStorageAddress() - ramOffset, + dataSize); + } + } + return input; + } + + public void setValues(String name, String input) { + switchStates.put(name, asBytes(input)); + } + + public byte[] getValues(String key) { + return switchStates.get(key); + } + + @Override + public Dimension getFrameSize() { + int height = verticalOverhead + 75; + int width = horizontalOverhead; + if (height < minHeight) { + height = minHeight; + } + int minWidth = isLiveDataSupported() ? minWidthOverlay : minWidthNoOverlay; + if (width < minWidth) { + width = minWidth; + } + return new Dimension(width, height); + } + + public ButtonGroup getButtonGroup() { + return this.buttonGroup; + } + + public Map getSwitchStates() { + return this.switchStates; + } + + @Override + public void cursorUp() { + } + + @Override + public void cursorDown() { + } + + @Override + public void cursorLeft() { + } + + @Override + public void cursorRight() { + } + + @Override + public boolean isLiveDataSupported() { + return false; + } + + @Override + public boolean isButtonSelected() { + if (buttonGroup.getSelection() == null) { + return false; + } + else { + return true; + } + } + + @Override + public boolean equals(Object other) { + // TODO: Validate DTC equals. + try { + if(null == other) { + return false; + } + + if(other == this) { + return true; + } + + if(!(other instanceof TableSwitch)) { + return false; + } + + TableSwitch otherTable = (TableSwitch)other; + + if( (null == this.getName() && null == otherTable.getName()) + || (this.getName().isEmpty() && otherTable.getName().isEmpty()) ) { + ;// Skip name compare if name is null or empty. + } else if(!this.getName().equalsIgnoreCase(otherTable.getName())) { + return false; + } + + if(this.getDataSize() != otherTable.getDataSize()) { + return false; + } + + if(this.getSwitchStates() == otherTable.getSwitchStates()) { + return true; + } + + // Compare Map Keys + Set keys = new HashSet(this.getSwitchStates().keySet()); + Set otherKeys = new HashSet(otherTable.getSwitchStates().keySet()); + + if(keys.size() != otherKeys.size()) { + return false; + } + + if(!keys.containsAll(otherKeys)) { + return false; + } + + // Compare Map Values. + Set values = new HashSet(this.getSwitchStates().values()); + Set otherValues = new HashSet(otherTable.getSwitchStates().values()); + if(values.equals(otherValues)) { + return true; + } + + // Compare DTC. Is there a better way to compare the DTC? + for(String key : keys) { + JRadioButton button = getButtonByText(this.getButtonGroup(), key); + JRadioButton otherButton = getButtonByText(otherTable.getButtonGroup(), key); + + if(button.isSelected() != otherButton.isSelected()) { + return false; + } + } + + return true; + } catch(Exception ex) { + // TODO: Log Exception. + return false; + } + } + + @Override + public void populateCompareValues(Table compareTable) { + return; // Do nothing. + } + + @Override + public void calcCellRanges() { + return; // Do nothing. + } + + @Override + public void drawTable() + { + return; // Do nothing. + } + + @Override + public void updateTableLabel() { + return; // Do nothing. + } + + @Override + public void setCurrentScale(Scale curScale) { + return; // Do nothing. + } + + + // returns the selected radio button in the specified group + private static JRadioButton getSelectedButton(ButtonGroup group) { + for (Enumeration e = group.getElements(); e.hasMoreElements(); ) { + JRadioButton b = (JRadioButton)e.nextElement(); + if (b.getModel() == group.getSelection()) { + return b; + } + } + return null; + } + + // Unselects & disables all radio buttons in the specified group + private static void setButtonsUnselected(ButtonGroup group) { + for (Enumeration e = group.getElements(); e.hasMoreElements(); ) { + JRadioButton b = (JRadioButton)e.nextElement(); + b.setSelected(false); + b.setEnabled(false); + } + } + + // returns the radio button based on its display text + private static JRadioButton getButtonByText(ButtonGroup group, String text) { + for (Enumeration e = group.getElements(); e.hasMoreElements(); ) { + JRadioButton b = (JRadioButton)e.nextElement(); + if (b.getText().equalsIgnoreCase(text)) { + return b; + } + } + return null; + } +} diff --git a/java_console/romraider/src/com/romraider/net/BrowserControl.java b/java_console/romraider/src/com/romraider/net/BrowserControl.java new file mode 100644 index 0000000000..371769b24d --- /dev/null +++ b/java_console/romraider/src/com/romraider/net/BrowserControl.java @@ -0,0 +1,89 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.net; + +import org.apache.log4j.Logger; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; + +public class BrowserControl { + private static final Logger LOGGER = Logger.getLogger(BrowserControl.class); + + private BrowserControl() { + throw new UnsupportedOperationException(); + } + + public static void displayURL(String url) { + try { + Class display = Class.forName("java.awt.Desktop"); + Object getDesktopMethod = display.getDeclaredMethod("getDesktop").invoke(null); + Method browseMethod = display.getDeclaredMethod("browse", java.net.URI.class); + browseMethod.invoke(getDesktopMethod, new URI(url)); + } catch (Exception e) { + LOGGER.debug("Failed to display URL via java.awt.Desktop. Calling by OS depended method.", e); + displayURLtraditional(url); + } + } + + private static void displayURLtraditional(String url) { + boolean windows = isWindowsPlatform(); + String cmd = null; + try { + if (windows) { + // cmd = 'rundll32 url.dll,FileProtocolHandler http://...' + cmd = WIN_PATH + " " + WIN_FLAG + " " + url; + Runtime.getRuntime().exec(cmd); + } else { + cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")"; + Process p = Runtime.getRuntime().exec(cmd); + try { + int exitCode = p.waitFor(); + if (exitCode != 0) { + cmd = UNIX_PATH + " " + url; + Runtime.getRuntime().exec(cmd); + } + } + catch (InterruptedException x) { + LOGGER.error("Error bringing up browser, command=" + cmd, x); + } + } + } + catch (IOException x) { + // couldn't exec browser + LOGGER.error("Could not invoke browser, command=" + cmd, x); + } + } + + public static boolean isWindowsPlatform() { + String os = System.getProperty("os.name"); + if (os != null && os.startsWith(WIN_ID)) { + return true; + } else { + return false; + } + } + + private static final String WIN_ID = "Windows"; + private static final String WIN_PATH = "rundll32"; + private static final String WIN_FLAG = "url.dll,FileProtocolHandler"; + private static final String UNIX_PATH = "netscape"; + private static final String UNIX_FLAG = "-remote openURL"; +} diff --git a/java_console/romraider/src/com/romraider/net/URL.java b/java_console/romraider/src/com/romraider/net/URL.java new file mode 100644 index 0000000000..58ea1a0985 --- /dev/null +++ b/java_console/romraider/src/com/romraider/net/URL.java @@ -0,0 +1,68 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.net; + +import javax.swing.JLabel; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +public class URL extends JLabel implements MouseListener { + + private static final long serialVersionUID = 8972482185527165793L; + String url = ""; + + public URL(String url) { + super(url); + this.url = url; + this.setFont(new Font("Arial", Font.PLAIN, 12)); + this.addMouseListener(this); + } + + public void paint(Graphics g) { + super.paint(g); + Font f = getFont(); + FontMetrics fm = getFontMetrics(f); + int x1 = 0; + int y1 = fm.getHeight() + 3; + int x2 = fm.stringWidth(getText()); + if (getText().length() > 0) { + g.drawLine(x1, y1, x2, y1); + } + } + + public void mouseClicked(MouseEvent e) { + BrowserControl.displayURL(url); + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseReleased(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/ramtune/test/command/executor/CommandExecutor.java b/java_console/romraider/src/com/romraider/ramtune/test/command/executor/CommandExecutor.java new file mode 100644 index 0000000000..142c20f8b4 --- /dev/null +++ b/java_console/romraider/src/com/romraider/ramtune/test/command/executor/CommandExecutor.java @@ -0,0 +1,27 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.ramtune.test.command.executor; + +public interface CommandExecutor { + + byte[] executeCommand(byte[] command); + + void close(); +} diff --git a/java_console/romraider/src/com/romraider/ramtune/test/io/RamTuneTestAppConnectionProperties.java b/java_console/romraider/src/com/romraider/ramtune/test/io/RamTuneTestAppConnectionProperties.java new file mode 100644 index 0000000000..4c707ce376 --- /dev/null +++ b/java_console/romraider/src/com/romraider/ramtune/test/io/RamTuneTestAppConnectionProperties.java @@ -0,0 +1,75 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.ramtune.test.io; + +import com.romraider.io.connection.ConnectionProperties; + +public final class RamTuneTestAppConnectionProperties implements ConnectionProperties { + private final ConnectionProperties defaultConnectionProperties; + private final int sendTimeout; + + public RamTuneTestAppConnectionProperties(ConnectionProperties defaultConnectionProperties, int sendTimeout) { + this.defaultConnectionProperties = defaultConnectionProperties; + this.sendTimeout = sendTimeout; + } + + public int getBaudRate() { + return defaultConnectionProperties.getBaudRate(); + } + + public void setBaudRate(int b) { + + } + + public int getDataBits() { + return defaultConnectionProperties.getDataBits(); + } + + public int getStopBits() { + return defaultConnectionProperties.getStopBits(); + } + + public int getParity() { + return defaultConnectionProperties.getParity(); + } + + public int getConnectTimeout() { + return defaultConnectionProperties.getConnectTimeout(); + } + + public int getSendTimeout() { + return sendTimeout > 0 ? sendTimeout : defaultConnectionProperties.getSendTimeout(); + } + + public String toString() { + final String properties = String.format( + "%s[baudRate=%d, dataBits=%d, stopBits=%d, parity=%d, " + + "connectTimeout=%d, sendTimeout=%d]", + getClass().getSimpleName(), + getBaudRate(), + getDataBits(), + getStopBits(), + getParity(), + getConnectTimeout(), + getSendTimeout() + ); + return properties; + } +} diff --git a/java_console/romraider/src/com/romraider/swing/AbstractFrame.java b/java_console/romraider/src/com/romraider/swing/AbstractFrame.java new file mode 100644 index 0000000000..d52e79a49f --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/AbstractFrame.java @@ -0,0 +1,65 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.JFrame; +import java.awt.HeadlessException; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + + +public abstract class AbstractFrame extends JFrame implements WindowListener, PropertyChangeListener { + public AbstractFrame() throws HeadlessException { + super(); + } + + public AbstractFrame(String arg0) throws HeadlessException { + super(arg0); + } + + private static final long serialVersionUID = 7948304087075622157L; + + public void windowActivated(WindowEvent arg0) { + } + + public void windowClosed(WindowEvent e) { + } + + public void windowClosing(WindowEvent e) { + } + + public void windowDeactivated(WindowEvent e) { + } + + public void windowDeiconified(WindowEvent e) { + } + + public void windowIconified(WindowEvent e) { + } + + public void windowOpened(WindowEvent e) { + } + + public void propertyChange(PropertyChangeEvent arg0) { + } + +} diff --git a/java_console/romraider/src/com/romraider/swing/CategoryTreeNode.java b/java_console/romraider/src/com/romraider/swing/CategoryTreeNode.java new file mode 100644 index 0000000000..e5092b9be0 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/CategoryTreeNode.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.tree.DefaultMutableTreeNode; + +public class CategoryTreeNode extends DefaultMutableTreeNode { + + private static final long serialVersionUID = -752423096680196879L; + + public CategoryTreeNode(String name) { + super(name); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/CompareImagesForm.java b/java_console/romraider/src/com/romraider/swing/CompareImagesForm.java new file mode 100644 index 0000000000..6d374895a6 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/CompareImagesForm.java @@ -0,0 +1,392 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Image; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Vector; + +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.border.EmptyBorder; +import javax.swing.border.EtchedBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.maps.Rom; +import com.romraider.maps.Table; + +public class CompareImagesForm extends JFrame implements ActionListener { + + private static final long serialVersionUID = -8937472127815934398L; + private final Vector roms; + private final JPanel contentPane; + private final JComboBox comboBoxImageLeft; + private final JComboBox comboBoxImageRight; + private final JButton btnCompare; + private final JList listChanges; + private final DefaultListModel listModelChanges = new DefaultListModel(); + private final ChangeListCellRenderer changeRenderer = new ChangeListCellRenderer(); + private final JScrollPane scrollPaneResults; + private final JLabel lblImageResultString; + + public CompareImagesForm(Vector roms, Image parentImage) { + this.setIconImage(parentImage); + setResizable(false); + this.roms = roms; + + setTitle("Compare Images"); + + setBounds(100, 100, 600, 450); + this.contentPane = new JPanel(); + this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + setContentPane(this.contentPane); + + JLabel lblSelectImages = new JLabel("Selected Images"); + lblSelectImages.setBounds(10, 11, 79, 14); + + contentPane.setLayout(null); + + JPanel panelImageSelector = new JPanel(); + panelImageSelector.setBounds(10, 36, 574, 94); + panelImageSelector.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); + panelImageSelector.setLayout(null); + + this.comboBoxImageLeft = new JComboBox(); + this.comboBoxImageLeft.setBounds(10, 7, 554, 20); + this.comboBoxImageLeft.setToolTipText("Select an image to compare."); + this.comboBoxImageLeft.setRenderer( new ComboBoxRenderer() ); + panelImageSelector.add(this.comboBoxImageLeft); + + this.comboBoxImageRight = new JComboBox(); + this.comboBoxImageRight.setBounds(10, 32, 554, 20); + this.comboBoxImageRight.setToolTipText("Select an image to compare."); + this.comboBoxImageRight.setRenderer( new ComboBoxRenderer() ); + panelImageSelector.add(this.comboBoxImageRight); + + this.btnCompare = new JButton("Compare"); + this.btnCompare.addActionListener(this); + this.btnCompare.setBounds(10, 64, 89, 23); + panelImageSelector.add(this.btnCompare); + this.contentPane.add(panelImageSelector); + this.contentPane.add(lblSelectImages); + + JLabel lblResults = new JLabel("Results:"); + lblResults.setBounds(10, 141, 46, 14); + contentPane.add(lblResults); + + lblImageResultString = new JLabel("Compare images..."); + lblImageResultString.setBounds(66, 141, 518, 14); + contentPane.add(lblImageResultString); + scrollPaneResults = new JScrollPane(); + scrollPaneResults.setBounds(10, 166, 574, 245); + contentPane.add(scrollPaneResults); + + this.listChanges = new JList(this.listModelChanges); + scrollPaneResults.setViewportView(this.listChanges); + listChanges.setCellRenderer(changeRenderer); + listChanges.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + listChanges.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent arg0) { + if (!arg0.getValueIsAdjusting()) { + ListItem selectedTableName = (ListItem) listChanges.getSelectedValue(); + String tableName = selectedTableName.getValue(); + Rom leftRom = (Rom) comboBoxImageLeft.getSelectedItem(); + Rom rightRom = (Rom) comboBoxImageRight.getSelectedItem(); + + // Display Tables + TableTreeNode leftNode = findAndShowTable(leftRom, tableName); + TableTreeNode rightNode = findAndShowTable(rightRom, tableName); + + // Set Comparison + if(leftNode != null && rightNode != null) { + leftNode.getFrame().compareByTable(rightNode.getTable()); + // Update menu bar + for(int i = 0; i< leftNode.getFrame().getTableMenuBar().getSimilarOpenTables().getItemCount(); i++) { + JMenuItem leftItem = leftNode.getFrame().getTableMenuBar().getSimilarOpenTables().getItem(i); + String romFileName = leftItem.getText(); + if(rightRom.getFileName().equalsIgnoreCase(romFileName)) { + leftItem.setSelected(true); + break; + } + } + } + } + } + }); + populateComboBoxes(); + } + + private TableTreeNode findAndShowTable(Rom rom, String tableName) { + for(TableTreeNode node : rom.getTableNodes()) { + if(node != null && node.getTable().getName().equals(tableName)){ + ECUEditorManager.getECUEditor().displayTable(node.getFrame()); + return node; + } + } + return null; + } + + public void populateComboBoxes() + { + for(int i=0; i 1) { + comboBoxImageRight.setSelectedIndex(1); + } + } + + public void compareTables(Rom left, Rom right) + { + listModelChanges.clear(); + + int equal = 0; + int different = 0; + int missing = 0; + + for(TableTreeNode leftNode : left.getTableNodes()) + { + Boolean found = false; + Table leftTable = leftNode.getTable(); + for(TableTreeNode rightNode : right.getTableNodes()) + { + Table rightTable = rightNode.getTable(); + + if(leftTable.getName().equalsIgnoreCase(rightTable.getName())) + { + if(leftTable.equals(rightTable)) { + equal++; + listModelChanges.addElement(new ListItem(1, leftTable.getName())); + } + else { + different++; + listModelChanges.addElement(new ListItem(2, leftTable.getName())); + } + found = true; + break; + } + } + + if(!found) { + missing++; + listModelChanges.addElement(new ListItem(3, leftTable.getName())); + } + } + + // Check if rightTables has tables that do not exist in left table. + for(TableTreeNode rightFrame : right.getTableNodes()) { + Boolean found = false; + for(TableTreeNode leftFrame : left.getTableNodes()) { + if(leftFrame.getTable().getName().equalsIgnoreCase(rightFrame.getTable().getName())) + { + found = true; + break; + } + } + + if(!found) { + missing++; + listModelChanges.addElement(new ListItem(3, rightFrame.getTable().getName())); + } + } + + // Fill out the result string. + if(equal > 0 && different == 0 && missing == 0) { + lblImageResultString.setText("Images are equal."); + lblImageResultString.setForeground(Settings.TABLE_EQUAL_COLOR); + } else if(different > 0) { + lblImageResultString.setText("Images are NOT equal. Equal Tables: "+equal+", Changed Tables: "+different+", Missing Tables: "+missing); + lblImageResultString.setForeground(Settings.TABLE_DIFFERENT_COLOR); + } else { + lblImageResultString.setText("Images are NOT equal. Equal Tables: "+equal+", Changed Tables: "+different+", Missing Tables: "+missing); + lblImageResultString.setForeground(Settings.TABLE_MISSING_COLOR); + } + + // Check if the list has items. + if(listModelChanges.size() < 1) + { + listModelChanges.addElement(new ListItem(0, "No tables are equal, different, or missing.")); + lblImageResultString.setText("Unable to compare images."); + lblImageResultString.setForeground(Color.RED); + return; + } + + // Add list items for 0 counts. + if(equal == 0) + { + listModelChanges.addElement(new ListItem(1, "No Equal Tables.")); + } + + if(different == 0) + { + listModelChanges.addElement(new ListItem(2, "No Changed Tables.")); + } + + if(missing == 0) + { + listModelChanges.addElement(new ListItem(3, "No Missing Tables.")); + } + + } + + @Override + public void actionPerformed(ActionEvent e) { + this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + if (e.getSource() == this.btnCompare) { + if(this.comboBoxImageLeft.getItemCount() > 0 && this.comboBoxImageRight.getItemCount() > 0) + { + Rom leftRom = (Rom)this.comboBoxImageLeft.getSelectedItem(); + Rom rightRom = (Rom)this.comboBoxImageRight.getSelectedItem(); + if(leftRom != null && rightRom != null) + { + compareTables(leftRom, rightRom); + } + } + } + this.setCursor(Cursor.getDefaultCursor()); + } + + class ComboBoxRenderer extends JLabel implements ListCellRenderer + { + + private static final long serialVersionUID = 831689602429105854L; + + public ComboBoxRenderer() { + setOpaque(true); + setHorizontalAlignment(LEFT); + setVerticalAlignment(CENTER); + } + + @Override + public Component getListCellRendererComponent(JList list, Object value, + int index, boolean isSelected, boolean cellHasFocus) { + + if(isSelected) { + setBackground(list.getSelectionBackground()); + setForeground(list.getSelectionForeground()); + } else { + setBackground(list.getBackground()); + setForeground(list.getForeground()); + } + + if(value != null) + { + // Set the text to the rom file name. + Rom rom = (Rom)value; + setText(rom.getFileName()); + setFont(list.getFont()); + } + return this; + } + } + + class ChangeListCellRenderer extends JLabel implements ListCellRenderer { + + private static final long serialVersionUID = -3645192077787635239L; + + public ChangeListCellRenderer() + { + setOpaque(true); + setHorizontalAlignment(LEFT); + setVerticalAlignment(CENTER); + } + + @Override + public Component getListCellRendererComponent(JList paramList, Object value, + int index, boolean isSelected, boolean cellHasFocus) { + + // Set the background color. + if(isSelected) { + setBackground(paramList.getSelectionBackground()); + } else { + setBackground(paramList.getBackground()); + } + + // Set the foreground color based on the item type. + ListItem item = (ListItem)value; + switch(item.getType()) { + case 1: + // equal - default green + setForeground(Settings.TABLE_EQUAL_COLOR); + break; + case 2: + // different - default red + setForeground(Settings.TABLE_DIFFERENT_COLOR); + break; + case 3: + // missing - default yellow + setForeground(Settings.TABLE_MISSING_COLOR); + break; + default: + setForeground(paramList.getForeground()); + break; + } + setText(item.getValue()); + return this; + } + } + + class ListItem { + + private int type; + private String value; + + public ListItem(int type, String value) { + this.type = type; + this.value = value; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } +} diff --git a/java_console/romraider/src/com/romraider/swing/CustomToolbarLayout.java b/java_console/romraider/src/com/romraider/swing/CustomToolbarLayout.java new file mode 100644 index 0000000000..a925d0f2a4 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/CustomToolbarLayout.java @@ -0,0 +1,110 @@ +package com.romraider.swing; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Insets; + +public class CustomToolbarLayout extends FlowLayout { + + private static final long serialVersionUID = 1L; + + public CustomToolbarLayout() { + super(); + } + + public CustomToolbarLayout(int align) { + super(align); + } + + public CustomToolbarLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } + + @Override + public Dimension minimumLayoutSize(Container target) { + // Size of largest component, so we can resize it in + // either direction with something like a split-pane. + return computeMinSize(target); + } + + @Override + public Dimension preferredLayoutSize(Container target) { + return computeSize(target); + } + + private Dimension computeSize(Container target) { + synchronized (target.getTreeLock()) { + int hgap = getHgap(); + int vgap = getVgap(); + int width = target.getWidth(); + + // Let this behave like a regular FlowLayout (single row) + // if the container hasn't been assigned any size yet + if (0 == width) { + width = Integer.MAX_VALUE; + } + + Insets insets = target.getInsets(); + if (null == insets){ + insets = new Insets(0, 0, 0, 0); + } + int reqdWidth = 0; + + int maxwidth = width - (insets.left + insets.right + hgap * 2); + int n = target.getComponentCount(); + int x = 0; + int y = insets.top + vgap; // FlowLayout starts by adding vgap, so do that here too. + int rowHeight = 0; + + for (int i = 0; i < n; i++) { + Component c = target.getComponent(i); + if (c.isVisible()) { + Dimension d = c.getPreferredSize(); + if ((x == 0) || ((x + d.width) <= maxwidth)) { + // fits in current row. + if (x > 0) { + x += hgap; + } + x += d.width; + rowHeight = Math.max(rowHeight, d.height); + } + else { + // Start of new row + x = d.width; + y += vgap + rowHeight; + rowHeight = d.height; + } + reqdWidth = Math.max(reqdWidth, x); + } + } + y += rowHeight; + y += insets.bottom; + return new Dimension(reqdWidth+insets.left+insets.right, y); + } + } + + private Dimension computeMinSize(Container target) { + synchronized (target.getTreeLock()) { + int minx = Integer.MAX_VALUE; + int miny = Integer.MIN_VALUE; + boolean found_one = false; + int n = target.getComponentCount(); + + for (int i = 0; i < n; i++) { + Component c = target.getComponent(i); + if (c.isVisible()) { + found_one = true; + Dimension d = c.getPreferredSize(); + minx = Math.min(minx, d.width); + miny = Math.min(miny, d.height); + } + } + if (found_one) { + return new Dimension(minx, miny); + } + return new Dimension(0, 0); + } + } +} diff --git a/java_console/romraider/src/com/romraider/swing/DebugPanel.java b/java_console/romraider/src/com/romraider/swing/DebugPanel.java new file mode 100644 index 0000000000..fdbc3ad915 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/DebugPanel.java @@ -0,0 +1,54 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static com.romraider.Version.PRODUCT_NAME; +import com.romraider.net.URL; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import java.awt.BorderLayout; +import java.awt.GridLayout; + +public class DebugPanel extends JPanel { + + private static final long serialVersionUID = -7159385694793030962L; + + public DebugPanel(Exception ex, String url) { + setLayout(new BorderLayout()); + + JPanel top = new JPanel(new GridLayout(7, 1)); + top.add(new JLabel(PRODUCT_NAME + " has encountered an exception. Please review the details below.")); + top.add(new JLabel("If you are unable to fix this problem please visit the following website")); + top.add(new JLabel("and provide these details and the steps that lead to this error.")); + top.add(new JLabel()); + top.add(new URL(url)); + top.add(new JLabel()); + top.add(new JLabel("Details:")); + add(top, BorderLayout.NORTH); + + JTextArea output = new JTextArea(ex.getMessage()); + add(output, BorderLayout.CENTER); + output.setAutoscrolls(true); + output.setRows(10); + output.setColumns(40); + ex.printStackTrace(); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/DefinitionManager.java b/java_console/romraider/src/com/romraider/swing/DefinitionManager.java new file mode 100644 index 0000000000..18e9415463 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/DefinitionManager.java @@ -0,0 +1,263 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.Vector; + +import javax.swing.JFileChooser; +import javax.swing.ListSelectionModel; + +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.util.SettingsManager; + +public class DefinitionManager extends javax.swing.JFrame implements ActionListener { + + private static final long serialVersionUID = -3920843496218196737L; + public static int MOVE_UP = 0; + public static int MOVE_DOWN = 1; + + Vector fileNames; + + public DefinitionManager() { + this.setIconImage(ECUEditorManager.getECUEditor().getIconImage()); + initComponents(); + initSettings(); + + definitionList.setFont(new Font("Tahoma", Font.PLAIN, 11)); + definitionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + btnCancel.addActionListener(this); + btnSave.addActionListener(this); + btnAddDefinition.addActionListener(this); + btnRemoveDefinition.addActionListener(this); + btnMoveUp.addActionListener(this); + btnMoveDown.addActionListener(this); + btnApply.addActionListener(this); + btnUndo.addActionListener(this); + + } + + private void initSettings() { + // add definitions to list + Vector definitionFiles = SettingsManager.getSettings().getEcuDefinitionFiles(); + fileNames = new Vector(); + + for (int i = 0; i < definitionFiles.size(); i++) { + fileNames.add(definitionFiles.get(i).getAbsolutePath()); + } + + updateListModel(); + } + + // //GEN-BEGIN:initComponents + private void initComponents() { + jScrollPane1 = new javax.swing.JScrollPane(); + definitionList = new javax.swing.JList(); + defLabel = new javax.swing.JLabel(); + btnMoveUp = new javax.swing.JButton(); + btnMoveDown = new javax.swing.JButton(); + btnAddDefinition = new javax.swing.JButton(); + btnRemoveDefinition = new javax.swing.JButton(); + btnSave = new javax.swing.JButton(); + btnCancel = new javax.swing.JButton(); + btnApply = new javax.swing.JButton(); + btnUndo = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setTitle("Definition File Manager"); + jScrollPane1.setViewportView(definitionList); + + defLabel.setText("ECU Definition File Priority"); + + btnMoveUp.setText("Move Up"); + + btnMoveDown.setText("Move Down"); + + btnAddDefinition.setText("Add..."); + + btnRemoveDefinition.setText("Remove"); + + btnSave.setText("Save"); + + btnCancel.setText("Cancel"); + + btnApply.setText("Apply"); + + btnUndo.setText("Undo"); + +// org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); +// getContentPane().setLayout(layout); +// layout.setHorizontalGroup( +// layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(layout.createSequentialGroup() +// .addContainerGap() +// .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE) +// .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() +// .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) +// .add(layout.createSequentialGroup() +// .add(btnSave) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(btnApply) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(btnUndo) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(btnCancel)) +// .add(layout.createSequentialGroup() +// .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(defLabel) +// .add(layout.createSequentialGroup() +// .add(btnMoveDown) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(btnMoveUp))) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 80, Short.MAX_VALUE) +// .add(btnAddDefinition))) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(btnRemoveDefinition))) +// .addContainerGap()) +// ); +// +// layout.linkSize(new java.awt.Component[]{btnAddDefinition, btnMoveDown, btnMoveUp, btnRemoveDefinition}, org.jdesktop.layout.GroupLayout.HORIZONTAL); +// +// layout.setVerticalGroup( +// layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(layout.createSequentialGroup() +// .addContainerGap() +// .add(defLabel) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) +// .add(btnMoveUp) +// .add(btnMoveDown) +// .add(btnRemoveDefinition, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) +// .add(btnAddDefinition)) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) +// .add(btnSave) +// .add(btnApply) +// .add(btnUndo) +// .add(btnCancel)) +// .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) +// ); + pack(); + }// //GEN-END:initComponents + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == btnCancel) { + dispose(); + + } else if (e.getSource() == btnSave) { + saveSettings(); + dispose(); + + } else if (e.getSource() == btnApply) { + saveSettings(); + + } else if (e.getSource() == btnMoveUp) { + moveSelection(MOVE_UP); + + } else if (e.getSource() == btnMoveDown) { + moveSelection(MOVE_DOWN); + + } else if (e.getSource() == btnAddDefinition) { + addFile(); + + } else if (e.getSource() == btnRemoveDefinition) { + removeSelection(); + + } else if (e.getSource() == btnUndo) { + initSettings(); + + } + + } + + public void saveSettings() { + Vector output = new Vector(); + + // create file vector + for (int i = 0; i < fileNames.size(); i++) { + output.add(new File(fileNames.get(i))); + } + + // save + SettingsManager.getSettings().setEcuDefinitionFiles(output); + } + + public void addFile() { + JFileChooser fc = new JFileChooser("./"); + fc.setFileFilter(new XMLFilter()); + + if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + fileNames.add(fc.getSelectedFile().getAbsolutePath()); + updateListModel(); + } + } + + public void moveSelection(int direction) { + int selectedIndex = definitionList.getSelectedIndex(); + String fileName = fileNames.get(selectedIndex); + + if (direction == MOVE_UP && selectedIndex > 0) { + fileNames.remove(selectedIndex); + fileNames.add(--selectedIndex, fileName); + + } else if (direction == MOVE_DOWN && selectedIndex < definitionList.getModel().getSize()) { + fileNames.remove(selectedIndex); + fileNames.add(++selectedIndex, fileName); + + } + updateListModel(); + definitionList.setSelectedIndex(selectedIndex); + } + + public void removeSelection() { + int index = definitionList.getSelectedIndex(); + if (index < 0) return; + fileNames.remove(index); + updateListModel(); + + } + + public void updateListModel() { + definitionList.setListData(fileNames); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btnAddDefinition; + private javax.swing.JButton btnApply; + private javax.swing.JButton btnCancel; + private javax.swing.JButton btnMoveDown; + private javax.swing.JButton btnMoveUp; + private javax.swing.JButton btnRemoveDefinition; + private javax.swing.JButton btnSave; + private javax.swing.JButton btnUndo; + private javax.swing.JLabel defLabel; + private javax.swing.JList definitionList; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables + +} diff --git a/java_console/romraider/src/com/romraider/swing/ECUEditorMenuBar.java b/java_console/romraider/src/com/romraider/swing/ECUEditorMenuBar.java new file mode 100644 index 0000000000..cd564f7eb3 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/ECUEditorMenuBar.java @@ -0,0 +1,623 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static com.romraider.Version.ABOUT_ICON; +import static com.romraider.Version.BUILDNUMBER; +import static com.romraider.Version.ECU_DEFS_URL; +import static com.romraider.Version.PRODUCT_NAME; +import static com.romraider.Version.SUPPORT_URL; +import static com.romraider.Version.VERSION; +import static javax.swing.JOptionPane.CANCEL_OPTION; +import static javax.swing.JOptionPane.ERROR_MESSAGE; +import static javax.swing.JOptionPane.INFORMATION_MESSAGE; +import static javax.swing.JOptionPane.showConfirmDialog; +import static javax.swing.JOptionPane.showMessageDialog; +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; + +import javax.swing.ButtonGroup; +import javax.swing.JFileChooser; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JSeparator; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.maps.Rom; +import com.romraider.maps.Table; +import com.romraider.net.BrowserControl; +import com.romraider.util.SettingsManager; + +public class ECUEditorMenuBar extends JMenuBar implements ActionListener { + + private static final long serialVersionUID = -4777040428837855236L; + private final JMenu fileMenu = new JMenu("File"); + private final JMenuItem openImage = new JMenuItem("Open Image..."); + private final JMenuItem openImages = new JMenuItem("Open Image(s)..."); + private final JMenuItem saveImage = new JMenuItem("Save Image As..."); + private final JMenuItem saveAsRepository = new JMenuItem("Save Image As Repository..."); + private final JMenuItem refreshImage = new JMenuItem("Refresh Image"); + private final JMenuItem closeImage = new JMenuItem("Close Image"); + private final JMenuItem closeAll = new JMenuItem("Close All Images"); + private final JMenuItem exit = new JMenuItem("Exit"); + + private final JMenu definitionMenu = new JMenu("ECU Definitions"); + private final JMenuItem defManager = new JMenuItem("ECU Definition Manager..."); + private final JMenuItem editDefinition = new JMenuItem("Edit ECU Definitions..."); + private final JMenuItem updateDefinition = new JMenuItem("Get ECU Definitions..."); + + private final JMenu editMenu = new JMenu("Edit"); + private final JMenuItem settings = new JMenuItem(PRODUCT_NAME + " Settings..."); + private final JMenuItem compareImages = new JMenuItem("Compare Images..."); + private final JMenu convertRom = new JMenu("Convert Image"); + private final JMenuItem convertIncrease = new JMenuItem("160KB --> 192KB..."); + private final JMenuItem convertDecrease = new JMenuItem("192KB --> 160KB..."); + private final ButtonGroup convertGroup = new ButtonGroup(); + + private final JMenu viewMenu = new JMenu("View"); + private final JMenuItem romProperties = new JMenuItem("ECU Image Properties"); + private final ButtonGroup levelGroup = new ButtonGroup(); + private final JMenu levelMenu = new JMenu("User Level"); + private final JRadioButtonMenuItem level1 = new JRadioButtonMenuItem("1 Beginner"); + private final JRadioButtonMenuItem level2 = new JRadioButtonMenuItem("2 Intermediate"); + private final JRadioButtonMenuItem level3 = new JRadioButtonMenuItem("3 Advanced"); + private final JRadioButtonMenuItem level4 = new JRadioButtonMenuItem("4 Highest"); + private final JRadioButtonMenuItem level5 = new JRadioButtonMenuItem("5 Debug Mode"); + +// private final JMenu loggerMenu = new JMenu("Logger"); +// private final JMenuItem openLogger = new JMenuItem("Launch Logger..."); + + private final JMenu ramTuneMenu = new JMenu("SSM"); + private final JMenuItem launchRamTuneTestApp = new JMenuItem("Launch Test App..."); + + private final JMenu helpMenu = new JMenu("Help"); + private final JMenuItem about = new JMenuItem("About " + PRODUCT_NAME); + + public ECUEditorMenuBar() { + // file menu items + add(fileMenu); + fileMenu.setMnemonic('F'); + + fileMenu.add(openImage); + openImage.addActionListener(this); + openImage.setMnemonic('O'); + + //fileMenu.add(openImages); + //openImages.addActionListener(this); + //openImages.setMnemonic('I'); + + fileMenu.add(saveImage); + saveImage.addActionListener(this); + saveImage.setMnemonic('S'); + + fileMenu.add(saveAsRepository); + saveAsRepository.setMnemonic('D'); + saveAsRepository.addActionListener(this); + + fileMenu.add(refreshImage); + refreshImage.addActionListener(this); + refreshImage.setMnemonic('R'); + + fileMenu.add(new JSeparator()); + + fileMenu.add(closeImage); + closeImage.addActionListener(this); + closeImage.setMnemonic('C'); + + //fileMenu.add(closeAll); + //closeAll.addActionListener(this); + //closeAll.setMnemonic('A'); + + fileMenu.add(new JSeparator()); + + fileMenu.add(exit); + exit.addActionListener(this); + exit.setMnemonic('X'); + + // edit menu items + add(editMenu); + editMenu.setMnemonic('E'); + + editMenu.add(settings); + settings.addActionListener(this); + settings.setMnemonic('S'); + + editMenu.add(compareImages); + compareImages.addActionListener(this); + compareImages.setMnemonic('C'); + + editMenu.add(convertRom); + convertRom.setMnemonic('O'); + + convertRom.add(convertIncrease); + convertIncrease.addActionListener(this); + convertIncrease.setMnemonic('I'); + + convertRom.add(convertDecrease); + convertDecrease.addActionListener(this); + convertDecrease.setMnemonic('D'); + + convertGroup.add(convertIncrease); + convertGroup.add(convertDecrease); + + // ecu def menu items + add(definitionMenu); + definitionMenu.setMnemonic('D'); + + definitionMenu.add(defManager); + defManager.addActionListener(this); + defManager.setMnemonic('D'); + + definitionMenu.add(updateDefinition); + updateDefinition.addActionListener(this); + updateDefinition.setMnemonic('U'); + + //definitionMenu.add(editDefinition); + //editDefinition.setMnemonic('E'); + //editDefinition.addActionListener(this); + + // view menu items + add(viewMenu); + viewMenu.setMnemonic('V'); + + viewMenu.add(romProperties); + romProperties.addActionListener(this); + romProperties.setMnemonic('P'); + + viewMenu.add(levelMenu); + levelMenu.setMnemonic('U'); + + levelMenu.add(level1); + level1.addActionListener(this); + level1.setMnemonic('1'); + + levelMenu.add(level2); + level2.addActionListener(this); + level2.setMnemonic('2'); + + levelMenu.add(level3); + level3.addActionListener(this); + level3.setMnemonic('3'); + + levelMenu.add(level4); + level4.addActionListener(this); + level4.setMnemonic('4'); + + levelMenu.add(level5); + level5.addActionListener(this); + level5.setMnemonic('5'); + + levelGroup.add(level1); + levelGroup.add(level2); + levelGroup.add(level3); + levelGroup.add(level4); + levelGroup.add(level5); + + // select correct userlevel button + if (getSettings().getUserLevel() == 1) { + level1.setSelected(true); + } else if (getSettings().getUserLevel() == 2) { + level2.setSelected(true); + } else if (getSettings().getUserLevel() == 3) { + level3.setSelected(true); + } else if (getSettings().getUserLevel() == 4) { + level4.setSelected(true); + } else if (getSettings().getUserLevel() == 5) { + level5.setSelected(true); + } + + // logger menu items +// add(loggerMenu); +// loggerMenu.setMnemonic('L'); +// +// loggerMenu.add(openLogger); +// openLogger.addActionListener(this); +// openLogger.setMnemonic('O'); + + // ramtune menu items + add(ramTuneMenu); + ramTuneMenu.setMnemonic('R'); + + ramTuneMenu.add(launchRamTuneTestApp); + launchRamTuneTestApp.addActionListener(this); + launchRamTuneTestApp.setMnemonic('L'); + + // help menu items + add(helpMenu); + helpMenu.setMnemonic('H'); + + helpMenu.add(about); + about.addActionListener(this); + about.setMnemonic('A'); + + updateMenu(); + } + + public void updateMenu() { + String file = getLastSelectedRomFileName(); + if ("".equals(file)) { + saveImage.setEnabled(false); + saveAsRepository.setEnabled(false); + closeImage.setEnabled(false); + //closeAll.setEnabled(false); + romProperties.setEnabled(false); + saveImage.setText("Save As..."); + saveAsRepository.setText("Save As Repository..."); + compareImages.setEnabled(false); + convertRom.setEnabled(false); + } else { + saveImage.setEnabled(true); + saveAsRepository.setEnabled(true); + closeImage.setEnabled(true); + //closeAll.setEnabled(true); + romProperties.setEnabled(true); + saveImage.setText("Save " + file + " As..."); + saveAsRepository.setText("Save "+ file +" As Repository..."); + compareImages.setEnabled(true); + convertRom.setEnabled(true); + } + refreshImage.setText("Refresh " + file); + closeImage.setText("Close " + file); + romProperties.setText(file + "Properties"); + + int lastSelectedRomSize = 0; + Rom lastSelectedRom = ECUEditorManager.getECUEditor().getLastSelectedRom(); + if(null != lastSelectedRom) { + lastSelectedRomSize = lastSelectedRom.getRealFileSize(); + } + + if(Settings.SIXTEENBIT_SMALL_SIZE == lastSelectedRomSize) { + convertIncrease.setEnabled(true); + convertDecrease.setEnabled(false); + } else if (Settings.SIXTEENBIT_LARGE_SIZE == lastSelectedRomSize) { + convertIncrease.setEnabled(false); + convertDecrease.setEnabled(true); + } else { + convertIncrease.setEnabled(false); + convertDecrease.setEnabled(false); + } + + openImages.setEnabled(false); + editDefinition.setEnabled(false); + revalidate(); + } + + @Override + public void actionPerformed(ActionEvent e) { + ECUEditor parent = ECUEditorManager.getECUEditor(); + if (e.getSource() == openImage) { + try { + openImageDialog(); + } catch (Exception ex) { + showMessageDialog(parent, + new DebugPanel(ex, getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + + } else if (e.getSource() == openImages) { + try { + openImagesDialog(); + } catch (Exception ex) { + showMessageDialog(parent, + new DebugPanel(ex, getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + + } else if (e.getSource() == saveImage) { + try { + this.saveImage(); + } catch (Exception ex) { + showMessageDialog(parent, + new DebugPanel(ex, getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + } else if (e.getSource() == saveAsRepository) { + try { + this.saveAsRepository(); + } catch(Exception ex) { + showMessageDialog(parent, + new DebugPanel(ex, getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + } else if (e.getSource() == closeImage) { + parent.closeImage(); + + } else if (e.getSource() == closeAll) { + parent.closeAllImages(); + + } else if (e.getSource() == exit) { + parent.handleExit(); + System.exit(0); + + } else if (e.getSource() == romProperties) { + showMessageDialog(parent, new RomPropertyPanel(parent.getLastSelectedRom()), + parent.getLastSelectedRom().getRomIDString() + " Properties", INFORMATION_MESSAGE); + + } else if (e.getSource() == refreshImage) { + try { + refreshImage(); + } catch (Exception ex) { + showMessageDialog(parent, new DebugPanel(ex, + getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + + } else if (e.getSource() == settings) { + SettingsForm form = new SettingsForm(); + form.setLocationRelativeTo(parent); + form.setVisible(true); + + } else if (e.getSource() == compareImages){ + CompareImagesForm form = new CompareImagesForm(parent.getImages(), parent.getIconImage()); + form.setLocationRelativeTo(parent); + form.setVisible(true); + + } else if (e.getSource() == convertIncrease) { + try { + increaseRomSize(); + refreshImage(); + } catch (Exception ex) { + showMessageDialog(parent, + new DebugPanel(ex, getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + + } else if (e.getSource() == convertDecrease) { + try { + decreaseRomSize(); + refreshImage(); + } catch (Exception ex) { + showMessageDialog(parent, + new DebugPanel(ex, getSettings().getSupportURL()), "Exception", ERROR_MESSAGE); + } + + } else if (e.getSource() == defManager) { + DefinitionManager form = new DefinitionManager(); + form.setLocationRelativeTo(parent); + form.setVisible(true); + + } else if (e.getSource() == level1) { + parent.setUserLevel(1); + + } else if (e.getSource() == level2) { + parent.setUserLevel(2); + + } else if (e.getSource() == level3) { + parent.setUserLevel(3); + + } else if (e.getSource() == level4) { + parent.setUserLevel(4); + + } else if (e.getSource() == level5) { + parent.setUserLevel(5); + +// } else if (e.getSource() == openLogger) { +// parent.launchLogger(); + } else if (e.getSource() == updateDefinition) { + BrowserControl.displayURL(ECU_DEFS_URL); + +// } else if (e.getSource() == launchRamTuneTestApp) { +// RamTuneTestApp.startTestApp(DISPOSE_ON_CLOSE); + + } else if (e.getSource() == about) { + //TODO: change this to use com.romraider.swing.menubar.action.AboutAction + String message = PRODUCT_NAME + " - ECU Editor\n" + + "Version: " + VERSION + "\n" + + "Build #: " + BUILDNUMBER + "\n" + + SUPPORT_URL; + String title = "About " + PRODUCT_NAME; + showMessageDialog(parent, message, title, INFORMATION_MESSAGE, ABOUT_ICON); + } + } + + public void refreshImage() throws Exception { + ECUEditor parent = ECUEditorManager.getECUEditor(); + if (parent.getLastSelectedRom() != null) { + File file = parent.getLastSelectedRom().getFullFileName(); + parent.closeImage(); + parent.openImage(file); + } + } + + public void openImageDialog() throws Exception { + ECUEditor parent = ECUEditorManager.getECUEditor(); + JFileChooser fc = new JFileChooser(SettingsManager.getSettings().getLastImageDir()); + fc.setFileFilter(new ECUImageFilter()); + fc.setDialogTitle("Open Image"); + + if (fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { + parent.openImage(fc.getSelectedFile()); + SettingsManager.getSettings().setLastImageDir(fc.getCurrentDirectory()); + } + } + + public void openImagesDialog() throws Exception { + ECUEditor parent = ECUEditorManager.getECUEditor(); + JFileChooser fc = new JFileChooser(getSettings().getLastImageDir()); + fc.setFileFilter(new ECUImageFilter()); + fc.setMultiSelectionEnabled(true); + fc.setDialogTitle("Open Image(s)"); + + if(fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { + parent.openImages(fc.getSelectedFiles()); + SettingsManager.getSettings().setLastImageDir(fc.getCurrentDirectory()); + } + } + + public void saveImage() throws Exception { + Rom lastSelectedRom = ECUEditorManager.getECUEditor().getLastSelectedRom(); + if (lastSelectedRom != null) { + File selectedFile = getImageOutputFile(); + if(null != selectedFile){ + byte[] output = lastSelectedRom.saveFile(); + this.writeImage(output, selectedFile); + } + } + } + + private File getImageOutputFile() throws Exception { + ECUEditor parent = ECUEditorManager.getECUEditor(); + JFileChooser fc = new JFileChooser(SettingsManager.getSettings().getLastImageDir()); + fc.setFileFilter(new ECUImageFilter()); + if (fc.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { + File selectedFile = fc.getSelectedFile(); + if (selectedFile.exists()) { + int option = showConfirmDialog(parent, selectedFile.getName() + " already exists! Overwrite?"); + + // option: 0 = Cancel, 1 = No + if (option == CANCEL_OPTION || option == 1) { + return null; + } + } + return selectedFile; + } + return null; + } + + private void writeImage(byte[] output, File selectedFile) throws Exception { + ECUEditor parent = ECUEditorManager.getECUEditor(); + FileOutputStream fos = new FileOutputStream(selectedFile); + try { + fos.write(output); + } finally { + fos.close(); + } + parent.getLastSelectedRom().setFullFileName(selectedFile.getAbsoluteFile()); + parent.setLastSelectedRom(parent.getLastSelectedRom()); + SettingsManager.getSettings().setLastImageDir(selectedFile.getParentFile()); + } + + private File getRepositoryOutputDir() { + JFileChooser fc = new JFileChooser(); + fc.setCurrentDirectory(getSettings().getLastRepositoryDir()); + fc.setDialogTitle("Select Repository Directory"); + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + + // disable the "All files" option + fc.setAcceptAllFileFilterUsed(false); + + if (fc.showSaveDialog(ECUEditorManager.getECUEditor()) == JFileChooser.APPROVE_OPTION) { + File selectedDir = fc.getSelectedFile(); + if (selectedDir.exists()) { + int option = showConfirmDialog(ECUEditorManager.getECUEditor(), selectedDir.getName() + " already exists! Overwrite?"); + + // option: 0 = Cancel, 1 = No + if (option == CANCEL_OPTION || option == 1) { + return null; + } + } + return selectedDir; + } + return null; + } + + private void saveAsRepository() throws Exception { + File selectedDir = getRepositoryOutputDir(); + String separator = System.getProperty("file.separator"); + + if(null != selectedDir) { + for(TableTreeNode treeNode : ECUEditorManager.getECUEditor().getLastSelectedRom().getTableNodes()) + { + Table table = treeNode.getTable(); + String category = table.getCategory(); + String tableName = table.getName(); + String tableDirString = selectedDir.getAbsolutePath() + separator + category; + File tableDir = new File(tableDirString.replace('/', '-')); + tableDir.mkdirs(); + String tableFileString = tableDir.getAbsolutePath() + separator + tableName+".txt"; + File tableFile = new File(tableFileString.replace('/', '-')); + + if(tableFile.exists()) + { + tableFile.delete(); + } + + tableFile.createNewFile(); + StringBuffer tableData = table.getTableAsString(); + BufferedWriter out = new BufferedWriter(new FileWriter(tableFile)); + try { + out.write(tableData.toString()); + } finally { + try { + out.close(); + } catch(Exception ex) { + ;// Do Nothing. + } + } + } + getSettings().setLastRepositoryDir(selectedDir); + } + } + + private void increaseRomSize() throws Exception{ + Rom lastSelectedRom = ECUEditorManager.getECUEditor().getLastSelectedRom(); + if (lastSelectedRom != null) { + File selectedFile = getImageOutputFile(); + if(null != selectedFile){ + if(lastSelectedRom.getRealFileSize() != Settings.SIXTEENBIT_SMALL_SIZE) + { + showMessageDialog(ECUEditorManager.getECUEditor(), "Error converting image. Image size is invalid."); + } else { + byte[] output = lastSelectedRom.saveFile(); + byte[] incOutput = new byte[Settings.SIXTEENBIT_LARGE_SIZE]; + System.arraycopy(output, 0, incOutput, 0, Settings.SIXTEENBIT_START_ADDRESS); + System.arraycopy(output, Settings.SIXTEENBIT_START_ADDRESS, incOutput, Settings.SIXTEENBIT_END_ADDRESS, Settings.SIXTEENBIT_SEGMENT_SIZE); + for(int i = Settings.SIXTEENBIT_START_ADDRESS; i < Settings.SIXTEENBIT_END_ADDRESS; i++) { + // Fill space. + incOutput[i] = Settings.SIXTEENBIT_SEGMENT_VALUE; + } + this.writeImage(incOutput, selectedFile); + } + } + } + } + + private void decreaseRomSize() throws Exception { + Rom lastSelectedRom = ECUEditorManager.getECUEditor().getLastSelectedRom(); + if (lastSelectedRom != null) { + File selectedFile = getImageOutputFile(); + if(null != selectedFile){ + if(lastSelectedRom.getRealFileSize() != Settings.SIXTEENBIT_LARGE_SIZE) + { + showMessageDialog(ECUEditorManager.getECUEditor(), "Error converting image. Image size is invalid."); + } else { + byte[] output =lastSelectedRom.saveFile(); + byte[] decOutput = new byte[Settings.SIXTEENBIT_SMALL_SIZE]; + System.arraycopy(output, 0, decOutput, 0, Settings.SIXTEENBIT_START_ADDRESS); + System.arraycopy(output, Settings.SIXTEENBIT_END_ADDRESS, decOutput, Settings.SIXTEENBIT_START_ADDRESS, Settings.SIXTEENBIT_SEGMENT_SIZE); + this.writeImage(decOutput, selectedFile); + } + } + } + } + + private String getLastSelectedRomFileName() { + Rom lastSelectedRom = ECUEditorManager.getECUEditor().getLastSelectedRom(); + return lastSelectedRom == null ? "" : lastSelectedRom.getFileName() + " "; + } + + private Settings getSettings() { + return SettingsManager.getSettings(); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/ECUEditorToolBar.java b/java_console/romraider/src/com/romraider/swing/ECUEditorToolBar.java new file mode 100644 index 0000000000..f95303a31c --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/ECUEditorToolBar.java @@ -0,0 +1,157 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static javax.swing.BorderFactory.createLineBorder; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Image; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.util.SettingsManager; + +public class ECUEditorToolBar extends JToolBar implements ActionListener { + + private static final long serialVersionUID = 7778170684606193919L; + private final JButton openImage = new JButton(); + private final JButton saveImage = new JButton(); + private final JButton refreshImage = new JButton(); + private final JButton closeImage = new JButton(); + + public ECUEditorToolBar(String name) { + super(name); + this.setFloatable(true); + this.setRollover(true); + FlowLayout toolBarLayout = new FlowLayout(FlowLayout.LEFT, 0, 0); + this.setLayout(toolBarLayout); + //this.setBorder(BorderFactory.createTitledBorder("Editor Tools")); + + this.updateIcons(); + + this.add(openImage); + this.add(saveImage); + this.add(closeImage); + this.add(refreshImage); + + openImage.setMaximumSize(new Dimension(58, 50)); + openImage.setBorder(createLineBorder(new Color(150, 150, 150), 0)); + saveImage.setMaximumSize(new Dimension(50, 50)); + saveImage.setBorder(createLineBorder(new Color(150, 150, 150), 0)); + closeImage.setMaximumSize(new Dimension(50, 50)); + closeImage.setBorder(createLineBorder(new Color(150, 150, 150), 0)); + refreshImage.setMaximumSize(new Dimension(50, 50)); + refreshImage.setBorder(createLineBorder(new Color(150, 150, 150), 0)); + + this.updateButtons(); + + openImage.addActionListener(this); + saveImage.addActionListener(this); + closeImage.addActionListener(this); + refreshImage.addActionListener(this); + } + + public void updateIcons() { + int iconScale = getSettings().getEditorIconScale(); + openImage.setIcon(rescaleImageIcon(new ImageIcon(getClass().getResource("/graphics/icon-open.png")), iconScale)); + saveImage.setIcon(rescaleImageIcon(new ImageIcon(getClass().getResource("/graphics/icon-save.png")), iconScale)); + refreshImage.setIcon(rescaleImageIcon(new ImageIcon(getClass().getResource("/graphics/icon-refresh.png")), iconScale)); + closeImage.setIcon(rescaleImageIcon(new ImageIcon( getClass().getResource("/graphics/icon-close.png")), iconScale)); + repaint(); + } + + private ImageIcon rescaleImageIcon(ImageIcon imageIcon, int percentOfOriginal) { + int newHeight = (int) (imageIcon.getImage().getHeight(this) * (percentOfOriginal * .01)); + int newWidth = (int) (imageIcon.getImage().getWidth(this) * (percentOfOriginal * .01)); + + if(newHeight > 0 && newWidth > 0) + { + imageIcon.setImage(imageIcon.getImage().getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH)); + } + return imageIcon; + } + + public void updateButtons() { + String file = getEditor().getLastSelectedRomFileName(); + + openImage.setToolTipText("Open Image"); + saveImage.setToolTipText("Save " + file + " As New Image..."); + refreshImage.setToolTipText("Refresh " + file + " from saved copy"); + closeImage.setToolTipText("Close " + file); + + if ("".equals(file)) { + saveImage.setEnabled(false); + refreshImage.setEnabled(false); + closeImage.setEnabled(false); + } else { + saveImage.setEnabled(true); + refreshImage.setEnabled(true); + closeImage.setEnabled(true); + } + revalidate(); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == openImage) { + try { + ((ECUEditorMenuBar) getEditor().getJMenuBar()).openImageDialog(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(getEditor(), new DebugPanel(ex, + getSettings().getSupportURL()), "Exception", JOptionPane.ERROR_MESSAGE); + } + } else if (e.getSource() == saveImage) { + try { + ((ECUEditorMenuBar) getEditor().getJMenuBar()).saveImage(); + getEditor().refreshUI(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(getEditor(), new DebugPanel(ex, + getSettings().getSupportURL()), "Exception", JOptionPane.ERROR_MESSAGE); + } + } else if (e.getSource() == closeImage) { + getEditor().closeImage(); + } else if (e.getSource() == refreshImage) { + try { + ((ECUEditorMenuBar) getEditor().getJMenuBar()).refreshImage(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(getEditor(), new DebugPanel(ex, + getSettings().getSupportURL()), "Exception", JOptionPane.ERROR_MESSAGE); + } + } + } + + private Settings getSettings() { + return SettingsManager.getSettings(); + } + + private ECUEditor getEditor() { + return ECUEditorManager.getECUEditor(); + } +} diff --git a/java_console/romraider/src/com/romraider/swing/ECUImageFilter.java b/java_console/romraider/src/com/romraider/swing/ECUImageFilter.java new file mode 100644 index 0000000000..118a02c516 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/ECUImageFilter.java @@ -0,0 +1,36 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.filechooser.FileFilter; +import java.io.File; + +public class ECUImageFilter extends FileFilter { + + private final FileFilter filter = new GenericFileFilter("ECU Image Files", "bin", "hex"); + + public boolean accept(File file) { + return filter.accept(file); + } + + public String getDescription() { + return filter.getDescription(); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/GenericFileFilter.java b/java_console/romraider/src/com/romraider/swing/GenericFileFilter.java new file mode 100644 index 0000000000..f19ff92128 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/GenericFileFilter.java @@ -0,0 +1,103 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.filechooser.FileFilter; +import java.io.File; +import java.util.Enumeration; +import java.util.Hashtable; + +public final class GenericFileFilter extends FileFilter { + + private final Hashtable filters = new Hashtable(); + private String description = null; + private String fullDescription = null; + private boolean useExtensionsInDescription = true; + + public GenericFileFilter(String description, String... extensions) { + setDescription(description); + for (String extension : extensions) { + addExtension(extension); + } + } + + public boolean accept(File f) { + if (f != null) { + if (f.isDirectory()) { + return true; + } + String extension = getExtension(f); + if (extension != null && filters.get(getExtension(f)) != null) { + return true; + } + } + return false; + } + + public String getExtension(File f) { + if (f != null) { + String filename = f.getName(); + int i = filename.lastIndexOf('.'); + if (i > 0 && i < filename.length() - 1) { + return filename.substring(i + 1).toLowerCase(); + } + } + return null; + } + + public void addExtension(String extension) { + filters.put(extension.toLowerCase(), this); + fullDescription = null; + } + + public String getDescription() { + if (fullDescription == null) { + if (description == null || isExtensionListInDescription()) { + fullDescription = description == null ? "(" : description + " ("; + // build the description from the extension list + Enumeration extensions = filters.keys(); + if (extensions != null) { + fullDescription += "." + extensions.nextElement(); + while (extensions.hasMoreElements()) { + fullDescription += ", ." + extensions.nextElement(); + } + } + fullDescription += ")"; + } else { + fullDescription = description; + } + } + return fullDescription; + } + + public void setDescription(String description) { + this.description = description; + fullDescription = null; + } + + public void setExtensionListInDescription(boolean b) { + useExtensionsInDescription = b; + fullDescription = null; + } + + public boolean isExtensionListInDescription() { + return useExtensionsInDescription; + } +} diff --git a/java_console/romraider/src/com/romraider/swing/JProgressPane.java b/java_console/romraider/src/com/romraider/swing/JProgressPane.java new file mode 100644 index 0000000000..106062a59e --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/JProgressPane.java @@ -0,0 +1,80 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JProgressBar; + +public class JProgressPane extends JPanel implements PropertyChangeListener{ + + private static final long serialVersionUID = -6827936662738014543L; + JLabel label = new JLabel(); + JProgressBar progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100); + String status = "ready"; + int percent = 0; + + public JProgressPane() { + + this.setPreferredSize(new Dimension(500, 18)); + this.setLayout(new BorderLayout(1, 2)); + label.setHorizontalAlignment(JLabel.CENTER); + label.setText(" Ready..."); + label.setFont(new Font("Tahoma", Font.PLAIN, 11)); + label.setHorizontalAlignment(JLabel.LEFT); + progressBar.setMinimumSize(new Dimension(200, 50)); + progressBar.setValue(0); + + this.add(progressBar, BorderLayout.WEST); + this.add(label, BorderLayout.CENTER); + + } + + public void update(String status, int percent) { + label.setText(" " + status); + progressBar.setValue(percent); + } + + public void setStatus(String status) { + this.status = status; + } + + public JProgressBar getProgressBar() { + return this.progressBar; + } + + @Override + public void propertyChange(PropertyChangeEvent evt) { + if("progress" == evt.getPropertyName()) { + int progress = (Integer) evt.getNewValue(); + progressBar.setValue(progress); + label.setText(" " + status); + } + else{ + ;// do nothing + } + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/JTableChooser.java b/java_console/romraider/src/com/romraider/swing/JTableChooser.java new file mode 100644 index 0000000000..09f59f3117 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/JTableChooser.java @@ -0,0 +1,122 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.Dimension; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Vector; + +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.ScrollPaneConstants; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; + +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.maps.Rom; +import com.romraider.maps.Table; + +public class JTableChooser extends JOptionPane implements MouseListener { + public JTableChooser() { + } + + private static final long serialVersionUID = 5611729002131147882L; + JPanel displayPanel = new JPanel(); + DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Open Images"); + JTree displayTree = new JTree(rootNode); + JScrollPane displayScrollPane; + + public Table showChooser(Table targetTable) { + Vector roms = ECUEditorManager.getECUEditor().getImages(); + int nameLength = 0; + + for (int i = 0; i < roms.size(); i++) { + Rom rom = roms.get(i); + DefaultMutableTreeNode romNode = new DefaultMutableTreeNode(rom.getFileName()); + rootNode.add(romNode); + + for (TableTreeNode tableTreeNode : rom.getTableNodes()) { + Table table = tableTreeNode.getTable(); + // use the length of the table name to set the width of the displayTree + // so the entire name can be read without being cut off on the right + if (table.getName().length() > nameLength) { + nameLength = table.getName().length(); + } + TableChooserTreeNode tableNode = new TableChooserTreeNode(table.getName(), table); + + // categories + boolean categoryExists = false; + for (int k = 0; k < romNode.getChildCount(); k++) { + if (romNode.getChildAt(k).toString().equalsIgnoreCase(table.getCategory())) { + ((DefaultMutableTreeNode) romNode.getChildAt(k)).add(tableNode); + categoryExists = true; + break; + } + } + + if (!categoryExists) { + DefaultMutableTreeNode categoryNode = new DefaultMutableTreeNode(table.getCategory()); + romNode.add(categoryNode); + categoryNode.add(tableNode); + } + } + } + + displayTree.setPreferredSize(new Dimension(nameLength*7, 400)); + displayTree.setMinimumSize(new Dimension(nameLength*7, 400)); + + displayTree.expandPath(new TreePath(rootNode.getPath())); + displayTree.setRootVisible(false); + + displayTree.addMouseListener(this); + displayScrollPane = new JScrollPane(displayTree); + displayScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + displayPanel.add(displayScrollPane); + + Object[] values = {"Compare", "Cancel"}; + + if ((showOptionDialog(SwingUtilities.windowForComponent(targetTable), displayPanel, "Select a Map", JOptionPane.DEFAULT_OPTION, + JOptionPane.PLAIN_MESSAGE, null, values, values[0]) == 0 + && (displayTree.getLastSelectedPathComponent() instanceof TableChooserTreeNode))) { + return ((TableChooserTreeNode) displayTree.getLastSelectedPathComponent()).getTable(); + } else { + return null; + } + } + + @Override + public void mouseReleased(MouseEvent e) { + displayTree.setPreferredSize(new Dimension(displayTree.getWidth(), (displayTree.getRowCount()*displayTree.getRowHeight()))); + displayTree.revalidate(); + } + @Override + public void mouseClicked(MouseEvent e){} + @Override + public void mouseEntered(MouseEvent e){} + @Override + public void mouseExited(MouseEvent e){} + @Override + public void mousePressed(MouseEvent e){} + +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/LookAndFeelManager.java b/java_console/romraider/src/com/romraider/swing/LookAndFeelManager.java new file mode 100644 index 0000000000..0f91ca7f90 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/LookAndFeelManager.java @@ -0,0 +1,69 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static com.romraider.Version.PRODUCT_NAME; +import static com.romraider.util.Platform.LINUX; +import static com.romraider.util.Platform.MAC_OS_X; +import static com.romraider.util.Platform.isPlatform; +import static javax.swing.UIManager.getCrossPlatformLookAndFeelClassName; +import static javax.swing.UIManager.getSystemLookAndFeelClassName; +import static javax.swing.UIManager.setLookAndFeel; + +import javax.swing.JDialog; +import javax.swing.JFrame; + +import org.apache.log4j.Logger; + +public final class LookAndFeelManager { + private static final Logger LOGGER = Logger.getLogger(LookAndFeelManager.class); + + private LookAndFeelManager() { + throw new UnsupportedOperationException(); + } + + public static void initLookAndFeel() { + try { + if (isPlatform(MAC_OS_X)) { + System.setProperty("apple.awt.rendering", "true"); + System.setProperty("apple.awt.brushMetalLook", "true"); + System.setProperty("apple.laf.useScreenMenuBar", "true"); + System.setProperty("apple.awt.window.position.forceSafeCreation", "true"); + System.setProperty("com.apple.mrj.application.apple.menu.about.name", PRODUCT_NAME); + } + + setLookAndFeel(getLookAndFeel()); + + // make sure we have nice window decorations. + JFrame.setDefaultLookAndFeelDecorated(true); + JDialog.setDefaultLookAndFeelDecorated(true); + + } catch (Exception ex) { + LOGGER.error("Error loading system look and feel.", ex); + } + } + + private static String getLookAndFeel() { +// if (true) return "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; + // Linux has issues with the gtk look and feel themes. + if (isPlatform(LINUX)) return getCrossPlatformLookAndFeelClassName(); + return getSystemLookAndFeelClassName(); + } +} diff --git a/java_console/romraider/src/com/romraider/swing/MDIDesktopPane.java b/java_console/romraider/src/com/romraider/swing/MDIDesktopPane.java new file mode 100644 index 0000000000..6e0516ffcc --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/MDIDesktopPane.java @@ -0,0 +1,295 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.Point; +import java.beans.PropertyVetoException; + +import javax.swing.DefaultDesktopManager; +import javax.swing.JComponent; +import javax.swing.JDesktopPane; +import javax.swing.JInternalFrame; +import javax.swing.JScrollPane; +import javax.swing.JViewport; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.util.SettingsManager; + +/** + * An extension of WDesktopPane that supports often used MDI functionality. This + * class also handles setting scroll bars for when windows move too far to the left or + * bottom, providing the MDIDesktopPane is in a ScrollPane. + */ +public class MDIDesktopPane extends JDesktopPane { + + private static final long serialVersionUID = -1839360490978587035L; + private final MDIDesktopManager manager; + + public MDIDesktopPane() { + manager = new MDIDesktopManager(this); + setDesktopManager(manager); + setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); + } + + @Override + public void setBounds(int x, int y, int w, int h) { + super.setBounds(x, y, w, h); + checkDesktopSize(); + } + + public Component add(JInternalFrame frame) { + Point p; + int w; + int h; + + // get frame location. + if(SettingsManager.getSettings().isAlwaysOpenTableAtZero()) { + p = new Point(0, 0); + } else { + if (getAllFrames().length > 0) { + JInternalFrame selectedFrame = getSelectedFrame(); + if(null == selectedFrame || !selectedFrame.isVisible()) { + // if none selected get the location at index 0. + p = getAllFrames()[0].getLocation(); + } else { + // get the selected frame location and open off of that location. + p = selectedFrame.getLocation(); + } + + p.x = p.x + Settings.FRAME_OFFSET; + p.y = p.y + Settings.FRAME_OFFSET; + } else { + p = new Point(0, 0); + } + } + + Component retval = super.add(frame); + frame.setLocation(p.x, p.y); + + checkDesktopSize(); + + if (frame.isResizable()) { + w = getWidth() - (getWidth() / 3); + h = getHeight() - (getHeight() / 3); + if (w < frame.getMinimumSize().getWidth()) { + w = (int) frame.getMinimumSize().getWidth(); + } + if (h < frame.getMinimumSize().getHeight()) { + h = (int) frame.getMinimumSize().getHeight(); + } + frame.setSize(w, h); + } + + moveToFront(frame); + frame.setVisible(true); + + if(frame instanceof TableFrame) { + getEditor().getTableToolBar().updateTableToolBar(); + ((TableFrame) frame).RegisterTable(); + } + + try { + frame.setSelected(true); + } catch (PropertyVetoException e) { + frame.toBack(); + } + + return retval; + } + + @Override + public void remove(Component c) { + super.remove(c); + getEditor().getTableToolBar().updateTableToolBar(); + checkDesktopSize(); + } + + public ECUEditor getEditor() { + return ECUEditorManager.getECUEditor(); + } + + /** + * Cascade all internal frames + */ + public void cascadeFrames() { + int x = 0; + int y = 0; + JInternalFrame allFrames[] = getAllFrames(); + + manager.setNormalSize(); + int frameHeight = (getBounds().height - 5) - allFrames.length * Settings.FRAME_OFFSET; + int frameWidth = (getBounds().width - 5) - allFrames.length * Settings.FRAME_OFFSET; + for (int i = allFrames.length - 1; i >= 0; i--) { + allFrames[i].setSize(frameWidth, frameHeight); + allFrames[i].setLocation(x, y); + x = x + Settings.FRAME_OFFSET; + y = y + Settings.FRAME_OFFSET; + } + } + + /** + * Tile all internal frames + */ + public void tileFrames() { + java.awt.Component allFrames[] = getAllFrames(); + manager.setNormalSize(); + int frameHeight = getBounds().height / allFrames.length; + int y = 0; + for (int i = 0; i < allFrames.length; i++) { + allFrames[i].setSize(getBounds().width, frameHeight); + allFrames[i].setLocation(0, y); + y = y + frameHeight; + } + } + + /** + * Sets all component size properties ( maximum, minimum, preferred) + * to the given dimension. + */ + public void setAllSize(Dimension d) { + setMinimumSize(d); + setMaximumSize(d); + setPreferredSize(d); + } + + /** + * Sets all component size properties ( maximum, minimum, preferred) + * to the given width and height. + */ + public void setAllSize(int width, int height) { + setAllSize(new Dimension(width, height)); + } + + private void checkDesktopSize() { + if (getParent() != null && isVisible()) { + manager.resizeDesktop(); + } + } +} + +/** + * Private class used to replace the standard DesktopManager for JDesktopPane. + * Used to provide scrollbar functionality. + */ +class MDIDesktopManager extends DefaultDesktopManager { + /** + * + */ + private static final long serialVersionUID = -7668105643849176819L; + private final MDIDesktopPane desktop; + + public MDIDesktopManager(MDIDesktopPane desktop) { + this.desktop = desktop; + } + + @Override + public void endResizingFrame(JComponent f) { + super.endResizingFrame(f); + resizeDesktop(); + } + + @Override + public void endDraggingFrame(JComponent f) { + super.endDraggingFrame(f); + resizeDesktop(); + } + + public void setNormalSize() { + JScrollPane scrollPane = getScrollPane(); + int x = 0; + int y = 0; + Insets scrollInsets = getScrollPaneInsets(); + + if (scrollPane != null) { + Dimension d = scrollPane.getVisibleRect().getSize(); + if (scrollPane.getBorder() != null) { + d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, + d.getHeight() - scrollInsets.top - scrollInsets.bottom); + } + + d.setSize(d.getWidth() - 20, d.getHeight() - 20); + desktop.setAllSize(x, y); + scrollPane.revalidate(); + } + } + + public MDIDesktopPane getDesktop() + { + return this.desktop; + } + + private Insets getScrollPaneInsets() { + JScrollPane scrollPane = getScrollPane(); + if (scrollPane == null) { + return new Insets(0, 0, 0, 0); + } else { + return getScrollPane().getBorder().getBorderInsets(scrollPane); + } + } + + private JScrollPane getScrollPane() { + if (desktop.getParent() instanceof JViewport) { + JViewport viewPort = (JViewport) desktop.getParent(); + if (viewPort.getParent() instanceof JScrollPane) { + return (JScrollPane) viewPort.getParent(); + } + } + return null; + } + + protected void resizeDesktop() { + int x = 0; + int y = 0; + JScrollPane scrollPane = getScrollPane(); + Insets scrollInsets = getScrollPaneInsets(); + + if (scrollPane != null) { + JInternalFrame allFrames[] = desktop.getAllFrames(); + for (int i = 0; i < allFrames.length; i++) { + if (allFrames[i].getX() + allFrames[i].getWidth() > x) { + x = allFrames[i].getX() + allFrames[i].getWidth(); + } + if (allFrames[i].getY() + allFrames[i].getHeight() > y) { + y = allFrames[i].getY() + allFrames[i].getHeight(); + } + } + Dimension d = scrollPane.getVisibleRect().getSize(); + if (scrollPane.getBorder() != null) { + d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, + d.getHeight() - scrollInsets.top - scrollInsets.bottom); + } + + if (x <= d.getWidth()) { + x = ((int) d.getWidth()) - 20; + } + if (y <= d.getHeight()) { + y = ((int) d.getHeight()) - 20; + } + desktop.setAllSize(x, y); + scrollPane.invalidate(); + scrollPane.validate(); + } + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/ParameterIdsTableModel.java b/java_console/romraider/src/com/romraider/swing/ParameterIdsTableModel.java new file mode 100644 index 0000000000..c2d145ee36 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/ParameterIdsTableModel.java @@ -0,0 +1,79 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.util.Map; + +import javax.swing.table.DefaultTableModel; + +public final class ParameterIdsTableModel extends DefaultTableModel { + private static final long serialVersionUID = -9125596053556735977L; + private static final String[] colNames = { + "Parameter Name", "Logger ID"}; + private Map parameterList; + + @Override + public final int getColumnCount() { + return colNames.length; + } + + @Override + public final String getColumnName(int column) { + return colNames[column]; + } + + @Override + public final Object getValueAt(int row, int column) { + if (null != parameterList) { + final String key = (String) parameterList.keySet().toArray()[row]; + final String value = parameterList.get(key); + switch (column) { + case 0: + return key; + case 1: + return value; + default: + return null; + } + } + else { + return null; + } + } + + @Override + public final int getRowCount() { + return (null != parameterList) ? parameterList.size() : 0; + } + + @Override + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + @Override + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setParameterList(Map parameterList) { + this.parameterList = parameterList; + } +} diff --git a/java_console/romraider/src/com/romraider/swing/RomCellRenderer.java b/java_console/romraider/src/com/romraider/swing/RomCellRenderer.java new file mode 100644 index 0000000000..95412f7716 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/RomCellRenderer.java @@ -0,0 +1,151 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static javax.swing.BorderFactory.createLineBorder; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridLayout; + +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.TreeCellRenderer; + +import com.romraider.Settings; +import com.romraider.maps.Rom; +import com.romraider.maps.Table; + +public class RomCellRenderer implements TreeCellRenderer { + + JLabel fileName; + JLabel carInfo; + DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer(); + + public RomCellRenderer() { + fileName = new JLabel(" "); + fileName.setFont(new Font("Tahoma", Font.BOLD, 11)); + fileName.setHorizontalAlignment(JLabel.CENTER); + + carInfo = new JLabel(" "); + carInfo.setFont(new Font("Tahoma", Font.PLAIN, 10)); + carInfo.setHorizontalAlignment(JLabel.CENTER); + + } + + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, + boolean selected, boolean expanded, boolean leaf, int row, + boolean hasFocus) { + + Component returnValue = null; + + if (value != null && value instanceof Rom) { + Rom rom = ((Rom) value); + + if (expanded) { + fileName.setText("- " + rom.getFileName()); + } else { + fileName.setText("+ " + rom.getFileName()); + } + + + carInfo.setText(rom.getRomIDString() + ", " + + rom.getRomID().getCaseId() + "; " + + rom.getRomID().getYear() + " " + + rom.getRomID().getMake() + " " + + rom.getRomID().getModel() + " " + + rom.getRomID().getSubModel() + ", " + + rom.getRomID().getTransmission() + ); + + JPanel renderer = new JPanel(new GridLayout(2, 1)); + renderer.add(fileName); + renderer.add(carInfo); + + if (selected) { + renderer.setBackground(new Color(220, 220, 255)); + renderer.setBorder(createLineBorder(new Color(0, 0, 225))); + + } else { + renderer.setBorder(createLineBorder(new Color(220, 0, 0))); + renderer.setBackground(new Color(255, 210, 210)); + } + + renderer.setPreferredSize(new Dimension(tree.getParent().getWidth(), 30)); + renderer.setMaximumSize(new Dimension(tree.getParent().getWidth(), 30)); + renderer.setEnabled(tree.isEnabled()); + returnValue = renderer; + } else if (value != null && value instanceof TableTreeNode) { + + Table table = ((TableFrame)((DefaultMutableTreeNode) value).getUserObject()).getTable(); + JPanel renderer = new JPanel(new GridLayout(1, 1)); + renderer.setBorder(createLineBorder(Color.WHITE)); + JLabel tableName = new JLabel(""); + renderer.setBackground(Color.WHITE); + + // display icon + if (table.getType() == Settings.TABLE_1D) { + tableName = new JLabel(table.getName() + " ", new ImageIcon(getClass().getResource("/graphics/1d.gif")), JLabel.LEFT); + } else if (table.getType() == Settings.TABLE_2D) { + tableName = new JLabel(table.getName() + " ", new ImageIcon(getClass().getResource("/graphics/2d.gif")), JLabel.LEFT); + } else if (table.getType() == Settings.TABLE_3D) { + tableName = new JLabel(table.getName() + " ", new ImageIcon(getClass().getResource("/graphics/3d.gif")), JLabel.LEFT); + } else if (table.getType() == Settings.TABLE_SWITCH) { + tableName = new JLabel(table.getName() + " ", new ImageIcon(getClass().getResource("/graphics/switch.gif")), JLabel.LEFT); + } + + // set color + renderer.add(tableName); + tableName.setFont(new Font("Tahoma", Font.PLAIN, 11)); + + if (selected) { + renderer.setBackground(new Color(220, 220, 255)); + renderer.setBorder(createLineBorder(new Color(0, 0, 225))); + } + + if (table.getUserLevel() == 5) { + tableName.setForeground(new Color(255, 150, 150)); + tableName.setFont(new Font("Tahoma", Font.ITALIC, 11)); + + } else if (table.getUserLevel() > table.getSettings().getUserLevel()) { + //tableName.setForeground(new Color(185, 185, 185)); + tableName.setFont(new Font("Tahoma", Font.ITALIC, 11)); + + } + + returnValue = renderer; + } + + if (returnValue == null) { + returnValue = defaultRenderer.getTreeCellRendererComponent(tree, + value, selected, expanded, leaf, row, hasFocus); + } + + return returnValue; + + } +} diff --git a/java_console/romraider/src/com/romraider/swing/RomPropertyPanel.java b/java_console/romraider/src/com/romraider/swing/RomPropertyPanel.java new file mode 100644 index 0000000000..898ba53821 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/RomPropertyPanel.java @@ -0,0 +1,305 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import com.romraider.maps.Rom; + +public class RomPropertyPanel extends javax.swing.JPanel { + + private static final long serialVersionUID = 5583360728106071942L; + Rom rom = new Rom(); + + public RomPropertyPanel(Rom rom) { + initComponents(); + + // populate fields + fileName.setText(rom.getFileName()); + xmlID.setText(rom.getRomID().getXmlid()); + ecuVersion.setText(rom.getRomID().getCaseId()); + fileSize.setText((rom.getRealFileSize() / 1024) + "kb"); + internalID.setText(rom.getRomID().getInternalIdString()); + storageAddress.setText("0x" + Integer.toHexString(rom.getRomID().getInternalIdAddress())); + + make.setText(rom.getRomID().getMake()); + market.setText(rom.getRomID().getMarket()); + year.setText(rom.getRomID().getYear() + ""); + model.setText(rom.getRomID().getModel()); + submodel.setText(rom.getRomID().getSubModel()); + transmission.setText(rom.getRomID().getTransmission()); + editStamp.setText(rom.getRomID().getEditStamp()); + + tableList.setListData(rom.getTables()); + } + + // //GEN-BEGIN:initComponents + private void initComponents() { + lblFilename = new javax.swing.JLabel(); + fileName = new javax.swing.JLabel(); + lblECURevision = new javax.swing.JLabel(); + xmlID = new javax.swing.JLabel(); + lblFilesize = new javax.swing.JLabel(); + fileSize = new javax.swing.JLabel(); + lblEcuVersion = new javax.swing.JLabel(); + ecuVersion = new javax.swing.JLabel(); + lblInternalId = new javax.swing.JLabel(); + internalID = new javax.swing.JLabel(); + lblStorageAddress = new javax.swing.JLabel(); + storageAddress = new javax.swing.JLabel(); + lblMake = new javax.swing.JLabel(); + lblMarket = new javax.swing.JLabel(); + lblTransmission = new javax.swing.JLabel(); + lblModel = new javax.swing.JLabel(); + lblSubmodel = new javax.swing.JLabel(); + lblYear = new javax.swing.JLabel(); + make = new javax.swing.JLabel(); + market = new javax.swing.JLabel(); + year = new javax.swing.JLabel(); + model = new javax.swing.JLabel(); + submodel = new javax.swing.JLabel(); + transmission = new javax.swing.JLabel(); + jScrollPane1 = new javax.swing.JScrollPane(); + tableList = new javax.swing.JList(); + lblTables = new javax.swing.JLabel(); + lblEditStamp = new javax.swing.JLabel(); + editStamp = new javax.swing.JLabel(); + + lblEditStamp.setText("Edit Stamp:"); + + editStamp.setText("stamp"); + + lblFilename.setText("Filename:"); + + fileName.setText("Filename"); + + lblECURevision.setText("ECU Revision:"); + + xmlID.setText("XMLID"); + + lblFilesize.setText("Filesize:"); + + fileSize.setText("999kb"); + + lblEcuVersion.setText("ECU Version:"); + + ecuVersion.setText("ECUVER"); + + lblInternalId.setText("Internal ID:"); + + internalID.setText("INTERNAL"); + + lblStorageAddress.setText("ID Storage Address:"); + + storageAddress.setText("0x00"); + + lblMake.setText("Make:"); + + lblMarket.setText("Market:"); + + lblTransmission.setText("Transmission:"); + + lblModel.setText("Model:"); + + lblSubmodel.setText("Submodel:"); + + lblYear.setText("Year:"); + + make.setText("Make"); + + market.setText("Market"); + + year.setText("Year"); + + model.setText("Model"); + + submodel.setText("Submodel"); + + transmission.setText("Transmission"); + + tableList.setModel(new javax.swing.AbstractListModel() { + /** + * + */ + private static final long serialVersionUID = -8498656966410761726L; + String[] strings = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}; + + public int getSize() { + return strings.length; + } + + public Object getElementAt(int i) { + return strings[i]; + } + }); + jScrollPane1.setViewportView(tableList); + + lblTables.setText("Tables:"); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .addContainerGap() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(lblFilename) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(fileName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 302, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .add(layout.createSequentialGroup() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(lblECURevision) + .add(lblEcuVersion) + .add(lblFilesize)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(fileSize) + .add(ecuVersion) + .add(xmlID))) + .add(layout.createSequentialGroup() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(lblYear) + .add(lblModel) + .add(lblSubmodel) + .add(lblTransmission) + .add(lblMarket) + .add(lblMake)) + .add(7, 7, 7) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(make) + .add(market) + .add(year) + .add(layout.createSequentialGroup() + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(transmission) + .add(submodel))) + .add(model)))) + .add(32, 32, 32) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(lblInternalId) + .add(lblStorageAddress) + .add(lblEditStamp)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 53, Short.MAX_VALUE) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(internalID) + .add(storageAddress) + .add(editStamp)) + .add(36, 36, 36)) + .add(lblTables) + .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 226, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() + .add(21, 21, 21) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblFilename) + .add(fileName)) + .add(layout.createSequentialGroup() + .add(40, 40, 40) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblECURevision) + .add(xmlID) + .add(lblInternalId) + .add(internalID)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ecuVersion) + .add(lblEcuVersion) + .add(storageAddress) + .add(lblStorageAddress)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblFilesize) + .add(fileSize) + .add(lblEditStamp) + .add(editStamp)))) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(lblTables) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblMake) + .add(make)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblMarket) + .add(market)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblYear) + .add(year)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblModel) + .add(model)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblSubmodel) + .add(submodel)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblTransmission) + .add(transmission))) + .add(jScrollPane1, 0, 0, Short.MAX_VALUE)) + .addContainerGap()) + ); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JLabel ecuVersion; + private javax.swing.JLabel fileName; + private javax.swing.JLabel fileSize; + private javax.swing.JLabel internalID; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JLabel lblECURevision; + private javax.swing.JLabel lblEcuVersion; + private javax.swing.JLabel lblFilename; + private javax.swing.JLabel lblFilesize; + private javax.swing.JLabel lblInternalId; + private javax.swing.JLabel lblMake; + private javax.swing.JLabel lblMarket; + private javax.swing.JLabel lblModel; + private javax.swing.JLabel lblStorageAddress; + private javax.swing.JLabel lblSubmodel; + private javax.swing.JLabel lblTables; + private javax.swing.JLabel lblTransmission; + private javax.swing.JLabel lblYear; + private javax.swing.JLabel make; + private javax.swing.JLabel market; + private javax.swing.JLabel model; + private javax.swing.JLabel storageAddress; + private javax.swing.JLabel submodel; + private javax.swing.JList tableList; + private javax.swing.JLabel transmission; + private javax.swing.JLabel xmlID; + private javax.swing.JLabel year; + private javax.swing.JLabel lblEditStamp; + private javax.swing.JLabel editStamp; + // End of variables declaration//GEN-END:variables + +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/RomTree.java b/java_console/romraider/src/com/romraider/swing/RomTree.java new file mode 100644 index 0000000000..ea5231e560 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/RomTree.java @@ -0,0 +1,142 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JTree; +import javax.swing.KeyStroke; +import javax.swing.tree.DefaultMutableTreeNode; + +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.maps.Rom; +import com.romraider.util.SettingsManager; + +public class RomTree extends JTree implements MouseListener { + + private static final long serialVersionUID = 1630446543383498886L; + + public RomTree(DefaultMutableTreeNode input) { + super(input); + setRootVisible(false); + setRowHeight(0); + addMouseListener(this); + setCellRenderer(new RomCellRenderer()); + setFont(new Font("Tahoma", Font.PLAIN, 11)); + + // key binding actions + Action tableSelectAction = new AbstractAction() { + private static final long serialVersionUID = -6008026264821746092L; + + @Override + public void actionPerformed(ActionEvent e) { + try{ + Object selectedRow = getSelectionPath().getLastPathComponent(); + showTable(selectedRow); + setLastSelectedRom(selectedRow); + }catch(NullPointerException ex) { + } + } + }; + + this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); + this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "space"); + this.getActionMap().put("enter", tableSelectAction); + this.getActionMap().put("space", tableSelectAction); + } + + public ECUEditor getEditor() { + return ECUEditorManager.getECUEditor(); + } + + @Override + public void mouseClicked(MouseEvent e) { + try{ + Object selectedRow = getPathForLocation(e.getX(), e.getY()).getLastPathComponent(); + + if(selectedRow instanceof TableTreeNode) { + if (e.getClickCount() >= SettingsManager.getSettings().getTableClickCount()) { + showTable(selectedRow); + } + } else if(selectedRow instanceof Rom || selectedRow instanceof CategoryTreeNode) { + if (e.getClickCount() >= SettingsManager.getSettings().getTableClickCount()) { + if(isCollapsed(getRowForLocation(e.getX(),e.getY()))) { + expandRow(getRowForLocation(e.getX(),e.getY())); + } + else { + collapseRow(getRowForLocation(e.getX(),e.getY())); + } + } + } + + setLastSelectedRom(selectedRow); + }catch(NullPointerException ex) { + } + } + + private void showTable(Object selectedRow) { + try{ + if(selectedRow instanceof TableTreeNode) { + TableTreeNode node = (TableTreeNode) selectedRow; + if(null != node) { + getEditor().displayTable(node.getFrame()); + } + } + } catch (NullPointerException ex) { + } + } + + private void setLastSelectedRom(Object selectedNode) { + if (selectedNode instanceof TableTreeNode || selectedNode instanceof CategoryTreeNode || selectedNode instanceof Rom) { + Object lastSelectedPathComponent = getLastSelectedPathComponent(); + if(lastSelectedPathComponent instanceof Rom) { + Rom node = (Rom) lastSelectedPathComponent; + if(null != node) { + getEditor().setLastSelectedRom(node); + } + } + } + getEditor().refreshUI(); + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseReleased(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/RomTreeRootNode.java b/java_console/romraider/src/com/romraider/swing/RomTreeRootNode.java new file mode 100644 index 0000000000..a184625403 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/RomTreeRootNode.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.tree.DefaultMutableTreeNode; + +public class RomTreeRootNode extends DefaultMutableTreeNode { + + private static final long serialVersionUID = 6810217325725782803L; + + public RomTreeRootNode(String name) { + super(name); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/ScalesTableModel.java b/java_console/romraider/src/com/romraider/swing/ScalesTableModel.java new file mode 100644 index 0000000000..63397d1de0 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/ScalesTableModel.java @@ -0,0 +1,95 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.util.Vector; + +import javax.swing.table.DefaultTableModel; + +import com.romraider.maps.Scale; + +public final class ScalesTableModel extends DefaultTableModel { + private static final long serialVersionUID = -5967359776053559125L; + private static final String[] colNames = { + "Name", "Expression", "Byte Expression", + "Unit", "Format", "Coarse", "Fine", "Min", "Max"}; + private Vector scales; + + @Override + public final int getColumnCount() { + return colNames.length; + } + + @Override + public final String getColumnName(int column) { + return colNames[column].toString(); + } + + @Override + public final Object getValueAt(int row, int column) { + if (null != scales) { + final Scale scale = scales.get(row); + switch (column) { + case 0: + return scale.getName(); + case 1: + return scale.getExpression(); + case 2: + return scale.getByteExpression(); + case 3: + return scale.getUnit(); + case 4: + return scale.getFormat(); + case 5: + return scale.getCoarseIncrement(); + case 6: + return scale.getFineIncrement(); + case 7: + return scale.getMin(); + case 8: + return scale.getMax(); + default: + return null; + } + } + else { + return null; + } + } + + @Override + public final int getRowCount() { + return (null != scales) ? scales.size() : 0; + } + + @Override + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + @Override + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setScalesList(Vector scales) { + this.scales = scales; + } +} diff --git a/java_console/romraider/src/com/romraider/swing/SetFont.java b/java_console/romraider/src/com/romraider/swing/SetFont.java new file mode 100644 index 0000000000..52df65976b --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/SetFont.java @@ -0,0 +1,90 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.awt.Font; + +import javax.swing.JComponent; + +/** + * Methods of this class can be used to change the style and/or size of a + * JComponent within the same font family. + */ +public class SetFont { + public SetFont() {} + + /** + * Set the style of JComponent to plain. + * @param component - item to change. + */ + public static final void plain(JComponent component) { + component.setFont( + new Font( + component.getFont().getFamily(), + Font.PLAIN, + component.getFont().getSize() + ) + ); + } + + /** + * Set the style of JComponent to plain using new size. + * @param component - item to change. + * @param size - the new font size. + */ + public static final void plain(JComponent component, int size) { + component.setFont( + new Font( + component.getFont().getFamily(), + Font.PLAIN, + size + ) + ); + } + + /** + * Set the style of JComponent to bold. + * @param component - item to change. + */ + public static final void bold(JComponent component) { + component.setFont( + new Font( + component.getFont().getFamily(), + Font.BOLD, + component.getFont().getSize() + ) + ); + } + + /** + * Set the style of JComponent to bold using new size. + * @param component - item to change. + * @param size - the new font size. + */ + public static final void bold(JComponent component, int size) { + component.setFont( + new Font( + component.getFont().getFamily(), + Font.BOLD, + size + ) + ); + } +} diff --git a/java_console/romraider/src/com/romraider/swing/SettingsForm.java b/java_console/romraider/src/com/romraider/swing/SettingsForm.java new file mode 100644 index 0000000000..fb78becf95 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/SettingsForm.java @@ -0,0 +1,1144 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static com.romraider.Version.PRODUCT_NAME; +import static java.io.File.separator; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.io.File; +import java.util.StringTokenizer; + +import javax.swing.ButtonGroup; +import javax.swing.DefaultComboBoxModel; +import javax.swing.GroupLayout; +import javax.swing.GroupLayout.Alignment; +import javax.swing.JCheckBox; +import javax.swing.JColorChooser; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; +import javax.swing.LayoutStyle.ComponentPlacement; +import javax.swing.UIManager; +import javax.swing.border.TitledBorder; + +import ZoeloeSoft.projects.JFontChooser.JFontChooser; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.editor.ecu.ECUEditorManager; +//import com.romraider.util.FileAssociator; +import com.romraider.util.SettingsManager; + +public class SettingsForm extends JFrame implements MouseListener { + + private static final long serialVersionUID = 3910602424260147767L; + + public SettingsForm() { + this.setIconImage(getEditor().getIconImage()); + initComponents(); + initSettings(); + + maxColor.addMouseListener(this); + minColor.addMouseListener(this); + highlightColor.addMouseListener(this); + selectColor.addMouseListener(this); + axisColor.addMouseListener(this); + increaseColor.addMouseListener(this); + decreaseColor.addMouseListener(this); + warningColor.addMouseListener(this); + + btnOk.addMouseListener(this); + btnApply.addMouseListener(this); + btnCancel.addMouseListener(this); + btnChooseFont.addMouseListener(this); + reset.addMouseListener(this); + btnAddAssocs.addMouseListener(this); + btnRemoveAssocs.addMouseListener(this); + + tableClickCount.setBackground(Color.WHITE); + tableClickBehavior.setBackground(Color.WHITE); + + // disable file association buttons if user is not in Windows + StringTokenizer osName = new StringTokenizer(System.getProperties().getProperty("os.name")); + if (!osName.nextToken().equalsIgnoreCase("windows")) { + btnAddAssocs.setEnabled(false); + btnRemoveAssocs.setEnabled(false); + extensionHex.setEnabled(false); + extensionBin.setEnabled(false); + } + + } + + private void initSettings() { + Settings settings = getSettings(); + obsoleteWarning.setSelected(settings.isObsoleteWarning()); + calcConflictWarning.setSelected(settings.isCalcConflictWarning()); + displayHighTables.setSelected(settings.isDisplayHighTables()); + saveDebugTables.setSelected(settings.isSaveDebugTables()); + debug.setSelected(settings.isDebug()); + + maxColor.setBackground(settings.getMaxColor()); + minColor.setBackground(settings.getMinColor()); + highlightColor.setBackground(settings.getHighlightColor()); + selectColor.setBackground(settings.getSelectColor()); + axisColor.setBackground(settings.getAxisColor()); + increaseColor.setBackground(settings.getIncreaseBorder()); + decreaseColor.setBackground(settings.getDecreaseBorder()); + + cellWidth.setText(((int) settings.getCellSize().getWidth()) + ""); + cellHeight.setText(((int) settings.getCellSize().getHeight()) + ""); + + btnChooseFont.setFont(settings.getTableFont()); + btnChooseFont.setText(settings.getTableFont().getFontName()); + + if (settings.getTableClickCount() == 1) { // single click opens table + tableClickCount.setSelectedIndex(0); + } else { // double click opens table + tableClickCount.setSelectedIndex(1); + } + + if(1 == settings.getTableClickBehavior()) { // open/focus + tableClickBehavior.setSelectedIndex(1); + } else { // open/close + tableClickBehavior.setSelectedIndex(0); + } + + valueLimitWarning.setSelected(settings.isValueLimitWarning()); + warningColor.setBackground(settings.getWarningColor()); + chckbxColorAxis.setSelected(settings.isColorAxis()); + + defaultScale.setText(settings.getDefaultScale()); + + if(settings.getTableClipboardFormat().equalsIgnoreCase(Settings.AIRBOYS_CLIPBOARD_FORMAT)) { + this.rdbtnAirboys.setSelected(true); + } else if(settings.getTableClipboardFormat().equalsIgnoreCase(Settings.CUSTOM_CLIPBOARD_FORMAT)) { + this.rdbtnCustom.setSelected(true); + } else { + this.rdbtnDefault.setSelected(true); + } + + this.textFieldEditorIconScale.setText(String.valueOf(settings.getEditorIconScale())); + this.textFieldTableIconScale.setText(String.valueOf(settings.getTableIconScale())); + + chckbxShowTableToolbar.setSelected(settings.isShowTableToolbarBorder()); + chckbxOpenRomNode.setSelected(settings.isOpenExpanded()); + chckbxOpenTablesAt.setSelected(settings.isAlwaysOpenTableAtZero()); + + if(settings.getDefaultScale().equalsIgnoreCase(Settings.DEFAULT_SCALE)) { + comboBoxDefaultScale.setSelectedItem(Settings.DEFAULT_SCALE); + } else if (settings.getDefaultScale().equalsIgnoreCase(Settings.METRIC_SCALE)) { + comboBoxDefaultScale.setSelectedItem(Settings.METRIC_SCALE); + } else if (settings.getDefaultScale().equalsIgnoreCase(Settings.STANDARD_SCALE)) { + comboBoxDefaultScale.setSelectedItem(Settings.STANDARD_SCALE); + } else { + comboBoxDefaultScale.setSelectedIndex(0); + } + + cbScaleHeaderAndData.setSelected(settings.isScaleHeadersAndData()); + } + + // //GEN-BEGIN:initComponents + private void initComponents() { + obsoleteWarning = new javax.swing.JCheckBox(); + calcConflictWarning = new javax.swing.JCheckBox(); + debug = new javax.swing.JCheckBox(); + btnCancel = new javax.swing.JButton(); + btnOk = new javax.swing.JButton(); + btnApply = new javax.swing.JButton(); + reset = new javax.swing.JButton(); + settingsTabbedPane = new javax.swing.JTabbedPane(); + jPanelClipboard = new javax.swing.JPanel(); + jPanelDefault = new javax.swing.JPanel(); + jPanelTableDisplay = new javax.swing.JPanel(); + jPanelIcons = new javax.swing.JPanel(); + jPanelScale = new javax.swing.JPanel(); + jPanel2 = new javax.swing.JPanel(); + lblAxis = new javax.swing.JLabel(); + lblHighlight = new javax.swing.JLabel(); + lblSelect = new javax.swing.JLabel(); + lblMin = new javax.swing.JLabel(); + lblMax = new javax.swing.JLabel(); + maxColor = new javax.swing.JLabel(); + minColor = new javax.swing.JLabel(); + highlightColor = new javax.swing.JLabel(); + selectColor = new javax.swing.JLabel(); + axisColor = new javax.swing.JLabel(); + warningColor = new javax.swing.JLabel(); + lblWarning = new javax.swing.JLabel(); + jPanel3 = new javax.swing.JPanel(); + lblIncrease = new javax.swing.JLabel(); + increaseColor = new javax.swing.JLabel(); + decreaseColor = new javax.swing.JLabel(); + lblDecrease = new javax.swing.JLabel(); + lblCellHeight = new javax.swing.JLabel(); + cellHeight = new javax.swing.JTextField(); + cellWidth = new javax.swing.JTextField(); + lblCellWidth = new javax.swing.JLabel(); + lblFont = new javax.swing.JLabel(); + btnChooseFont = new javax.swing.JButton(); + saveDebugTables = new javax.swing.JCheckBox(); + displayHighTables = new javax.swing.JCheckBox(); + valueLimitWarning = new javax.swing.JCheckBox(); + chckbxColorAxis = new javax.swing.JCheckBox(); + jPanel4 = new javax.swing.JPanel(); + extensionHex = new javax.swing.JCheckBox(); + extensionBin = new javax.swing.JCheckBox(); + btnAddAssocs = new javax.swing.JButton(); + btnRemoveAssocs = new javax.swing.JButton(); + editorIconsPanel = new javax.swing.JPanel(); + tableIconsPanel = new javax.swing.JPanel(); + tableClickBehavior = new javax.swing.JComboBox(); + labelTableClick = new javax.swing.JLabel(); + tableClickCount = new javax.swing.JComboBox(); + defaultScale = new javax.swing.JTextField(); + comboBoxDefaultScale = new javax.swing.JComboBox(); + cbScaleHeaderAndData = new javax.swing.JCheckBox(); + + clipboardButtonGroup = new ButtonGroup(); + rdbtnDefault = new JRadioButton("RomRaider Default"); + rdbtnAirboys = new JRadioButton("Airboys Spreadsheet"); + rdbtnCustom = new JRadioButton("Custom (manually specify formats in settings.xml)"); + clipboardButtonGroup.add(this.rdbtnDefault); + clipboardButtonGroup.add(this.rdbtnAirboys); + clipboardButtonGroup.add(this.rdbtnCustom); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setTitle(PRODUCT_NAME + " Settings"); + setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); + setFont(new java.awt.Font("Tahoma", 0, 12)); + obsoleteWarning.setText("Warn me when opening out of date ECU image revision"); + obsoleteWarning.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + obsoleteWarning.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + calcConflictWarning.setText("Warn me when real and byte value calculations conflict"); + calcConflictWarning.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + calcConflictWarning.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + debug.setText("Debug mode"); + debug.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + debug.setEnabled(false); + debug.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + btnCancel.setMnemonic('C'); + btnCancel.setText("Cancel"); + + btnOk.setMnemonic('O'); + btnOk.setText("OK"); + + btnApply.setMnemonic('A'); + btnApply.setText("Apply"); + + reset.setText("Restore Defaults"); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Background")); + lblAxis.setText("Axis Cell:"); + + lblHighlight.setText("Highlighted Cell:"); + lblSelect.setText("Selected Cell:"); + + lblMin.setText("Minimum Value:"); + + lblMax.setText("Maximum Value:"); + + maxColor.setBackground(new java.awt.Color(255, 0, 0)); + maxColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + maxColor.setOpaque(true); + + minColor.setBackground(new java.awt.Color(255, 0, 0)); + minColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + minColor.setOpaque(true); + + highlightColor.setBackground(new java.awt.Color(255, 0, 0)); + highlightColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + highlightColor.setOpaque(true); + + selectColor.setBackground(new java.awt.Color(255, 0, 0)); + selectColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + selectColor.setOpaque(true); + + axisColor.setBackground(new java.awt.Color(255, 0, 0)); + axisColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + axisColor.setOpaque(true); + + warningColor.setBackground(new java.awt.Color(255, 0, 0)); + warningColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + warningColor.setOpaque(true); + + lblWarning.setText("Warning:"); + + GroupLayout jPanel2Layout = new GroupLayout(jPanel2); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(Alignment.TRAILING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGroup(jPanel2Layout.createParallelGroup(Alignment.TRAILING) + .addComponent(lblWarning) + .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(4) + .addComponent(lblMin)) + .addComponent(lblMax))) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(Alignment.TRAILING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(maxColor, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED, 139, Short.MAX_VALUE) + .addComponent(lblHighlight) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(highlightColor, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) + .addGroup(Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(minColor, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED, 172, Short.MAX_VALUE) + .addComponent(lblAxis)) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(warningColor, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED, 151, Short.MAX_VALUE) + .addComponent(lblSelect))) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) + .addComponent(selectColor, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(axisColor, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGroup(jPanel2Layout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblMax) + .addComponent(maxColor, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE) + .addComponent(highlightColor, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE) + .addComponent(lblHighlight)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblMin) + .addComponent(minColor, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE) + .addComponent(axisColor, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE) + .addComponent(lblAxis)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanel2Layout.createParallelGroup(Alignment.BASELINE) + .addComponent(warningColor, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE) + .addComponent(lblWarning)) + .addComponent(selectColor, GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE) + .addComponent(lblSelect)) + .addContainerGap()) + ); + jPanel2.setLayout(jPanel2Layout); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Cell Borders")); + lblIncrease.setText("Increased:"); + + increaseColor.setBackground(new java.awt.Color(255, 0, 0)); + increaseColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + increaseColor.setOpaque(true); + + decreaseColor.setBackground(new java.awt.Color(255, 0, 0)); + decreaseColor.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + decreaseColor.setOpaque(true); + + lblDecrease.setText("Decreased:"); + +// org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3); +// jPanel3.setLayout(jPanel3Layout); +// jPanel3Layout.setHorizontalGroup( +// jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup() +// .addContainerGap() +// .add(lblIncrease) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(increaseColor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 59, Short.MAX_VALUE) +// .add(lblDecrease) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(decreaseColor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) +// .addContainerGap()) +// ); +// jPanel3Layout.setVerticalGroup( +// jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) +// .add(decreaseColor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) +// .add(lblDecrease) +// .add(lblIncrease) +// .add(increaseColor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 15, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) +// ); + + lblCellHeight.setText("Cell Height:"); + + lblCellWidth.setText("Cell Width:"); + + lblFont.setText("Font:"); + + btnChooseFont.setText("Choose"); + + saveDebugTables.setText("Save changes made on tables in debug mode"); + saveDebugTables.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + saveDebugTables.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + displayHighTables.setText("List tables that are above my userlevel"); + displayHighTables.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + displayHighTables.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + valueLimitWarning.setText("Warn when values exceed limits"); + valueLimitWarning.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + valueLimitWarning.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + chckbxColorAxis.setText("Color Axis"); + chckbxColorAxis.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + chckbxColorAxis.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("File Associations")); + extensionHex.setText("HEX"); + extensionHex.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + extensionHex.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + extensionBin.setText("BIN"); + extensionBin.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); + extensionBin.setMargin(new java.awt.Insets(0, 0, 0, 0)); + + btnAddAssocs.setText("Add Associations"); + + btnRemoveAssocs.setText("Remove Associations"); + +// org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); +// jPanel4.setLayout(jPanel4Layout); +// jPanel4Layout.setHorizontalGroup( +// jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() +// .addContainerGap() +// .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(extensionBin) +// .add(extensionHex)) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 93, Short.MAX_VALUE) +// .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) +// .add(btnAddAssocs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) +// .add(btnRemoveAssocs)) +// .add(25, 25, 25)) +// ); +// jPanel4Layout.setVerticalGroup( +// jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) +// .add(jPanel4Layout.createSequentialGroup() +// .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) +// .add(btnAddAssocs) +// .add(extensionHex)) +// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) +// .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) +// .add(btnRemoveAssocs) +// .add(extensionBin))) +// ); + + initTabs(); + + settingsTabbedPane.addTab("General", jPanelDefault); + settingsTabbedPane.addTab("Table Display", jPanelTableDisplay); + settingsTabbedPane.addTab("Clipboard", jPanelClipboard); + settingsTabbedPane.addTab("Icons", jPanelIcons); + settingsTabbedPane.addTab("Scale", jPanelScale); + + this.cbScaleHeaderAndData = new JCheckBox("Scale Headers and Data."); + this.cbScaleHeaderAndData.setToolTipText("If checked, the header scale will change when the data scale is selected. Otherwise click on a header row or column to select the scale."); + + JLabel lblDefaultScale = new JLabel("Default Scale:"); + + comboBoxDefaultScale.setModel(new DefaultComboBoxModel(new String[] { Settings.DEFAULT_SCALE, Settings.METRIC_SCALE, Settings.STANDARD_SCALE})); + + GroupLayout gl_jPanelScale = new GroupLayout(jPanelScale); + gl_jPanelScale.setHorizontalGroup( + gl_jPanelScale.createParallelGroup(Alignment.LEADING) + .addGroup(gl_jPanelScale.createSequentialGroup() + .addContainerGap() + .addGroup(gl_jPanelScale.createParallelGroup(Alignment.LEADING) + .addComponent(cbScaleHeaderAndData) + .addGroup(gl_jPanelScale.createSequentialGroup() + .addComponent(lblDefaultScale) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(comboBoxDefaultScale, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) + .addContainerGap(277, Short.MAX_VALUE)) + ); + gl_jPanelScale.setVerticalGroup( + gl_jPanelScale.createParallelGroup(Alignment.LEADING) + .addGroup(gl_jPanelScale.createSequentialGroup() + .addContainerGap() + .addGroup(gl_jPanelScale.createParallelGroup(Alignment.BASELINE) + .addComponent(lblDefaultScale) + .addComponent(comboBoxDefaultScale, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(ComponentPlacement.UNRELATED) + .addComponent(cbScaleHeaderAndData) + .addContainerGap(453, Short.MAX_VALUE)) + ); + jPanelScale.setLayout(gl_jPanelScale); + + editorIconsPanel = new JPanel(); + + // Content Pane Layout + GroupLayout layout = new GroupLayout(getContentPane()); + layout.setHorizontalGroup( + layout.createParallelGroup(Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(Alignment.LEADING) + .addComponent(settingsTabbedPane, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 432, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addComponent(reset) + .addPreferredGap(ComponentPlacement.RELATED, 136, Short.MAX_VALUE) + .addComponent(btnApply) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(btnOk) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(btnCancel))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(settingsTabbedPane, GroupLayout.PREFERRED_SIZE, 542, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(Alignment.BASELINE) + .addComponent(btnCancel) + .addComponent(btnOk) + .addComponent(btnApply) + .addComponent(reset)) + .addContainerGap()) + ); + getContentPane().setLayout(layout); + pack(); + }// //GEN-END:initComponents + + private void initTabs() { + + JPanel panelUISettings = new JPanel(); + panelUISettings.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "UI Settings", TitledBorder.LEADING, TitledBorder.TOP, null, null)); + // Init Default Tab Panel + GroupLayout jPanelDefaultLayout = new GroupLayout(jPanelDefault); + jPanelDefaultLayout.setHorizontalGroup( + jPanelDefaultLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelDefaultLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelDefaultLayout.createParallelGroup(Alignment.LEADING) + .addComponent(panelUISettings, GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE) + .addComponent(obsoleteWarning) + .addComponent(calcConflictWarning) + .addComponent(debug)) + .addContainerGap()) + ); + jPanelDefaultLayout.setVerticalGroup( + jPanelDefaultLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelDefaultLayout.createSequentialGroup() + .addContainerGap() + .addComponent(obsoleteWarning) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(calcConflictWarning) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(debug) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(panelUISettings, GroupLayout.PREFERRED_SIZE, 173, GroupLayout.PREFERRED_SIZE) + .addContainerGap(267, Short.MAX_VALUE)) + ); + chckbxOpenRomNode = new JCheckBox("Open rom node expanded"); + + chckbxShowTableToolbar = new JCheckBox("Show table toolbar border"); + + panelTreeSettings = new JPanel(); + panelTreeSettings.setBorder(new TitledBorder(null, "Rom Tree Settings", TitledBorder.LEADING, TitledBorder.TOP, null, null)); + + chckbxOpenTablesAt = new JCheckBox("Always open tables at [0,0]"); + GroupLayout gl_panelUISettings = new GroupLayout(panelUISettings); + gl_panelUISettings.setHorizontalGroup( + gl_panelUISettings.createParallelGroup(Alignment.LEADING) + .addGroup(gl_panelUISettings.createSequentialGroup() + .addGroup(gl_panelUISettings.createParallelGroup(Alignment.LEADING) + .addComponent(chckbxOpenRomNode) + .addComponent(chckbxShowTableToolbar)) + .addContainerGap(244, Short.MAX_VALUE)) + .addComponent(panelTreeSettings, GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE) + .addGroup(gl_panelUISettings.createSequentialGroup() + .addComponent(chckbxOpenTablesAt) + .addContainerGap()) + ); + gl_panelUISettings.setVerticalGroup( + gl_panelUISettings.createParallelGroup(Alignment.LEADING) + .addGroup(gl_panelUISettings.createSequentialGroup() + .addComponent(chckbxOpenRomNode) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(chckbxShowTableToolbar) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(chckbxOpenTablesAt) + .addPreferredGap(ComponentPlacement.RELATED, 12, Short.MAX_VALUE) + .addComponent(panelTreeSettings, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)) + ); + + labelTableClick.setText("Click to open tables"); + tableClickCount.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Single", "Double"})); + tableClickBehavior.setModel(new DefaultComboBoxModel(new String[] {"open/close", "open/focus"})); + + lblClickBehavior = new JLabel("Table click behavior"); + GroupLayout gl_panelTreeSettings = new GroupLayout(panelTreeSettings); + gl_panelTreeSettings.setHorizontalGroup( + gl_panelTreeSettings.createParallelGroup(Alignment.LEADING) + .addGroup(gl_panelTreeSettings.createSequentialGroup() + .addGroup(gl_panelTreeSettings.createParallelGroup(Alignment.LEADING) + .addComponent(tableClickCount, 0, 72, Short.MAX_VALUE) + .addComponent(tableClickBehavior, 0, 86, Short.MAX_VALUE)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(gl_panelTreeSettings.createParallelGroup(Alignment.LEADING) + .addComponent(labelTableClick) + .addComponent(lblClickBehavior)) + .addGap(200)) + ); + gl_panelTreeSettings.setVerticalGroup( + gl_panelTreeSettings.createParallelGroup(Alignment.LEADING) + .addGroup(gl_panelTreeSettings.createSequentialGroup() + .addGroup(gl_panelTreeSettings.createParallelGroup(Alignment.BASELINE) + .addComponent(labelTableClick) + .addComponent(tableClickCount, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(gl_panelTreeSettings.createParallelGroup(Alignment.BASELINE) + .addComponent(lblClickBehavior) + .addComponent(tableClickBehavior, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) + .addContainerGap(23, Short.MAX_VALUE)) + ); + panelTreeSettings.setLayout(gl_panelTreeSettings); + panelUISettings.setLayout(gl_panelUISettings); + jPanelDefault.setLayout(jPanelDefaultLayout); + + // Init Table Display Tab + GroupLayout jPanelTableDisplayLayout = new GroupLayout(jPanelTableDisplay); + jPanelTableDisplayLayout.setHorizontalGroup( + jPanelTableDisplayLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelTableDisplayLayout.createParallelGroup(Alignment.LEADING) + .addComponent(lblCellHeight) + .addComponent(lblFont)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanelTableDisplayLayout.createParallelGroup(Alignment.LEADING) + .addComponent(btnChooseFont) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addComponent(cellHeight, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED, 155, Short.MAX_VALUE) + .addComponent(lblCellWidth) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(cellWidth, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE))) + .addGap(47)) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addComponent(jPanel4, GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE) + .addContainerGap()) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addComponent(jPanel3, GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE) + .addContainerGap()) + .addComponent(jPanel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addContainerGap() + .addComponent(saveDebugTables) + .addContainerGap(184, Short.MAX_VALUE)) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addContainerGap() + .addComponent(displayHighTables) + .addContainerGap(214, Short.MAX_VALUE)) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addContainerGap() + .addComponent(valueLimitWarning) + .addContainerGap(246, Short.MAX_VALUE)) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addContainerGap() + .addComponent(chckbxColorAxis) + .addContainerGap(324, Short.MAX_VALUE)) + ); + jPanelTableDisplayLayout.setVerticalGroup( + jPanelTableDisplayLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelTableDisplayLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(jPanel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(jPanel4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(saveDebugTables) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(displayHighTables) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(valueLimitWarning) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(chckbxColorAxis) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanelTableDisplayLayout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblCellWidth) + .addComponent(cellWidth, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(lblCellHeight) + .addComponent(cellHeight, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(jPanelTableDisplayLayout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblFont) + .addComponent(btnChooseFont, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + jPanelTableDisplay.setLayout(jPanelTableDisplayLayout); + + // Init Clipboard Tab Panel + GroupLayout jPanelClipboardLayout = new GroupLayout(jPanelClipboard); + jPanelClipboardLayout.setHorizontalGroup( + jPanelClipboardLayout.createParallelGroup(Alignment.TRAILING) + .addGroup(jPanelClipboardLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelClipboardLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelClipboardLayout.createSequentialGroup() + .addGap(17) + .addGroup(jPanelClipboardLayout.createParallelGroup(Alignment.LEADING) + .addComponent(rdbtnAirboys) + .addComponent(rdbtnDefault) + .addComponent(rdbtnCustom)))) + .addGap(157)) + ); + jPanelClipboardLayout.setVerticalGroup( + jPanelClipboardLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelClipboardLayout.createSequentialGroup() + .addContainerGap() + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(rdbtnDefault) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(rdbtnAirboys) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(rdbtnCustom) + .addGap(435)) + ); + jPanelClipboard.setLayout(jPanelClipboardLayout); + + // Init Icons Tab panel + editorIconsPanel.setBorder(new TitledBorder(null, "Editor Toolbar Icons", TitledBorder.LEADING, TitledBorder.TOP, null, null)); + tableIconsPanel.setBorder(new TitledBorder(null, "Table Toolbar Icons", TitledBorder.LEADING, TitledBorder.TOP, null, null)); + + GroupLayout jPanelIconsLayout = new GroupLayout(jPanelIcons); + jPanelIconsLayout.setHorizontalGroup( + jPanelIconsLayout.createParallelGroup(Alignment.TRAILING) + .addGroup(jPanelIconsLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelIconsLayout.createParallelGroup(Alignment.LEADING) + .addComponent(editorIconsPanel, GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE) + .addComponent(tableIconsPanel, GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)) + .addContainerGap()) + ); + jPanelIconsLayout.setVerticalGroup( + jPanelIconsLayout.createParallelGroup(Alignment.LEADING) + .addGroup(jPanelIconsLayout.createSequentialGroup() + .addContainerGap() + .addComponent(editorIconsPanel, GroupLayout.PREFERRED_SIZE, 66, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(tableIconsPanel, GroupLayout.PREFERRED_SIZE, 64, GroupLayout.PREFERRED_SIZE) + .addContainerGap(367, Short.MAX_VALUE)) + ); + + JLabel lblTableIconScale = new JLabel("Scale:"); + + textFieldTableIconScale = new JTextField(); + textFieldTableIconScale.setToolTipText("The percentage of the icons original size."); + textFieldTableIconScale.setColumns(10); + + JLabel labelTableScalePercent = new JLabel("%"); + GroupLayout tableIconsPanelLayout = new GroupLayout(tableIconsPanel); + tableIconsPanelLayout.setHorizontalGroup( + tableIconsPanelLayout.createParallelGroup(Alignment.LEADING) + .addGroup(tableIconsPanelLayout.createSequentialGroup() + .addContainerGap() + .addComponent(lblTableIconScale) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(textFieldTableIconScale, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(labelTableScalePercent) + .addContainerGap(216, Short.MAX_VALUE)) + ); + tableIconsPanelLayout.setVerticalGroup( + tableIconsPanelLayout.createParallelGroup(Alignment.LEADING) + .addGroup(tableIconsPanelLayout.createSequentialGroup() + .addContainerGap() + .addGroup(tableIconsPanelLayout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblTableIconScale) + .addComponent(textFieldTableIconScale, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(labelTableScalePercent)) + .addContainerGap(116, Short.MAX_VALUE)) + ); + tableIconsPanel.setLayout(tableIconsPanelLayout); + + JLabel lblEditorIconScale = new JLabel("Scale:"); + + textFieldEditorIconScale = new JTextField(); + textFieldEditorIconScale.setToolTipText("The percentage of the icons original size."); + textFieldEditorIconScale.setColumns(10); + + JLabel labelEditorScalePercent = new JLabel("%"); + GroupLayout editorIconsPanelLayout = new GroupLayout(editorIconsPanel); + editorIconsPanelLayout.setHorizontalGroup( + editorIconsPanelLayout.createParallelGroup(Alignment.LEADING) + .addGroup(editorIconsPanelLayout.createSequentialGroup() + .addContainerGap() + .addComponent(lblEditorIconScale) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(textFieldEditorIconScale, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(labelEditorScalePercent) + .addContainerGap(216, Short.MAX_VALUE)) + ); + editorIconsPanelLayout.setVerticalGroup( + editorIconsPanelLayout.createParallelGroup(Alignment.LEADING) + .addGroup(editorIconsPanelLayout.createSequentialGroup() + .addContainerGap() + .addGroup(editorIconsPanelLayout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblEditorIconScale) + .addComponent(textFieldEditorIconScale, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(labelEditorScalePercent)) + .addContainerGap(95, Short.MAX_VALUE)) + ); + editorIconsPanel.setLayout(editorIconsPanelLayout); + + jPanelIcons.setLayout(jPanelIconsLayout); + } + + @Override + public void mouseClicked(MouseEvent e) { + Settings settings = getSettings(); + if (e.getSource() == maxColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getMaxColor()); + if (color != null) { + maxColor.setBackground(color); + } + } else if (e.getSource() == minColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getMinColor()); + if (color != null) { + minColor.setBackground(color); + } + } else if (e.getSource() == highlightColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getHighlightColor()); + if (color != null) { + highlightColor.setBackground(color); + } + } else if (e.getSource() == selectColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getSelectColor()); + if (color != null) { + selectColor.setBackground(color); + } + } else if (e.getSource() == axisColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getAxisColor()); + if (color != null) { + axisColor.setBackground(color); + } + } else if (e.getSource() == increaseColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getIncreaseBorder()); + if (color != null) { + increaseColor.setBackground(color); + } + } else if (e.getSource() == decreaseColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Background Color", settings.getDecreaseBorder()); + if (color != null) { + decreaseColor.setBackground(color); + } + } else if (e.getSource() == warningColor) { + Color color = JColorChooser.showDialog(this.getContentPane(), + "Warning Color", settings.getWarningColor()); + if (color != null) { + warningColor.setBackground(color); + } + } else if (e.getSource() == btnApply) { + applySettings(); + } else if (e.getSource() == btnOk) { + // Apply settings to Settings object. + applySettings(); + // Write settings to file. + saveSettings(); + this.dispose(); + } else if (e.getSource() == btnCancel) { + this.dispose(); + } else if (e.getSource() == btnChooseFont) { + JFontChooser fc = new JFontChooser(this); + fc.setLocationRelativeTo(this); + if (fc.showDialog(settings.getTableFont()) == JFontChooser.OK_OPTION) { + btnChooseFont.setFont(fc.getFont()); + btnChooseFont.setText(fc.getFont().getFontName()); + } + } else if (e.getSource() == reset) { + Settings newSettings = new Settings(); + Settings curSettings = getSettings(); + + newSettings.setEcuDefinitionFiles(curSettings.getEcuDefinitionFiles()); + newSettings.setLastImageDir(curSettings.getLastImageDir()); + newSettings.setLastRepositoryDir(curSettings.getLastRepositoryDir()); + newSettings.setUserLevel(curSettings.getUserLevel()); + newSettings.setLoggerDefinitionFilePath(curSettings.getLoggerDefinitionFilePath()); + newSettings.setLoggerDebuggingLevel(curSettings.getLoggerDebuggingLevel()); + newSettings.setLoggerProfileFilePath(curSettings.getLoggerProfileFilePath()); + newSettings.setLoggerOutputDirPath(curSettings.getLoggerOutputDirPath()); + + SettingsManager.save(newSettings); + + initSettings(); + } else if (e.getSource() == btnAddAssocs) { + // add file associations for selected file types + boolean added = false; + try { + if (extensionHex.isSelected()) { + //FileAssociator.addAssociation("HEX", new File(".").getCanonicalPath() + separator + PRODUCT_NAME + ".exe", "ECU Image"); + added = true; + } + + if (extensionBin.isSelected()) { + //FileAssociator.addAssociation("BIN", new File(".").getCanonicalPath() + separator + PRODUCT_NAME + ".exe", "ECU Image"); + added = true; + } + } catch (Exception ex) { + added = false; + } finally { + if(added) { + JOptionPane.showMessageDialog(null, "Association(s) added.", "Add Association Success", JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, "Failed to add association(s).", "Add Association Failure", JOptionPane.ERROR_MESSAGE); + } + } + + } else if (e.getSource() == btnRemoveAssocs) { + // remove file associations for selected file types + boolean removed = false; + if (extensionHex.isSelected()) { + //removed = FileAssociator.removeAssociation("HEX"); + } + + if (extensionBin.isSelected()) { + //removed = FileAssociator.removeAssociation("BIN"); + } + + if(removed) { + JOptionPane.showMessageDialog(null, "Association removed.", "Remove Association Success", JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(null, "Failed to remove association.", "Remove Association Failure", JOptionPane.ERROR_MESSAGE); + } + } + } + + public void applySettings() { + try { + Integer.parseInt(cellHeight.getText()); + } catch (NumberFormatException ex) { + // number formatted imporperly, reset + cellHeight.setText((int) (getSettings().getCellSize().getHeight()) + ""); + } + try { + Integer.parseInt(cellWidth.getText()); + } catch (NumberFormatException ex) { + // number formatted imporperly, reset + cellWidth.setText((int) (getSettings().getCellSize().getWidth()) + ""); + } + + getSettings().setObsoleteWarning(obsoleteWarning.isSelected()); + getSettings().setCalcConflictWarning(calcConflictWarning.isSelected()); + getSettings().setDisplayHighTables(displayHighTables.isSelected()); + getSettings().setSaveDebugTables(saveDebugTables.isSelected()); + getSettings().setDebug(debug.isSelected()); + getSettings().setOpenExpanded(chckbxOpenRomNode.isSelected()); + getSettings().setAlwaysOpenTableAtZero(chckbxOpenTablesAt.isSelected()); + getSettings().setShowTableToolbarBorder(chckbxShowTableToolbar.isSelected()); + + getSettings().setMaxColor(maxColor.getBackground()); + getSettings().setMinColor(minColor.getBackground()); + getSettings().setHighlightColor(highlightColor.getBackground()); + getSettings().setSelectColor(selectColor.getBackground()); + getSettings().setAxisColor(axisColor.getBackground()); + getSettings().setIncreaseBorder(increaseColor.getBackground()); + getSettings().setDecreaseBorder(decreaseColor.getBackground()); + + getSettings().setScaleHeadersAndData(this.cbScaleHeaderAndData.isSelected()); + + getSettings().setCellSize(new Dimension(Integer.parseInt(cellWidth.getText()), + Integer.parseInt(cellHeight.getText()))); + + getSettings().setTableFont(btnChooseFont.getFont()); + + if (tableClickCount.getSelectedIndex() == 0) { // single click opens table + getSettings().setTableClickCount(1); + } else { // double click opens table + getSettings().setTableClickCount(2); + } + + if(1 == tableClickBehavior.getSelectedIndex()) { // open/close frame + getSettings().setTableClickBehavior(1); + } else { // open/focus frame + getSettings().setTableClickBehavior(0); + } + + getSettings().setValueLimitWarning(valueLimitWarning.isSelected()); + getSettings().setWarningColor(warningColor.getBackground()); + getSettings().setColorAxis(chckbxColorAxis.isSelected()); + getSettings().setDefaultScale(defaultScale.getText()); + + if(rdbtnAirboys.isSelected()) + { + getSettings().setAirboysFormat(); + } else if(rdbtnCustom.isSelected()) { + getSettings().setTableClipboardFormat(Settings.CUSTOM_CLIPBOARD_FORMAT); + // Table Header settings need to be manually edited in the settings.xml file; + } else { + getSettings().setDefaultFormat(); + } + + try{ + getSettings().setEditorIconScale(Integer.parseInt(textFieldEditorIconScale.getText())); + getEditor().getToolBar().updateIcons(); + } catch(NumberFormatException ex) { + // Number formatted incorrectly reset. + textFieldEditorIconScale.setText(String.valueOf(getSettings().getEditorIconScale())); + } + + try{ + getSettings().setTableIconScale(Integer.parseInt(textFieldTableIconScale.getText())); + getEditor().getTableToolBar().updateIcons(); + } catch(NumberFormatException ex) { + // Number formatted incorrectly reset. + textFieldTableIconScale.setText(String.valueOf(getSettings().getTableIconScale())); + } + + getSettings().setDefaultScale(comboBoxDefaultScale.getSelectedItem().toString()); + } + + private Settings getSettings() + { + return SettingsManager.getSettings(); + } + + private ECUEditor getEditor() + { + return ECUEditorManager.getECUEditor(); + } + + public void saveSettings() + { + saveSettings(getSettings()); + } + + public void saveSettings(Settings newSettings) { + SettingsManager.save(newSettings); + drawVisibleTables(); + getEditor().refreshUI(); + } + + private void drawVisibleTables() { + for(JInternalFrame frame : getEditor().getRightPanel().getAllFrames()) { + if(frame instanceof TableFrame && frame.isVisible()) { + TableFrame tableFrame = (TableFrame) frame; + tableFrame.getTable().drawTable(); + } + } + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseReleased(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JLabel axisColor; + private javax.swing.JButton btnAddAssocs; + private javax.swing.JButton btnApply; + private javax.swing.JButton btnCancel; + private javax.swing.JButton btnChooseFont; + private javax.swing.JButton btnOk; + private javax.swing.JButton btnRemoveAssocs; + private javax.swing.JCheckBox calcConflictWarning; + private javax.swing.JTextField cellHeight; + private javax.swing.JTextField cellWidth; + private javax.swing.JCheckBox debug; + private javax.swing.JLabel decreaseColor; + private javax.swing.JCheckBox displayHighTables; + private javax.swing.JCheckBox extensionBin; + private javax.swing.JCheckBox extensionHex; + private javax.swing.JLabel highlightColor; + private javax.swing.JLabel selectColor; + private javax.swing.JLabel increaseColor; + private javax.swing.JLabel labelTableClick; + private javax.swing.JLabel lblClickBehavior; + private javax.swing.JTabbedPane settingsTabbedPane; + private javax.swing.JPanel jPanelDefault; + private javax.swing.JPanel jPanelClipboard; + private javax.swing.JPanel jPanelTableDisplay; + private javax.swing.JPanel jPanelIcons; + private javax.swing.JPanel jPanelScale; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JLabel lblAxis; + private javax.swing.JLabel lblCellHeight; + private javax.swing.JLabel lblCellWidth; + private javax.swing.JLabel lblDecrease; + private javax.swing.JLabel lblFont; + private javax.swing.JLabel lblHighlight; + private javax.swing.JLabel lblSelect; + private javax.swing.JLabel lblIncrease; + private javax.swing.JLabel lblMax; + private javax.swing.JLabel lblMin; + private javax.swing.JLabel lblWarning; + private javax.swing.JLabel maxColor; + private javax.swing.JLabel minColor; + private javax.swing.JCheckBox obsoleteWarning; + private javax.swing.JButton reset; + private javax.swing.JCheckBox saveDebugTables; + private javax.swing.JComboBox tableClickCount; + private javax.swing.JCheckBox valueLimitWarning; + private javax.swing.JCheckBox chckbxColorAxis; + private javax.swing.JLabel warningColor; + private ButtonGroup clipboardButtonGroup; + private javax.swing.JRadioButton rdbtnDefault; + private javax.swing.JRadioButton rdbtnAirboys; + private javax.swing.JRadioButton rdbtnCustom; + private JPanel editorIconsPanel; + private JPanel tableIconsPanel; + private JTextField textFieldTableIconScale; + private JTextField textFieldEditorIconScale; + private javax.swing.JCheckBox chckbxShowTableToolbar; + private javax.swing.JCheckBox chckbxOpenRomNode; + private JPanel panelTreeSettings; + private javax.swing.JComboBox tableClickBehavior; + private javax.swing.JCheckBox chckbxOpenTablesAt; + private javax.swing.JTextField defaultScale; + private javax.swing.JComboBox comboBoxDefaultScale; + private javax.swing.JCheckBox cbScaleHeaderAndData; +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/SwitchStateTableModel.java b/java_console/romraider/src/com/romraider/swing/SwitchStateTableModel.java new file mode 100644 index 0000000000..9cc93bc46b --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/SwitchStateTableModel.java @@ -0,0 +1,81 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.util.Map; + +import javax.swing.table.DefaultTableModel; + +import com.romraider.util.HexUtil; + +public final class SwitchStateTableModel extends DefaultTableModel { + private static final long serialVersionUID = -6053559125596735977L; + private static final String[] colNames = { + "Switch State", "State Data"}; + private Map switchStates; + + @Override + public final int getColumnCount() { + return colNames.length; + } + + @Override + public final String getColumnName(int column) { + return colNames[column]; + } + + @Override + public final Object getValueAt(int row, int column) { + if (null != switchStates) { + final String key = (String) switchStates.keySet().toArray()[row]; + final byte[] value = switchStates.get(key); + switch (column) { + case 0: + return key; + case 1: + return HexUtil.asHex(value); + default: + return null; + } + } + else { + return null; + } + } + + @Override + public final int getRowCount() { + return (null != switchStates) ? switchStates.size() : 0; + } + + @Override + public final Class getColumnClass(int column) { + return getValueAt(0, column).getClass(); + } + + @Override + public final boolean isCellEditable(int row, int column) { + return false; + } + + public final void setScalesList(Map switchStates) { + this.switchStates = switchStates; + } +} diff --git a/java_console/romraider/src/com/romraider/swing/TableChooserTreeNode.java b/java_console/romraider/src/com/romraider/swing/TableChooserTreeNode.java new file mode 100644 index 0000000000..8a2e970671 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TableChooserTreeNode.java @@ -0,0 +1,38 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import com.romraider.maps.Table; +import javax.swing.tree.DefaultMutableTreeNode; + +public class TableChooserTreeNode extends DefaultMutableTreeNode { + + private static final long serialVersionUID = 6660923635216155045L; + private Table table; + + public TableChooserTreeNode(String text, Table table) { + super(text); + this.table = table; + } + + public Table getTable() { + return table; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/TableFrame.java b/java_console/romraider/src/com/romraider/swing/TableFrame.java new file mode 100644 index 0000000000..53d08e9ed5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TableFrame.java @@ -0,0 +1,234 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static javax.swing.BorderFactory.createBevelBorder; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JInternalFrame; +import javax.swing.JMenu; +import javax.swing.JOptionPane; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.event.InternalFrameEvent; +import javax.swing.event.InternalFrameListener; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditor; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.logger.ecu.ui.handler.table.TableUpdateHandler; +import com.romraider.maps.Rom; +import com.romraider.maps.Table; + +public class TableFrame extends JInternalFrame implements InternalFrameListener, ActionListener { + + private static final long serialVersionUID = -2651279694660392351L; + private final Table table; + private TableMenuBar tableMenuBar = null; + + public TableFrame(String title, Table table) { + super(title, true, true); + this.table = table; + add(table); + setFrameIcon(null); + setBorder(createBevelBorder(0)); + if (System.getProperty("os.name").startsWith("Mac OS")) + putClientProperty("JInternalFrame.isPalette", true); + setVisible(false); + tableMenuBar = new TableMenuBar(this); + setJMenuBar(tableMenuBar); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addInternalFrameListener(this); + } + + @Override + public void internalFrameActivated(InternalFrameEvent e) { + ECUEditor parent = getEditor(); + parent.getTableToolBar().updateTableToolBar(); + parent.getToolBar().updateButtons(); + parent.getEditorMenuBar().updateMenu(); + } + + @Override + public void internalFrameOpened(InternalFrameEvent e) { + RegisterTable(); + } + + @Override + public void internalFrameClosing(InternalFrameEvent e) { + TableUpdateHandler.getInstance().deregisterTable(this.getTable()); + } + + @Override + public void internalFrameClosed(InternalFrameEvent e) { + getEditor().getTableToolBar().updateTableToolBar(); + } + + @Override + public void internalFrameIconified(InternalFrameEvent e) { + ; + } + + @Override + public void internalFrameDeiconified(InternalFrameEvent e) { + ; + } + + @Override + public void internalFrameDeactivated(InternalFrameEvent e) { + getEditor().getTableToolBar().updateTableToolBar(); + } + + public void RegisterTable() { + TableUpdateHandler.getInstance().registerTable(this.getTable()); + } + + public Table getTable() { + return table; + } + + public ECUEditor getEditor() { + return ECUEditorManager.getECUEditor(); + } + + public TableMenuBar getTableMenuBar() { + return this.tableMenuBar; + } + + @Override + public void actionPerformed(ActionEvent e) { + TableMenuBar menu = getTableMenuBar(); + + if (e.getSource() == menu.getUndoAll()) { + getTable().undoAll(); + + } else if (e.getSource() == menu.getRevert()) { + getTable().setRevertPoint(); + + } else if (e.getSource() == menu.getUndoSel()) { + getTable().undoSelected(); + + } else if (e.getSource() == menu.getClose()) { + ECUEditorManager.getECUEditor().removeDisplayTable(this); + + } else if (e.getSource() == menu.getTableProperties()) { + JOptionPane.showMessageDialog(getTable(), new TablePropertyPanel(getTable()), + getTable().getName() + " Table Properties", JOptionPane.INFORMATION_MESSAGE); + + } else if (e.getSource() == menu.getCopySel()) { + getTable().copySelection(); + + } else if (e.getSource() == menu.getCopyTable()) { + getTable().copyTable(); + + } else if (e.getSource() == menu.getPaste()) { + getTable().paste(); + + } else if (e.getSource() == menu.getCompareOff()) { + getTable().setCompareTable(null); + getTable().setCompareValueType(Settings.DATA_TYPE_BIN); + getTableMenuBar().getCompareToBin().setSelected(true); + + } else if (e.getSource() == menu.getCompareAbsolute()) { + getTable().setCompareDisplay(Settings.COMPARE_DISPLAY_ABSOLUTE); + + } else if (e.getSource() == menu.getComparePercent()) { + getTable().setCompareDisplay(Settings.COMPARE_DISPLAY_PERCENT); + + } else if (e.getSource() == menu.getCompareOriginal()) { + getTable().setCompareValueType(Settings.DATA_TYPE_ORIGINAL); + getTableMenuBar().getCompareToOriginal().setSelected(true); + compareByTable(getTable()); + + } else if (e.getSource() == menu.getCompareMap()) { + JTableChooser chooser = new JTableChooser(); + Table selectedTable = chooser.showChooser(getTable()); + if(null != selectedTable) { + compareByTable(selectedTable); + } + + } else if (e.getSource() instanceof TableMenuItem) { + Table selectedTable = findSimilarTable((TableMenuItem)e.getSource()); + if(null != e.getSource()) { + compareByTable(selectedTable); + } + + } else if (e.getSource() == menu.getCompareToOriginal()) { + getTable().setCompareValueType(Settings.DATA_TYPE_ORIGINAL); + getTable().refreshCompare(); + + } else if (e.getSource() == menu.getCompareToBin()) { + getTable().setCompareValueType(Settings.DATA_TYPE_BIN); + getTable().refreshCompare(); + + } else if (e.getSource() == menu.getInterp()) { + getTable().interpolate(); + + } else if (e.getSource() == menu.getVertInterp()) { + getTable().verticalInterpolate(); + + } else if (e.getSource() == menu.getHorizInterp()) { + getTable().horizontalInterpolate(); + } + } + + public void compareByTable(Table selectedTable) { + if(null == selectedTable) { + return; + } + getTable().setCompareTable(selectedTable); + ECUEditorManager.getECUEditor().getTableToolBar().updateTableToolBar(getTable()); + getTable().populateCompareValues(selectedTable); + } + + public void refreshSimilarOpenTables() { + JMenu similarTables = getTableMenuBar().getSimilarOpenTables(); + similarTables.removeAll(); + + for(Rom rom : ECUEditorManager.getECUEditor().getImages()) { + for(TableTreeNode tableNode : rom.getTableNodes()) { + if(tableNode.getTable().getName().equalsIgnoreCase(getTable().getName())) { + JRadioButtonMenuItem similarTable = new TableMenuItem(rom.getFileName()); + similarTable.setToolTipText(tableNode.getFrame().getTable().getName()); + similarTable.addActionListener(this); + similarTables.add(similarTable); + break; + } + } + } + + getTableMenuBar().initCompareGroup(); + getTableMenuBar().repaint(); + } + + private Table findSimilarTable(TableMenuItem menuItem) { + for(Rom rom : ECUEditorManager.getECUEditor().getImages()) { + if(menuItem.getText().equalsIgnoreCase(rom.getFileName())) { + for(TableTreeNode treeNode : rom.getTableNodes()) { + if(menuItem.getToolTipText().equalsIgnoreCase(treeNode.getFrame().getTable().getName())) { + return treeNode.getFrame().getTable(); + } + } + } + } + return null; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/TableMenuBar.java b/java_console/romraider/src/com/romraider/swing/TableMenuBar.java new file mode 100644 index 0000000000..3e14fd1283 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TableMenuBar.java @@ -0,0 +1,407 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.ButtonGroup; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JSeparator; + +import com.romraider.Settings; +import com.romraider.maps.Table3D; + +public class TableMenuBar extends JMenuBar { + + private static final long serialVersionUID = -695692646459410510L; + private JMenu fileMenu; + private JMenuItem graph; + + private JMenu compareMenu; + private JRadioButtonMenuItem compareOriginal; + private JRadioButtonMenuItem compareMap; + private JMenu similarOpenTables; + private JRadioButtonMenuItem compareOff; + private JMenu compareDisplay; + private JRadioButtonMenuItem comparePercent; + private JRadioButtonMenuItem compareAbsolute; + private JMenu compareToValue; + private JRadioButtonMenuItem compareToOriginal; + private JRadioButtonMenuItem compareToBin; + + private JMenuItem close; + private JMenu editMenu; + private JMenuItem undoSel; + private JMenuItem undoAll; + private JMenuItem revert; + private JMenuItem copySel; + private JMenuItem copyTable; + private JMenuItem paste; + private JMenuItem interp; + private JMenuItem vertInterp; + private JMenuItem horizInterp; + private JMenu viewMenu; + private JMenuItem tableProperties; + + private ButtonGroup compareGroup; + private ButtonGroup compareDisplayGroup; + private ButtonGroup compareToGroup; + + public TableMenuBar(TableFrame frame) { + initFileMenu(frame); + initEditMenu(frame); + initViewMenu(frame); + applyTableTypeRules(frame); + } + + private void initFileMenu(TableFrame frame) { + fileMenu = new JMenu("Table"); + graph = new JMenuItem("View Graph"); + compareMenu = new JMenu("Compare"); + setClose(new JMenuItem("Close Table")); + + initCompareMenu(frame); + getClose().setText("Close " + frame.getTable().getName()); + + graph.addActionListener(frame); + getClose().addActionListener(frame); + + graph.setMnemonic('G'); + getClose().setMnemonic('X'); + graph.setEnabled(false); + + fileMenu.add(graph); + fileMenu.add(compareMenu); + fileMenu.add(new JSeparator()); + fileMenu.add(getClose()); + + this.add(fileMenu); + } + + private void initEditMenu(TableFrame frame) { + editMenu = new JMenu("Edit"); + setUndoSel(new JMenuItem("Undo Selected Changes")); + setUndoAll(new JMenuItem("Undo All Changes")); + setRevert(new JMenuItem("Set Revert Point")); + setCopySel(new JMenuItem("Copy Selection")); + setCopyTable(new JMenuItem("Copy Table")); + setPaste(new JMenuItem("Paste")); + setVertInterp(new JMenuItem("Vertical Interpolate")); + setHorizInterp(new JMenuItem("Horizontal Interpolate")); + setInterp(new JMenuItem("Interpolate")); + + editMenu.add(getUndoSel()); + editMenu.add(getUndoAll()); + editMenu.add(getRevert()); + editMenu.add(new JSeparator()); + editMenu.add(getCopySel()); + editMenu.add(getCopyTable()); + editMenu.add(new JSeparator()); + editMenu.add(getPaste()); + editMenu.add(new JSeparator()); + if (frame.getTable() instanceof Table3D) { + editMenu.add(getVertInterp()); + editMenu.add(getHorizInterp()); + } + editMenu.add(getInterp()); + + editMenu.setMnemonic('E'); + getUndoSel().setMnemonic('U'); + getUndoAll().setMnemonic('A'); + getRevert().setMnemonic('R'); + getCopySel().setMnemonic('C'); + getCopyTable().setMnemonic('T'); + getPaste().setMnemonic('P'); + getInterp().setMnemonic('I'); + getVertInterp().setMnemonic('V'); + getHorizInterp().setMnemonic('H'); + + getUndoSel().addActionListener(frame); + getUndoAll().addActionListener(frame); + getRevert().addActionListener(frame); + getCopySel().addActionListener(frame); + getCopyTable().addActionListener(frame); + getPaste().addActionListener(frame); + getInterp().addActionListener(frame); + getVertInterp().addActionListener(frame); + getHorizInterp().addActionListener(frame); + this.add(editMenu); + } + + private void initViewMenu(TableFrame frame) { + + viewMenu = new JMenu("View"); + viewMenu.setMnemonic('V'); + + setTableProperties(new JMenuItem("Table Properties")); + getTableProperties().setToolTipText("Select to view the table properties."); + getTableProperties().setMnemonic('P'); + getTableProperties().addActionListener(frame); + + fileMenu.setMnemonic('F'); + fileMenu.setMnemonic('T'); + + viewMenu.add(getTableProperties()); + + this.add(viewMenu); + } + + private void initCompareMenu(TableFrame frame) { + setCompareOriginal(new JRadioButtonMenuItem("Show Changes")); + getCompareOriginal().setToolTipText("Compares the current values to the original or revert point values."); + setCompareMap(new JRadioButtonMenuItem("Compare to Another Map")); + getCompareMap().setToolTipText("Compares this table and a selected table."); + setSimilarOpenTables(new JMenu("Compare to Table")); + getSimilarOpenTables().setToolTipText("Compares this table to a similar table."); + + setCompareOff(new JRadioButtonMenuItem("Off")); + + setComparePercent(new JRadioButtonMenuItem("Percent Difference")); + setCompareAbsolute(new JRadioButtonMenuItem("Absolute Difference")); + compareDisplayGroup = new ButtonGroup(); + compareDisplayGroup.add(getComparePercent()); + compareDisplayGroup.add(getCompareAbsolute()); + compareDisplay = new JMenu("Display"); + compareDisplay.add(getComparePercent()); + compareDisplay.add(getCompareAbsolute()); + + setCompareToOriginal(new JRadioButtonMenuItem("Compare to Original Value")); + getCompareToOriginal().setToolTipText("Compares this table to the selected table's original or revert point values."); + setCompareToBin(new JRadioButtonMenuItem("Compare to Bin Value")); + getCompareToBin().setToolTipText("Compares this table to the selected table's current values."); + compareToGroup = new ButtonGroup(); + compareToGroup.add(getCompareToOriginal()); + compareToGroup.add(getCompareToBin()); + compareToValue = new JMenu("Compare to"); + compareToValue.add(getCompareToOriginal()); + compareToValue.add(getCompareToBin()); + + compareMenu.add(getCompareOriginal()); + compareMenu.add(getCompareMap()); + compareMenu.add(getSimilarOpenTables()); + compareMenu.add(getCompareOff()); + compareMenu.add(new JSeparator()); + compareMenu.add(compareDisplay); + compareMenu.add(new JSeparator()); + compareMenu.add(compareToValue); + + compareMenu.setMnemonic('C'); + getCompareOriginal().setMnemonic('C'); + getCompareMap().setMnemonic('M'); + getCompareOff().setMnemonic('O'); + compareDisplay.setMnemonic('D'); + getComparePercent().setMnemonic('P'); + getCompareAbsolute().setMnemonic('A'); + getSimilarOpenTables().setMnemonic('S'); + compareToValue.setMnemonic('T'); + getCompareToOriginal().setMnemonic('R'); + getCompareToOriginal().setMnemonic('B'); + + getCompareOff().setSelected(true); + getCompareAbsolute().setSelected(true); + getCompareToOriginal().setSelected(true); + + initCompareGroup(); + + getCompareOriginal().addActionListener(frame); + getCompareMap().addActionListener(frame); + getCompareOff().addActionListener(frame); + getComparePercent().addActionListener(frame); + getCompareAbsolute().addActionListener(frame); + getCompareToOriginal().addActionListener(frame); + getCompareToBin().addActionListener(frame); + } + + public void initCompareGroup() { + compareGroup = new ButtonGroup(); + + compareGroup.add(getCompareOriginal()); + compareGroup.add(getCompareMap()); + compareGroup.add(getCompareOff()); + + for(int i = 0; i< getSimilarOpenTables().getItemCount(); i++) { + compareGroup.add(getSimilarOpenTables().getItem(i)); + } + } + + private void applyTableTypeRules(TableFrame frame) { + // Hide items that don't work with a DTC tables. + if(frame.getTable().getType() == Settings.TABLE_SWITCH) { + editMenu.setEnabled(false); + getCompareOriginal().setEnabled(false); + getComparePercent().setEnabled(false); + getCompareAbsolute().setEnabled(false); + getCompareToOriginal().setEnabled(false); + getCompareToBin().setEnabled(false); + } + } + + public JMenuItem getUndoAll() { + return undoAll; + } + + public void setUndoAll(JMenuItem undoAll) { + this.undoAll = undoAll; + } + + public JMenuItem getRevert() { + return revert; + } + + public void setRevert(JMenuItem revert) { + this.revert = revert; + } + + public JMenuItem getUndoSel() { + return undoSel; + } + + public void setUndoSel(JMenuItem undoSel) { + this.undoSel = undoSel; + } + + public JMenuItem getClose() { + return close; + } + + public void setClose(JMenuItem close) { + this.close = close; + } + + public JMenuItem getTableProperties() { + return tableProperties; + } + public void setTableProperties(JMenuItem tableProperties) { + this.tableProperties = tableProperties; + } + + public JMenuItem getCopySel() { + return copySel; + } + + public void setCopySel(JMenuItem copySel) { + this.copySel = copySel; + } + + public JMenuItem getCopyTable() { + return copyTable; + } + + public void setCopyTable(JMenuItem copyTable) { + this.copyTable = copyTable; + } + + public JMenuItem getPaste() { + return paste; + } + + public void setPaste(JMenuItem paste) { + this.paste = paste; + } + + public JRadioButtonMenuItem getCompareOff() { + return compareOff; + } + + public void setCompareOff(JRadioButtonMenuItem compareOff) { + this.compareOff = compareOff; + } + + public JRadioButtonMenuItem getCompareAbsolute() { + return compareAbsolute; + } + + public void setCompareAbsolute(JRadioButtonMenuItem compareAbsolute) { + this.compareAbsolute = compareAbsolute; + } + + public JRadioButtonMenuItem getComparePercent() { + return comparePercent; + } + + public void setComparePercent(JRadioButtonMenuItem comparePercent) { + this.comparePercent = comparePercent; + } + + public JRadioButtonMenuItem getCompareOriginal() { + return compareOriginal; + } + + public void setCompareOriginal(JRadioButtonMenuItem compareOriginal) { + this.compareOriginal = compareOriginal; + } + + public JRadioButtonMenuItem getCompareToOriginal() { + return compareToOriginal; + } + + public void setCompareToOriginal(JRadioButtonMenuItem compareToOriginal) { + this.compareToOriginal = compareToOriginal; + } + + public JRadioButtonMenuItem getCompareMap() { + return compareMap; + } + + public void setCompareMap(JRadioButtonMenuItem compareMap) { + this.compareMap = compareMap; + } + + public JRadioButtonMenuItem getCompareToBin() { + return compareToBin; + } + + public void setCompareToBin(JRadioButtonMenuItem compareToBin) { + this.compareToBin = compareToBin; + } + + public JMenu getSimilarOpenTables() { + return similarOpenTables; + } + + public void setSimilarOpenTables(JMenu similarOpenTables) { + this.similarOpenTables = similarOpenTables; + } + + public JMenuItem getInterp() { + return interp; + } + + public void setInterp(JMenuItem interp) { + this.interp = interp; + } + + public JMenuItem getHorizInterp() { + return this.horizInterp; + } + + public void setHorizInterp(JMenuItem horizInterp) { + this.horizInterp = horizInterp; + } + + public JMenuItem getVertInterp() { + return this.vertInterp; + } + + public void setVertInterp(JMenuItem vertInterp) { + this.vertInterp = vertInterp; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/TableMenuItem.java b/java_console/romraider/src/com/romraider/swing/TableMenuItem.java new file mode 100644 index 0000000000..52bfaf514e --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TableMenuItem.java @@ -0,0 +1,12 @@ +package com.romraider.swing; + +import javax.swing.JRadioButtonMenuItem; + +public class TableMenuItem extends JRadioButtonMenuItem{ + + private static final long serialVersionUID = -3618983591185294967L; + + public TableMenuItem(String itemName) { + super(itemName); + } +} diff --git a/java_console/romraider/src/com/romraider/swing/TablePropertyPanel.java b/java_console/romraider/src/com/romraider/swing/TablePropertyPanel.java new file mode 100644 index 0000000000..cee0f9cb02 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TablePropertyPanel.java @@ -0,0 +1,362 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import java.util.HashMap; +import java.util.Map; +import java.util.Vector; + +import javax.swing.GroupLayout; +import javax.swing.GroupLayout.Alignment; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.LayoutStyle.ComponentPlacement; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumn; + +import com.romraider.Settings; +import com.romraider.maps.Scale; +import com.romraider.maps.Table; +import com.romraider.maps.TableSwitch; + +public class TablePropertyPanel extends javax.swing.JPanel { + + private static final long serialVersionUID = -5817685772039277602L; + + public TablePropertyPanel(Table table) { + initComponents(); + setVisible(true); + + category.setText(table.getCategory()); + + int dim; + if (Settings.TABLE_SWITCH == table.getType()) { + dim = 1; + storageSize.setText("switch"); + scrollPane.setViewportView(populateScalesTable( + ((TableSwitch) table).getSwitchStates())); + } + else { + if (Settings.STORAGE_TYPE_FLOAT == table.getStorageType()) { + storageSize.setText("float"); + } + else { + String dataType; + if (table.isSignedData()) { + dataType = "int"; + } + else { + dataType = "uint"; + } + storageSize.setText(dataType + (table.getStorageType() * 8)); + } + dim = table.getType(); + scrollPane.setViewportView(populateScalesTable(table.getScales())); + } + + tableName.setText(String.format("%s (%dD)", table.getName(), dim)); + storageAddress.setText("0x" + Integer.toHexString(table.getStorageAddress())); + + if (table.getEndian() == Settings.ENDIAN_BIG) { + endian.setText("big"); + } else { + endian.setText("little"); + } + + description.setText(table.getDescription()); + + if (table.getUserLevel() == 1) { + userLevel.setText("Beginner"); + } else if (table.getUserLevel() == 2) { + userLevel.setText("Intermediate"); + } else if (table.getUserLevel() == 3) { + userLevel.setText("Advanced"); + } else if (table.getUserLevel() == 4) { + userLevel.setText("All"); + } else if (table.getUserLevel() == 5) { + userLevel.setText("Debug"); + } + + logIDscrollPane.setViewportView(populateLogParamTable(table.getLogParamString())); +} + + // //GEN-BEGIN:initComponents + private void initComponents() { + lblTable = new javax.swing.JLabel(); + tableName = new javax.swing.JLabel(); + lblCategory = new javax.swing.JLabel(); + category = new javax.swing.JLabel(); + jPanel1 = new javax.swing.JPanel(); + jPanel2 = new javax.swing.JPanel(); + lblStorageAddress = new javax.swing.JLabel(); + lblStorageSize = new javax.swing.JLabel(); + lblEndian = new javax.swing.JLabel(); + endian = new javax.swing.JLabel(); + storageSize = new javax.swing.JLabel(); + storageAddress = new javax.swing.JLabel(); + jPanel3 = new javax.swing.JPanel(); + jScrollPane1 = new javax.swing.JScrollPane(); + description = new javax.swing.JTextArea(); + jLabel5 = new javax.swing.JLabel(); + userLevel = new javax.swing.JLabel(); + scrollPane = new JScrollPane(); + logIDscrollPane = new JScrollPane(); + + setAutoscrolls(true); + setFont(new java.awt.Font("Tahoma", 0, 12)); + setInheritsPopupMenu(true); + lblTable.setText("Table:"); + lblTable.setFocusable(false); + + tableName.setText("Tablename (3D)"); + tableName.setFocusable(false); + + lblCategory.setText("Category:"); + lblCategory.setFocusable(false); + + category.setText("Category"); + category.setFocusable(false); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Conversions"))); + + GroupLayout jPanel1Layout = new GroupLayout(jPanel1); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(Alignment.LEADING) + .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(Alignment.LEADING) + .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE) + ); + + jPanel1.setLayout(jPanel1Layout); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Storage")); + lblStorageAddress.setText("Storage Address:"); + lblStorageAddress.setFocusable(false); + + lblStorageSize.setText("Data Type:"); + lblStorageSize.setFocusable(false); + + lblEndian.setText("Endian:"); + lblEndian.setFocusable(false); + + endian.setText("little"); + endian.setFocusable(false); + + storageSize.setText("unkn"); + storageSize.setFocusable(false); + + storageAddress.setText("0x00"); + storageAddress.setFocusable(false); + + org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(lblStorageAddress) + .add(lblStorageSize) + .add(lblEndian)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(endian) + .add(storageSize) + .add(storageAddress)) + .addContainerGap(28, Short.MAX_VALUE)) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(jPanel2Layout.createSequentialGroup() + .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblStorageSize) + .add(storageSize)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblStorageAddress) + .add(storageAddress)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(lblEndian) + .add(endian)) + .addContainerGap(37, Short.MAX_VALUE)) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Description")); + jScrollPane1.setBorder(null); + description.setBackground(new java.awt.Color(236, 233, 216)); + description.setColumns(20); + description.setEditable(false); + description.setFont(new java.awt.Font("Tahoma", 0, 11)); + description.setLineWrap(true); + description.setRows(5); + description.setText("Description"); + description.setWrapStyleWord(true); + description.setBorder(null); + description.setOpaque(false); + description.setRequestFocusEnabled(false); + jScrollPane1.setViewportView(description); + + org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(jPanel3Layout.createSequentialGroup() + .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE) + .addContainerGap()) + ); + + jLabel5.setText("User Level:"); + + userLevel.setText("Beginner"); + + lblLogId = new JLabel("Log Param:"); + + GroupLayout layout = new GroupLayout(this); + layout.setHorizontalGroup( + layout.createParallelGroup(Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(Alignment.LEADING) + .addComponent(lblCategory) + .addComponent(lblTable) + .addComponent(lblLogId)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(Alignment.TRAILING) + .addComponent(tableName, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE) + .addComponent(category, GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE) + .addComponent(logIDscrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 300, 300))) + .addGroup(layout.createSequentialGroup() + .addComponent(jLabel5) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(userLevel, GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)) + .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE) + .addComponent(jPanel2, GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE) + .addComponent(jPanel3, GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(Alignment.BASELINE) + .addComponent(tableName) + .addComponent(lblTable)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblCategory) + .addComponent(category)) + .addGap(6) + .addGroup(layout.createParallelGroup(Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(userLevel)) + .addPreferredGap(ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(Alignment.BASELINE) + .addComponent(lblLogId) + .addComponent(logIDscrollPane, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)) + .addGap(8) + .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(jPanel3, GroupLayout.PREFERRED_SIZE, 93, GroupLayout.PREFERRED_SIZE) + .addGap(23)) + ); + this.setLayout(layout); + }// //GEN-END:initComponents + private javax.swing.JLabel category; + private javax.swing.JTextArea description; + private javax.swing.JLabel endian; + private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JLabel lblCategory; + private javax.swing.JLabel lblEndian; + private javax.swing.JLabel lblStorageAddress; + private javax.swing.JLabel lblStorageSize; + private javax.swing.JLabel lblTable; + private javax.swing.JLabel storageAddress; + private javax.swing.JLabel storageSize; + private javax.swing.JLabel tableName; + private javax.swing.JLabel userLevel; + private JScrollPane scrollPane; + private JLabel lblLogId; + private JScrollPane logIDscrollPane; + + private JTable populateScalesTable(Vector scales) { + final ScalesTableModel scalesModel = new ScalesTableModel(); + scalesModel.setScalesList(scales); + return createScalesTable(scalesModel); + } + + private JTable populateScalesTable(Map switchStates) { + final SwitchStateTableModel scalesModel = new SwitchStateTableModel(); + scalesModel.setScalesList(switchStates); + return createScalesTable(scalesModel); + } + + private JTable createScalesTable(DefaultTableModel tableModel) { + final JTable table = new JTable(tableModel); + table.setAutoCreateRowSorter(false); + table.setColumnSelectionAllowed(false); + table.setRowSelectionAllowed(true); + table.setFillsViewportHeight(true); + return table; + } + + private JTable populateLogParamTable(String logParams) { + final Map paramMap = new HashMap(); + final String[] paramEntries = logParams.split(", "); + for (String entry : paramEntries) { + final String[] entries = entry.split(":"); + if(!paramMap.containsKey(entries[0])){ + paramMap.put(entries[0], entries.length > 1 ? entries[1] : "n/a"); + } + } + final ParameterIdsTableModel tableModel = new ParameterIdsTableModel(); + tableModel.setParameterList(paramMap); + final JTable table = new JTable(tableModel); + TableColumn column = null; + for (int i = 0; i < table.getColumnCount(); i++) { + column = table.getColumnModel().getColumn(i); + if (i == 0) { + column.setPreferredWidth(240); + } else { + column.setPreferredWidth(80); + } + } + table.setAutoCreateRowSorter(false); + table.setColumnSelectionAllowed(false); + table.setRowSelectionAllowed(true); + table.setFillsViewportHeight(true); + return table; + } +} diff --git a/java_console/romraider/src/com/romraider/swing/TableToolBar.java b/java_console/romraider/src/com/romraider/swing/TableToolBar.java new file mode 100644 index 0000000000..7679535c36 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TableToolBar.java @@ -0,0 +1,794 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import static javax.swing.BorderFactory.createLineBorder; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Image; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.beans.PropertyVetoException; +import java.math.BigDecimal; +import java.net.URL; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.util.Vector; + +import javax.naming.NameNotFoundException; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JFormattedTextField; +import javax.swing.JInternalFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +import org.apache.log4j.Logger; + +//import com.ecm.graphics.Graph3dFrameManager; +//import com.ecm.graphics.data.GraphData; +//import com.ecm.graphics.data.GraphDataListener; +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.maps.DataCell; +import com.romraider.maps.Scale; +import com.romraider.maps.Table; +import com.romraider.maps.Table1D; +import com.romraider.maps.Table3D; +import com.romraider.util.SettingsManager; + +public class TableToolBar extends JToolBar implements MouseListener, ItemListener, ActionListener +// , GraphDataListener +{ + + private static final long serialVersionUID = 8697645329367637930L; + private static final Logger LOGGER = Logger.getLogger(TableToolBar.class); + private final JButton incrementFine = new JButton(); + private final JButton decrementFine = new JButton(); + private final JButton incrementCoarse = new JButton(); + private final JButton decrementCoarse = new JButton(); + private final JButton enable3d = new JButton(); + private final JButton colorCells = new JButton(); + private final JButton refreshCompare = new JButton(); + + private final JButton setValue = new JButton("Set"); + private final JButton multiply = new JButton("Mul"); + + private final JFormattedTextField incrementByFine = new JFormattedTextField(new DecimalFormat("#.####")); + private final JFormattedTextField incrementByCoarse = new JFormattedTextField(new DecimalFormat("#.####")); + private final JFormattedTextField setValueText = new JFormattedTextField(new DecimalFormat("#.####")); + + private final JComboBox scaleSelection = new JComboBox(); + + private final JPanel liveDataPanel = new JPanel(); + private final JCheckBox overlayLog = new JCheckBox("Overlay Log"); + private final JButton clearOverlay = new JButton("Clear Overlay"); + private final JLabel liveDataValue = new JLabel(); + + private final URL incrementFineImage = getClass().getResource("/graphics/icon-incfine.png"); + private final URL decrementFineImage = getClass().getResource("/graphics/icon-decfine.png"); + private final URL incrementCoarseImage = getClass().getResource("/graphics/icon-inccoarse.png"); + private final URL decrementCoarseImage = getClass().getResource("/graphics/icon-deccoarse.png"); + private final URL enable3dImage = getClass().getResource("/graphics/3d_render.png"); + private final URL colorCellImage = getClass().getResource("/graphics/icon-palette.png"); + private final URL refreshCompareImage = getClass().getResource("/graphics/table_refresh.png"); + + private final TitledBorder toolbarBorder = BorderFactory.createTitledBorder(Settings.defaultTableToolBarName); + + private Table selectedTable = null; + + public TableToolBar() { + super(Settings.defaultTableToolBarName); + this.setFloatable(true); + this.setRollover(true); + FlowLayout toolBarLayout = new FlowLayout(FlowLayout.LEFT, 0, 0); + this.setLayout(toolBarLayout); + + setBorder(toolbarBorder); + + this.updateIcons(); + + JPanel finePanel = new JPanel(); + finePanel.add(incrementFine); + finePanel.add(decrementFine); + finePanel.add(incrementByFine); + this.add(finePanel); + + JPanel coarsePanel = new JPanel(); + coarsePanel.add(incrementCoarse); + coarsePanel.add(decrementCoarse); + coarsePanel.add(incrementByCoarse); + this.add(coarsePanel); + + JPanel setValuePanel = new JPanel(); + setValuePanel.add(setValueText); + setValuePanel.add(setValue); + setValuePanel.add(multiply); + this.add(setValuePanel); + + colorCells.setEnabled(false); + refreshCompare.setEnabled(false); + enable3d.setEnabled(false); + + JPanel otherPanel = new JPanel(); + otherPanel.add(colorCells); + otherPanel.add(refreshCompare); + otherPanel.add(enable3d); + this.add(otherPanel); + + JPanel scaleSelectionPanel = new JPanel(); + scaleSelectionPanel.add(scaleSelection); + this.add(scaleSelectionPanel); + + incrementFine.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + decrementFine.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + incrementCoarse.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + decrementCoarse.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + + enable3d.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + setValue.setPreferredSize(new Dimension(33, 23)); + setValue.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + multiply.setPreferredSize(new Dimension(33, 23)); + multiply.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + + colorCells.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + refreshCompare.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + + scaleSelection.setPreferredSize(new Dimension(80, 23)); + + clearOverlay.setPreferredSize(new Dimension(75, 23)); + clearOverlay.setBorder(createLineBorder(new Color(150, 150, 150), 1)); + + incrementByFine.setAlignmentX(JTextArea.CENTER_ALIGNMENT); + incrementByFine.setAlignmentY(JTextArea.CENTER_ALIGNMENT); + incrementByFine.setPreferredSize(new Dimension(45, 23)); + incrementByCoarse.setAlignmentX(JTextArea.CENTER_ALIGNMENT); + incrementByCoarse.setAlignmentY(JTextArea.CENTER_ALIGNMENT); + incrementByCoarse.setPreferredSize(new Dimension(45, 23)); + setValueText.setAlignmentX(JTextArea.CENTER_ALIGNMENT); + setValueText.setAlignmentY(JTextArea.CENTER_ALIGNMENT); + setValueText.setPreferredSize(new Dimension(45, 23)); + + incrementFine.setToolTipText("Increment Value (Fine)"); + decrementFine.setToolTipText("Decrement Value (Fine)"); + incrementCoarse.setToolTipText("Increment Value (Coarse)"); + decrementCoarse.setToolTipText("Decrement Value (Coarse)"); + enable3d.setToolTipText("Render data in 3d"); + setValue.setToolTipText("Set Absolute Value"); + setValueText.setToolTipText("Set Absolute Value"); + incrementByFine.setToolTipText("Fine Value Adjustment"); + incrementByCoarse.setToolTipText("Coarse Value Adjustment"); + multiply.setToolTipText("Multiply Value"); + overlayLog.setToolTipText("Enable Overlay Of Real Time Log Data"); + clearOverlay.setToolTipText("Clear Log Data Overlay Highlights"); + colorCells.setToolTipText("Color Table Cells"); + refreshCompare.setToolTipText("Refresh Table Compare"); + + incrementFine.addMouseListener(this); + decrementFine.addMouseListener(this); + incrementCoarse.addMouseListener(this); + decrementCoarse.addMouseListener(this); + enable3d.addMouseListener(this); + setValue.addMouseListener(this); + multiply.addMouseListener(this); + scaleSelection.addItemListener(this); + overlayLog.addItemListener(this); + clearOverlay.addActionListener(this); + colorCells.addMouseListener(this); + refreshCompare.addMouseListener(this); + + // key binding actions + Action enterAction = new AbstractAction() { + private static final long serialVersionUID = -6008026264821746092L; + + @Override + public void actionPerformed(ActionEvent e) { + JInternalFrame selectedFrame = ECUEditorManager.getECUEditor().getRightPanel().getSelectedFrame(); + if(selectedFrame == null || !(selectedFrame instanceof TableFrame)) { + return; + } + TableFrame frame = (TableFrame)selectedFrame; + frame.toFront(); + try { + frame.setSelected(true); + } catch (PropertyVetoException ex) { + } + frame.requestFocusInWindow(); + setValue(frame.getTable()); + } + }; + + // set input mapping + InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW); + + KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); + + im.put(enter, "enterAction"); + getActionMap().put(im.get(enter), enterAction); + + liveDataPanel.add(overlayLog); + liveDataPanel.add(clearOverlay); + //liveDataPanel.add(liveDataValue); + this.add(liveDataPanel); + overlayLog.setEnabled(false); + clearOverlay.setEnabled(false); + + incrementFine.getInputMap().put(enter, "enterAction"); + decrementFine.getInputMap().put(enter, "enterAction"); + incrementCoarse.getInputMap().put(enter, "enterAction"); + decrementCoarse.getInputMap().put(enter, "enterAction"); + incrementByFine.getInputMap().put(enter, "enterAction"); + incrementByCoarse.getInputMap().put(enter, "enterAction"); + setValueText.getInputMap().put(enter, "enterAction"); + setValue.getInputMap().put(enter, "enterAction"); + + this.setEnabled(true); + } + + public void updateIcons() { + Settings settings = SettingsManager.getSettings(); + incrementFine.setIcon(rescaleImageIcon(new ImageIcon(incrementFineImage), settings.getTableIconScale())); + decrementFine.setIcon(rescaleImageIcon(new ImageIcon(decrementFineImage), settings.getTableIconScale())); + incrementCoarse.setIcon(rescaleImageIcon(new ImageIcon(incrementCoarseImage), settings.getTableIconScale())); + decrementCoarse.setIcon(rescaleImageIcon(new ImageIcon(decrementCoarseImage), settings.getTableIconScale())); + enable3d.setIcon(rescaleImageIcon(new ImageIcon(enable3dImage), settings.getTableIconScale())); + colorCells.setIcon(rescaleImageIcon(new ImageIcon(colorCellImage), settings.getTableIconScale())); + refreshCompare.setIcon(rescaleImageIcon(new ImageIcon(refreshCompareImage), settings.getTableIconScale())); + } + + private ImageIcon rescaleImageIcon(ImageIcon imageIcon, int percentOfOriginal) { + int newHeight = (int) (imageIcon.getImage().getHeight(this) * (percentOfOriginal * .01)); + int newWidth = (int) (imageIcon.getImage().getWidth(this) * (percentOfOriginal * .01)); + + imageIcon.setImage(imageIcon.getImage().getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH)); + return imageIcon; + } + + public Table getTable() { + JInternalFrame frame = ECUEditorManager.getECUEditor().getRightPanel().getSelectedFrame(); + if(null == frame) { + return null; + } + + if( !(frame instanceof TableFrame) ) { + return null; + } + + + return ((TableFrame)frame).getTable(); + } + + @Override + public void setBorder(Border border) { + if(SettingsManager.getSettings().isShowTableToolbarBorder()) { + super.setBorder(toolbarBorder); + } else { + super.setBorder(BorderFactory.createEmptyBorder()); + } + } + + public void updateTableToolBar() { + this.updateTableToolBar(getTable()); + } + + public void updateTableToolBar(Table selectedTable) { + if(selectedTable == null && this.selectedTable == null) { + // Skip if the table is the same to avoid multiple updates + return; + } else if(selectedTable == null || this.selectedTable == null) { + // Update the toolbar. + } else if(this.selectedTable.equals(selectedTable)) { + // Skip if the table is the same to avoid multiple updates + return; + } + + this.selectedTable = selectedTable; + + setBorder(toolbarBorder); + + if(null == selectedTable) + { + // disable the toolbar. + toggleTableToolBar(selectedTable); + return; + } + + updateToolbarIncrementDecrementValues(); + + this.overlayLog.setSelected(selectedTable.getOverlayLog()); + this.enable3d.setEnabled(selectedTable.getType() == Settings.TABLE_3D); + + setScales(selectedTable.getScales()); + + if(null == selectedTable.getCurrentScale()) + { + this.scaleSelection.setSelectedItem("Default"); + } else { + this.scaleSelection.setSelectedItem(selectedTable.getCurrentScale().getName()); + } + + toggleTableToolBar(selectedTable); + } + + private void updateToolbarIncrementDecrementValues() { + if(null == selectedTable) { + return; + } + + double fineIncrement = 0; + double coarseIncrement = 0; + + try { + // enable the toolbar. + fineIncrement = Math.abs(selectedTable.getCurrentScale().getFineIncrement()); + coarseIncrement = Math.abs(selectedTable.getCurrentScale().getCoarseIncrement()); + } catch (Exception ex) { + // scaling units haven't been added yet -- no problem + } + + incrementByFine.setValue(fineIncrement); + incrementByCoarse.setValue(coarseIncrement); + } + + private void toggleTableToolBar(Table currentTable) { + String newTitle = ""; + boolean enabled; + + if(null == currentTable) { + enabled = false; + } else { + if(currentTable instanceof Table1D) { + Table1D cur1DTable = (Table1D)currentTable; + if(cur1DTable.isAxis()) { + newTitle = cur1DTable.getAxisParent().getName() + " ("+ cur1DTable.getName() +")"; + } else { + newTitle = currentTable.getName(); + } + } else { + newTitle = currentTable.getName(); + } + + enabled = true; + } + + toolbarBorder.setTitle(newTitle); + + incrementFine.setEnabled(enabled); + decrementFine.setEnabled(enabled); + incrementCoarse.setEnabled(enabled); + decrementCoarse.setEnabled(enabled); + + setValue.setEnabled(enabled); + multiply.setEnabled(enabled); + + incrementByFine.setEnabled(enabled); + incrementByCoarse.setEnabled(enabled); + setValueText.setEnabled(enabled); + + scaleSelection.setEnabled(enabled); + + liveDataValue.setEnabled(enabled); + + colorCells.setEnabled(enabled); + refreshCompare.setEnabled(enabled); + + //Only enable the 3d button if table includes 3d data + if (null != currentTable && currentTable.getType() == Settings.TABLE_3D && enabled) { + enable3d.setEnabled(true); + } + else{ + enable3d.setEnabled(false); + } + + if(null != currentTable && null != currentTable.getCompareTable() && enabled) { + refreshCompare.setEnabled(true); + } else { + refreshCompare.setEnabled(false); + } + + if (null != currentTable && currentTable.isLiveDataSupported() && enabled) { + overlayLog.setEnabled(true); + clearOverlay.setEnabled(true); + } + else{ + overlayLog.setEnabled(false); + clearOverlay.setEnabled(false); + } + + if(null != currentTable && currentTable.isStaticDataTable()) { + if(enabled) { + scaleSelection.setEnabled(true); + } else { + scaleSelection.setEnabled(false); + } + + // Disable everything that does not apply to static value tables. + colorCells.setEnabled(false); + refreshCompare.setEnabled(false); + + incrementFine.setEnabled(false); + decrementFine.setEnabled(false); + incrementCoarse.setEnabled(false); + decrementCoarse.setEnabled(false); + incrementByFine.setEnabled(false); + incrementByCoarse.setEnabled(false); + setValue.setEnabled(false); + setValueText.setEnabled(false); + multiply.setEnabled(false); + enable3d.setEnabled(false); + } + + + repaint(); + } + + public void setScales(Vector scales) { + + // remove item listener to avoid null pointer exception when populating + scaleSelection.removeItemListener(this); + scaleSelection.removeAllItems(); + + for (Scale scale : scales) { + scaleSelection.addItem(scale.getName()); + } + + // and put it back + scaleSelection.addItemListener(this); + } + + @Override + public void mouseClicked(MouseEvent e) { + Table curTable = getSelectedTable(); + if(null == curTable) + { + return; + } + + if (e.getSource() == incrementCoarse) { + incrementCoarse(curTable); + } else if (e.getSource() == decrementCoarse) { + decrementCoarse(curTable); + } else if (e.getSource() == enable3d) { + enable3d(curTable); + } else if (e.getSource() == incrementFine) { + incrementFine(curTable); + } else if (e.getSource() == decrementFine) { + decrementFine(curTable); + } else if (e.getSource() == multiply) { + multiply(curTable); + } else if (e.getSource() == setValue) { + setValue(curTable); + } else if (e.getSource() == colorCells) { + colorCells(curTable); + } else if (e.getSource() == refreshCompare) { + refreshCompare(curTable); + } + } + + public void setValue(Table currentTable) { + currentTable.setRealValue(setValueText.getText()); + } + + public void multiply() { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + multiply(curTable); + } + + public void multiply(Table currentTable) { + try{ + currentTable.multiply(Double.parseDouble(setValueText.getText())); + }catch(NumberFormatException nex) { + // Do Nothing. setValueText is null or not a valid double. + } + } + + public void incrementFine() { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + incrementFine(curTable); + } + + public void incrementFine(Table currentTable) { + currentTable.increment(Double.parseDouble(String.valueOf(incrementByFine.getValue()))); + } + + public void decrementFine() { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + decrementFine(curTable); + } + + public void decrementFine(Table currentTable) { + currentTable.increment(0 - Double.parseDouble(String.valueOf(incrementByFine.getValue()))); + } + + public void incrementCoarse() { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + incrementCoarse(curTable); + } + + public void incrementCoarse(Table currentTable) { + currentTable.increment(Double.parseDouble(String.valueOf(incrementByCoarse.getValue()))); + } + + public void decrementCoarse() { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + decrementCoarse(curTable); + } + + public void decrementCoarse(Table currentTable) { + currentTable.increment(0 - Double.parseDouble(String.valueOf(incrementByCoarse.getValue()))); + } + + /** + * Method launches a 3d Frame. + */ + public void enable3d(Table currentTable) { + int rowCount = 0; + int valueCount = 0; + + //Pull data into format 3d graph understands + Vector graphValues = new Vector(); + graphValues.clear(); + + if (currentTable.getType() == Settings.TABLE_3D) { + Table3D table3d = (Table3D) currentTable; + DataCell[][] tableData = table3d.get3dData(); + valueCount = tableData.length; + DataCell[] dataRow = tableData[0]; + rowCount = dataRow.length; + + for (int j = (rowCount - 1); j >= 0; j--) { + float[] rowValues = new float[valueCount]; + for (int i = 0; i < valueCount; i++) { + DataCell theCell = tableData[i][j]; + rowValues[i] = (float) theCell.getRealValue(); + } + graphValues.add(rowValues); + } + + Table1D xAxisTable1D = table3d.getXAxis(); + Table1D yAxisTable1D = table3d.getYAxis(); + + //Gather x axis values + DataCell[] dataCells = xAxisTable1D.getData(); + int length = dataCells.length; + double[] xValues = new double[length]; + + for (int i = 0; i < length; i++) { + xValues[i] = dataCells[i].getRealValue(); + } + + //Gather y/z axis values + dataCells = yAxisTable1D.getData(); + length = dataCells.length; + double[] yValues = new double[length]; + + for (int i = 0; i < length; i++) { + double theValue = dataCells[i].getRealValue(); + BigDecimal finalRoundedValue = new BigDecimal(theValue).setScale(2, BigDecimal.ROUND_HALF_UP); + yValues[i] = finalRoundedValue.doubleValue(); + } + + //Define Labels for graph + String xLabel = table3d.getXAxis().getName(); + String zLabel = table3d.getYAxis().getName(); + String yLabel = table3d.getCategory(); + + //TODO Figure out mix between heavy weight and lightweight components + //Below is initial work on making graph3d a JInternal Frame + /* + Graph3dJPanel graph3dJPanel = new Graph3dJPanel(graphValues, testX, testZ,xLabel, yLabel, zLabel); + graph3dJPanel.addModifiedDataListener(this); + JInternalFrame graphFrame = new JInternalFrame(); + graphFrame.add(graph3dJPanel); + graphFrame.setSize(200, 200); + + graphFrame.setFrameIcon(null); + graphFrame.setBorder(BorderFactory.createBevelBorder(0)); + graphFrame.setVisible(true); + graphFrame.setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE); + ECUEditorManager.getECUEditor().rightPanel.add(graphFrame); + */ + + // TODO: do we want to get the max/min allowed or the max/min current? + table3d.calcCellRanges(); + double maxV = table3d.getMaxReal(); + double minV = table3d.getMinReal(); + //TODO Remove this when above is working + //*********** + /*minV = 0.0; + maxV = 13.01;*/ + LOGGER.debug("Scale: " + maxV + "," + minV); + //*********** + + throw new UnsupportedOperationException(); +// Graph3dFrameManager.openGraph3dFrame(graphValues, minV, maxV, xValues, yValues, xLabel, yLabel, zLabel, currentTable.getName()); +// GraphData.addGraphDataListener(this); + } + } + + public void colorCells(Table currentTable) { + currentTable.colorCells(); + } + + public void refreshCompare(Table currentTable) { + currentTable.populateCompareValues(currentTable.getCompareTable()); + } + + public void setCoarseValue(double input) { + incrementByCoarse.setText(String.valueOf(input)); + try { + incrementByCoarse.commitEdit(); + } catch (ParseException ex) { + } + } + + public void setFineValue(double input) { + incrementByFine.setText(String.valueOf(input)); + try { + incrementByFine.commitEdit(); + } catch (ParseException ex) { + } + } + + public void focusSetValue(char input) { + setValueText.requestFocus(); + setValueText.setText(String.valueOf(input)); + } + + public void setInputMap(InputMap im) { + incrementFine.setInputMap(WHEN_FOCUSED, im); + decrementFine.setInputMap(WHEN_FOCUSED, im); + incrementCoarse.setInputMap(WHEN_FOCUSED, im); + decrementCoarse.setInputMap(WHEN_FOCUSED, im); + setValue.setInputMap(WHEN_FOCUSED, im); + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseReleased(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + + @Override + public void itemStateChanged(ItemEvent e) { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + + if (e.getSource() == scaleSelection) { + // scale changed + try { + + curTable.setScaleByName((String)scaleSelection.getSelectedItem()); + updateToolbarIncrementDecrementValues(); + } catch (NameNotFoundException e1) { + e1.printStackTrace(); + } + } else if (e.getSource() == overlayLog) { + // enable/disable log overlay and live data display + curTable.setOverlayLog(overlayLog.isSelected()); + } + } + + + @Override + public void actionPerformed(ActionEvent e) { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + + if (e.getSource() == clearOverlay) { + // clear log overlay + curTable.clearLiveDataTrace(); + } + } + + public void setLiveDataValue(String value) { + liveDataValue.setText(value); + } + + + // ****************************************** + // Code for listening to graph3d data changes + // ****************************************** + + //@Override + public void newGraphData(int x, int z, float value) { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + + if(curTable.getType() == Settings.TABLE_3D) { + Table3D table3d = (Table3D) curTable; + table3d.selectCellAt(x, table3d.getSizeY() - z - 1); + + //Set the value + table3d.setRealValue(String.valueOf(value)); + } + } + + //@Override + public void selectStateChange(int x, int z, boolean value) { + Table curTable = getSelectedTable(); + if(null == curTable) { + return; + } + + if(curTable.getType() == Settings.TABLE_3D) { + if (value) { + Table3D table3d = (Table3D) curTable; + table3d.selectCellAtWithoutClear(x, table3d.getSizeY() - z - 1); + } else { + Table3D table3d = (Table3D) curTable; + table3d.deSelectCellAt(x, table3d.getSizeY() - z - 1); + } + } + } + + public Table getSelectedTable() { + return this.selectedTable; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/TableTreeNode.java b/java_console/romraider/src/com/romraider/swing/TableTreeNode.java new file mode 100644 index 0000000000..0d35d80951 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/TableTreeNode.java @@ -0,0 +1,57 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.tree.DefaultMutableTreeNode; + +import com.romraider.maps.Table; + +public class TableTreeNode extends DefaultMutableTreeNode { + + private static final long serialVersionUID = 2824050968863990871L; + private String toolTip; + + public TableTreeNode(TableFrame tableFrame) { + super(tableFrame); + } + + public TableFrame getFrame() { + if(getUserObject() instanceof TableFrame) { + return (TableFrame)getUserObject(); + } + return null; + } + + public void setFrame(TableFrame tableFrame) { + this.setUserObject(tableFrame); + } + + public Table getTable() { + return this.getFrame().getTable(); + } + + public void setToolTipText(String input) { + toolTip = input; + } + + public String getToolTipText() { + return toolTip; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/XMLFilter.java b/java_console/romraider/src/com/romraider/swing/XMLFilter.java new file mode 100644 index 0000000000..d0d65e90a5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/XMLFilter.java @@ -0,0 +1,106 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing; + +import javax.swing.filechooser.FileFilter; +import java.io.File; +import java.util.Enumeration; +import java.util.Hashtable; + +public class XMLFilter extends FileFilter { + + private Hashtable filters = null; + private String description = null; + private String fullDescription = null; + private boolean useExtensionsInDescription = true; + + public XMLFilter() { + this.filters = new Hashtable(); + this.addExtension("xml"); + this.setDescription("ECU Definition Files"); + } + + public boolean accept(File f) { + if (f != null) { + if (f.isDirectory()) { + return true; + } + String extension = getExtension(f); + if (extension != null && filters.get(getExtension(f)) != null) { + return true; + } + ; + } + return false; + } + + public String getExtension(File f) { + if (f != null) { + String filename = f.getName(); + int i = filename.lastIndexOf('.'); + if (i > 0 && i < filename.length() - 1) { + return filename.substring(i + 1).toLowerCase(); + } + ; + } + return null; + } + + public void addExtension(String extension) { + filters.put(extension.toLowerCase(), this); + fullDescription = null; + } + + public String getDescription() { + if (fullDescription == null) { + if (description == null || isExtensionListInDescription()) { + fullDescription = description == null ? "(" : description + + " ("; + // build the description from the extension list + Enumeration extensions = filters.keys(); + if (extensions != null) { + fullDescription += "." + extensions.nextElement(); + while (extensions.hasMoreElements()) { + fullDescription += ", ." + + extensions.nextElement(); + } + } + fullDescription += ")"; + } else { + fullDescription = description; + } + } + return fullDescription; + } + + public void setDescription(String description) { + this.description = description; + fullDescription = null; + } + + public void setExtensionListInDescription(boolean b) { + useExtensionsInDescription = b; + fullDescription = null; + } + + public boolean isExtensionListInDescription() { + return useExtensionsInDescription; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/swing/menubar/Menu.java b/java_console/romraider/src/com/romraider/swing/menubar/Menu.java new file mode 100644 index 0000000000..a9de5ffa22 --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/menubar/Menu.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing.menubar; + +import javax.swing.JMenu; + +public final class Menu extends JMenu { + + private static final long serialVersionUID = -5058943622469501273L; + + public Menu(String text, int mnemonic) { + setText(text); + setMnemonic(mnemonic); + } +} diff --git a/java_console/romraider/src/com/romraider/swing/menubar/MenuItem.java b/java_console/romraider/src/com/romraider/swing/menubar/MenuItem.java new file mode 100644 index 0000000000..748e33c2ab --- /dev/null +++ b/java_console/romraider/src/com/romraider/swing/menubar/MenuItem.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.swing.menubar; + +import javax.swing.Action; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + +public final class MenuItem extends JMenuItem { + + private static final long serialVersionUID = 8944116003490787227L; + + public MenuItem(String text, Action action) { + super(action); + setText(text); + } + + public MenuItem(String text, Action action, int mnemonic) { + super(action); + setText(text); + setMnemonic(mnemonic); + } + + public MenuItem(String text, Action action, int mnemonic, KeyStroke accelerator) { + this(text, action, mnemonic); + setAccelerator(accelerator); + } + +} diff --git a/java_console/romraider/src/com/romraider/util/AxisRange.java b/java_console/romraider/src/com/romraider/util/AxisRange.java new file mode 100644 index 0000000000..006e6a3557 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/AxisRange.java @@ -0,0 +1,39 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +public final class AxisRange { + private final int startIndex; + private final int endIndex; + + public AxisRange(int startIndex, int endIndex) { + this.startIndex = startIndex; + this.endIndex = endIndex; + } + + public int getStartIndex() { + return startIndex; + } + + public int getEndIndex() { + return endIndex; + } + +} diff --git a/java_console/romraider/src/com/romraider/util/ByteUtil.java b/java_console/romraider/src/com/romraider/util/ByteUtil.java new file mode 100644 index 0000000000..b8a5f8b486 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/ByteUtil.java @@ -0,0 +1,118 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import java.nio.ByteBuffer; +import java.util.List; + +public final class ByteUtil { + + private ByteUtil() { + throw new UnsupportedOperationException(); + } + + public static int asUnsignedInt(byte b) { + return asUnsignedInt(new byte[]{b}); + } + + public static int asSignedInt(byte[] bytes) { + int i = 0; + for (int j = 0; j < bytes.length; j++) { + if (j == 0) { + i |= bytes[j]; + } + else { + i <<= 8; + i |= bytes[j] & 0xFF; + } + } + return i; + } + + public static int asUnsignedInt(byte[] bytes) { + int i = 0; + for (int j = 0; j < bytes.length; j++) { + if (j > 0) { + i <<= 8; + } + i |= bytes[j] & 0xFF; + } + return i; + } + + public static byte asByte(int i) { + return Integer.valueOf(i).byteValue(); + } + + public static float asFloat(byte[] b, int offset, int length) { + final ByteBuffer buf = ByteBuffer.wrap(b, offset, length); + return buf.getFloat(); + } + + public static int asInt(byte b) { + return Byte.valueOf(b).intValue(); + } + + public static boolean matchOnes(byte b, int mask) { + return (b & mask) == mask; + } + + public static boolean matchZeroes(byte b, int mask) { + return (b & mask) == 0; + } + + public static void byteListToBytes(List buffer, byte[] response) { + for (int i = 0; i < buffer.size(); i++) { + response[i] = buffer.get(i); + } + } + + public static int indexOfBytes(byte[] bytes, byte[] pattern) { + int[] failure = computeFailure(pattern); + int j = 0; + for (int i = 0; i < bytes.length; i++) { + while (j > 0 && pattern[j] != bytes[i]) { + j = failure[j - 1]; + } + if (pattern[j] == bytes[i]) { + j++; + } + if (j == pattern.length) { + return i - pattern.length + 1; + } + } + return -1; + } + + private static int[] computeFailure(byte[] pattern) { + int[] failure = new int[pattern.length]; + int j = 0; + for (int i = 1; i < pattern.length; i++) { + while (j>0 && pattern[j] != pattern[i]) { + j = failure[j - 1]; + } + if (pattern[j] == pattern[i]) { + j++; + } + failure[i] = j; + } + return failure; + } +} diff --git a/java_console/romraider/src/com/romraider/util/ColorScaler.java b/java_console/romraider/src/com/romraider/util/ColorScaler.java new file mode 100644 index 0000000000..42b2a0afec --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/ColorScaler.java @@ -0,0 +1,62 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import java.awt.Color; + +import com.romraider.Settings; + +public final class ColorScaler { + + private ColorScaler() { + } + + public static Color getScaledColor(double scale) { + + Settings settings = SettingsManager.getSettings(); + if(0.0 == scale) { + return settings.getMinColor(); + } + + if(Double.NaN == scale) { + return settings.getMaxColor(); + } + + Color minColor = settings.getMinColor(); + Color maxColor = settings.getMaxColor(); + + float[] minColorHSB = new float[3]; + float[] maxColorHSB = new float[3]; + + rgbToHsb(minColor, minColorHSB); + rgbToHsb(maxColor, maxColorHSB); + + float h = minColorHSB[0] + (maxColorHSB[0] - minColorHSB[0]) * (float) scale; + float s = minColorHSB[1] + (maxColorHSB[1] - minColorHSB[1]) * (float) scale; + float b = minColorHSB[2] + (maxColorHSB[2] - minColorHSB[2]) * (float) scale; + + return Color.getHSBColor(h, s, b); + + } + + private static void rgbToHsb(Color color, float[] colorHSB) { + Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), colorHSB); + } +} diff --git a/java_console/romraider/src/com/romraider/util/FormatFilename.java b/java_console/romraider/src/com/romraider/util/FormatFilename.java new file mode 100644 index 0000000000..42f68e2835 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/FormatFilename.java @@ -0,0 +1,68 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import java.io.File; + +/** + * Shorten a long text file path for use in title bar or limited width display + * component. + */ +public final class FormatFilename { + private final static String separator = System.getProperty("file.separator"); + + private FormatFilename() { + } + + /** + * Shorten a text file path name if > 45 characters. + * @param file - the File to shorten the path name for. + * @return the shortened name + */ + public final static String getShortName(File file) { + String filePath = file.getAbsolutePath(); + if (filePath.length() > 45) { + filePath = getShortName(filePath); + } + return filePath; + } + + public final static String getShortName(String filePath) { + String regex = separator; + if (separator.equals("\\")) { + regex = "\\" + separator; + } + final String[] filePathParts = filePath.split(regex); + String logFileName = filePath; + if (filePathParts.length > 3) { + logFileName = String.format( + "%s%s%s...%s%s%s%s", + filePathParts[0], + separator, + filePathParts[1].substring(0, + Math.min(4, filePathParts[1].length())), + separator, + filePathParts[filePathParts.length - 2], + separator, + filePathParts[filePathParts.length - 1]); + } + return logFileName; + } +} diff --git a/java_console/romraider/src/com/romraider/util/HexUtil.java b/java_console/romraider/src/com/romraider/util/HexUtil.java new file mode 100644 index 0000000000..d40c7ead16 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/HexUtil.java @@ -0,0 +1,104 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +public final class HexUtil { + + private HexUtil() { + } + + public static String asHex(byte b) { + return asHex(new byte[]{b}); + } + + public static String asHex(byte[] in) { + return bytesToHex(in).toUpperCase(); + } + + public static byte[] asBytes(String hex) { + if (hex.indexOf(' ') >= 0) { + hex = hex.replaceAll(" ", ""); + } + if (hex.startsWith("0x")) { + hex = hex.substring(2); + } + return hexToBytes(hex); + } + + public static String bytesToHex(byte[] bs, int off, int length) { + StringBuffer sb = new StringBuffer(length * 2); + bytesToHexAppend(bs, off, length, sb); + return sb.toString(); + } + + public static void bytesToHexAppend(byte[] bs, int off, int length, StringBuffer sb) { + sb.ensureCapacity(sb.length() + length * 2); + for (int i = off; (i < (off + length)) && (i < bs.length); i++) { + sb.append(Character.forDigit((bs[i] >>> 4) & 0xf, 16)); + sb.append(Character.forDigit(bs[i] & 0xf, 16)); + } + } + + public static String bytesToHex(byte[] bs) { + return bytesToHex(bs, 0, bs.length); + } + + public static byte[] hexToBytes(String s) { + return hexToBytes(s, 0); + } + + public static byte[] hexToBytes(String s, int off) { + byte[] bs = new byte[off + (1 + s.length()) / 2]; + hexToBytes(s, bs, off); + return bs; + } + + public static void hexToBytes(String s, byte[] out, int off) throws NumberFormatException, IndexOutOfBoundsException { + int slen = s.length(); + if ((slen % 2) != 0) { + s = '0' + s; + } + if (out.length < off + slen / 2) { + throw new IndexOutOfBoundsException("Output buffer too small for input (" + out.length + "<" + off + slen / 2 + ")"); + } + // Safe to assume the string is even length + byte b1, b2; + for (int i = 0; i < slen; i += 2) { + b1 = (byte) Character.digit(s.charAt(i), 16); + b2 = (byte) Character.digit(s.charAt(i + 1), 16); + if ((b1 < 0) || (b2 < 0)) { + throw new NumberFormatException(); + } + out[off + i / 2] = (byte) (b1 << 4 | b2); + } + } + + public static int hexToInt(String input) { + if (input.length() > 2 && input.substring(0, 2).equalsIgnoreCase("0x")) { + return Integer.parseInt(input.substring(2), 16); + } else { + return Integer.parseInt(input, 16); + } + } + + public static String intToHexString(int input) { + return "0x" + Integer.toHexString(input).toUpperCase(); + } +} diff --git a/java_console/romraider/src/com/romraider/util/JEPUtil.java b/java_console/romraider/src/com/romraider/util/JEPUtil.java new file mode 100644 index 0000000000..bb7f128717 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/JEPUtil.java @@ -0,0 +1,48 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2014 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import org.nfunk.jep.JEP; +import java.util.Map; + +public final class JEPUtil { + + private JEPUtil() { + } + + public static double evaluate(String expression, double value) { + final JEP parser = new JEP(); + parser.addStandardFunctions(); + parser.initSymTab(); // clear the contents of the symbol table + parser.addVariable("x", value); + parser.parseExpression(expression); + return parser.getValue(); + } + + public static double evaluate(String expression, Map valueMap) { + final JEP parser = new JEP(); + parser.initSymTab(); // clear the contents of the symbol table + for (String id : valueMap.keySet()) { + parser.addVariable(id, valueMap.get(id)); + } + parser.parseExpression(expression); + return parser.getValue(); + } +} diff --git a/java_console/romraider/src/com/romraider/util/JREChecker.java b/java_console/romraider/src/com/romraider/util/JREChecker.java new file mode 100644 index 0000000000..571af836c5 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/JREChecker.java @@ -0,0 +1,59 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +/** + * @author Steve Wadsworth + * @since 2012-12-30 + * + * This class is intended to contain utility methods needed to determine various + * parameters of the JVM in which the application is running. + * + */ + +public final class JREChecker { + + /** + * Check to see if the JVM is 32-bit + * + * @return true if JVM is 32-bit + */ + public static boolean is32bit() { + // determine if we're running in a 32-bit JVM + // this may need to be extended for other JVM providers and versions + String bitness = System.getProperty("sun.arch.data.model", "unknown"); + // if we don't know, try harder - additional tests can be added here as + // necessary + if (bitness.equals("unknown")) { + // if sun.arch.data.model isn't found, we may be on a non-Sun + // (Oracle) VM try some other properties + if (System.getProperty("java.vm.name").indexOf("64") >= 0 || + System.getProperty("sun.cpu.isalist").indexOf("64") >= 0) { + bitness = "64"; + } + } + // should be either 32, 64, or still unknown. only known 32 should + // return true + if (bitness.equals("32")) { + return true; + } + return false; + } +} diff --git a/java_console/romraider/src/com/romraider/util/LogManager.java b/java_console/romraider/src/com/romraider/util/LogManager.java new file mode 100644 index 0000000000..4d3834ed1e --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/LogManager.java @@ -0,0 +1,33 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import static org.apache.log4j.PropertyConfigurator.configureAndWatch; + +public final class LogManager { + + private LogManager() { + throw new UnsupportedOperationException(); + } + + public static void initDebugLogging() { + configureAndWatch("log4j.properties"); + } +} diff --git a/java_console/romraider/src/com/romraider/util/MD5Checksum.java b/java_console/romraider/src/com/romraider/util/MD5Checksum.java new file mode 100644 index 0000000000..d283355b35 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/MD5Checksum.java @@ -0,0 +1,53 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.security.MessageDigest; + +public class MD5Checksum { + + public static byte[] createChecksum(String filename) throws Exception { + InputStream fis = new FileInputStream(filename); + + byte[] buffer = new byte[1024]; + MessageDigest complete = MessageDigest.getInstance("MD5"); + int numRead; + do { + numRead = fis.read(buffer); + if (numRead > 0) { + complete.update(buffer, 0, numRead); + } + } while (numRead != -1); + fis.close(); + return complete.digest(); + } + + public static String getMD5Checksum(String filename) throws Exception { + byte[] b = createChecksum(filename); + String result = ""; + for (int i = 0; i < b.length; i++) { + result += + Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); + } + return result; + } +} diff --git a/java_console/romraider/src/com/romraider/util/ObjectCloner.java b/java_console/romraider/src/com/romraider/util/ObjectCloner.java new file mode 100644 index 0000000000..46b12425da --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/ObjectCloner.java @@ -0,0 +1,96 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +public final class ObjectCloner { + + private ObjectCloner() { + } + + // returns a deep copy of an object + public static Object deepCopy(Object obj) throws Exception { + /*ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + ObjectOutputStream oos = new ObjectOutputStream(bos); + try { + ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); + try { + ObjectInputStream ois = new ObjectInputStream(bin); + try { + // serialize and pass the object + oos.writeObject(obj); + oos.flush(); + + // return the new object + return ois.readObject(); + + } finally { + ois.close(); + } + } finally { + bin.close(); + } + } finally { + oos.close(); + } + } finally { + bos.close(); + }*/ + + /*ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(obj); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bais); + Object deepCopy = ois.readObject(); + return deepCopy;*/ + + //obj2DeepCopy must be serializable + ObjectOutputStream outStream = null; + ObjectInputStream inStream = null; + + try { + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + outStream = new ObjectOutputStream(byteOut); + outStream.writeObject(obj); + outStream.flush(); + ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); + inStream = new ObjectInputStream(byteIn); + + // read the serialized, and deep copied, object and return it + return inStream.readObject(); + + } catch (Exception e) { + throw (e); + + } finally { + //always close your streams in finally clauses + outStream.close(); + inStream.close(); + } + + + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/util/ParamChecker.java b/java_console/romraider/src/com/romraider/util/ParamChecker.java new file mode 100644 index 0000000000..9e6c39c6c2 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/ParamChecker.java @@ -0,0 +1,99 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import java.util.Collection; +import java.util.Map; + +public final class ParamChecker { + + private ParamChecker() { + } + + public static void checkNotNull(Object param, String paramName) { + if (param == null) { + throw new IllegalArgumentException("Parameter " + paramName + " must not be null"); + } + } + + public static void checkNotNull(Object... params) { + for (int i = 0; i < params.length; i++) { + checkNotNull(params[i], "arg" + i); + } + } + + public static void checkNotNullOrEmpty(String param, String paramName) { + if (isNullOrEmpty(param)) { + throw new IllegalArgumentException("Parameter " + paramName + " must not be null or empty"); + } + } + + public static void checkNotNullOrEmpty(Object[] param, String paramName) { + if (param == null || param.length == 0) { + throw new IllegalArgumentException("Parameter " + paramName + " must not be null or empty"); + } + } + + public static void checkNotNullOrEmpty(Collection param, String paramName) { + if (param == null || param.isEmpty()) { + throw new IllegalArgumentException("Parameter " + paramName + " must not be null or empty"); + } + } + + public static void checkNotNullOrEmpty(Map param, String paramName) { + if (param == null || param.isEmpty()) { + throw new IllegalArgumentException("Parameter " + paramName + " must not be null or empty"); + } + } + + public static void checkGreaterThanZero(int param, String paramName) { + if (param <= 0) { + throw new IllegalArgumentException("Parameter " + paramName + " must be > 0"); + } + } + + public static void checkNotNullOrEmpty(byte[] param, String paramName) { + if (param == null || param.length == 0) { + throw new IllegalArgumentException("Parameter " + paramName + " must not be null or empty"); + } + } + + public static void checkBit(int bit) { + if (!isValidBit(bit)) { + throw new IllegalArgumentException("Bit must be between 0 and 7 inclusive."); + } + } + + public static boolean isNullOrEmpty(String param) { + return param == null || param.length() == 0; + } + + public static boolean isNullOrEmpty(Collection param) { + return param == null || param.isEmpty(); + } + + public static boolean isNullOrEmpty(Map param) { + return param == null || param.isEmpty(); + } + + public static boolean isValidBit(int bit) { + return bit >= 0 && bit <= 7; + } +} diff --git a/java_console/romraider/src/com/romraider/util/Platform.java b/java_console/romraider/src/com/romraider/util/Platform.java new file mode 100644 index 0000000000..97aaac65ad --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/Platform.java @@ -0,0 +1,31 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +public final class Platform { + public static final String LINUX = "Linux"; + public static final String MAC_OS_X = "Mac OS X"; + public static final String WINDOWS = "Windows"; + private static final String OS_NAME = "os.name"; + + public static boolean isPlatform(String platform) { + return System.getProperties().getProperty(OS_NAME).toLowerCase().contains(platform.toLowerCase()); + } +} diff --git a/java_console/romraider/src/com/romraider/util/RomServer.java b/java_console/romraider/src/com/romraider/util/RomServer.java new file mode 100644 index 0000000000..6d689eb1ba --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/RomServer.java @@ -0,0 +1,96 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import org.apache.log4j.Logger; +import static org.apache.log4j.Logger.getLogger; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +public final class RomServer { + private static final Logger LOGGER = getLogger(RomServer.class); + private static final String HOST = "localhost"; + private static final int PORT = 50001; + + public static boolean isRunning() { + try { + ServerSocket sock = new ServerSocket(PORT); + sock.close(); + return false; + } catch (Exception ex) { + return true; + } + } + + public static String waitForRom() throws IOException { + ServerSocket sock = new ServerSocket(PORT); + try { + return waitForRom(sock); + } finally { + sock.close(); + } + } + + public static void sendRomToOpenInstance(String rom) { + try { + Socket socket = new Socket(HOST, PORT); + OutputStream os = socket.getOutputStream(); + try { + write(os, rom); + } finally { + socket.close(); + } + } catch (Throwable e) { + LOGGER.error("Error occurred", e); + } + } + + private static void write(OutputStream os, String rom) { + PrintWriter pw = new PrintWriter(os, true); + try { + pw.println(rom); + } finally { + pw.close(); + } + } + + private static String waitForRom(ServerSocket sock) throws IOException { + Socket client = sock.accept(); + try { + return getRom(client); + } finally { + client.close(); + } + } + + private static String getRom(Socket client) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); + try { + return br.readLine(); + } finally { + br.close(); + } + } +} diff --git a/java_console/romraider/src/com/romraider/util/SaxParserFactory.java b/java_console/romraider/src/com/romraider/util/SaxParserFactory.java new file mode 100644 index 0000000000..843c7fb750 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/SaxParserFactory.java @@ -0,0 +1,57 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; + +public final class SaxParserFactory { + + private SaxParserFactory() { + throw new UnsupportedOperationException(); + } + + public static SAXParser getSaxParser() throws ParserConfigurationException, SAXException { + SAXParserFactory parserFactory = SAXParserFactory.newInstance(); + parserFactory.setNamespaceAware(false); + parserFactory.setValidating(true); + parserFactory.setXIncludeAware(false); + return parserFactory.newSAXParser(); + } + + public static void main(String args[]) { + try { + SAXParser parser = SaxParserFactory.getSaxParser(); + BufferedInputStream b = new BufferedInputStream(new FileInputStream(new File("/ecu_defs.xml"))); + System.out.println(b.available()); + parser.parse(b, new DefaultHandler()); + System.out.println(parser.isValidating()); + + } catch (Exception ex) { + System.err.println(ex); + } + } +} diff --git a/java_console/romraider/src/com/romraider/util/SettingsManager.java b/java_console/romraider/src/com/romraider/util/SettingsManager.java new file mode 100644 index 0000000000..9c98e166c2 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/SettingsManager.java @@ -0,0 +1,103 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import static com.romraider.Version.VERSION; +import static javax.swing.JOptionPane.INFORMATION_MESSAGE; +import static javax.swing.JOptionPane.showMessageDialog; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import com.romraider.Settings; +import com.romraider.swing.JProgressPane; +import com.romraider.xml.DOMSettingsBuilder; +import com.romraider.xml.DOMSettingsUnmarshaller; +import com.sun.org.apache.xerces.internal.parsers.DOMParser; + +public class SettingsManager { + private static final String SETTINGS_FILE = "/settings.xml"; + private static final String USER_HOME = + System.getProperty("user.home") + "/.RomRaider"; + private static final String START_DIR = System.getProperty("user.dir"); + private static String settingsDir = USER_HOME; + + private static Settings settings = null; + + public static Settings getSettings() { + if(null == settings) { + settings = load(); + } + return settings; + } + + private static Settings load() { + Settings loadedSettings; + try { + FileInputStream settingsFileIn = null; + try { + final File sf = new File(USER_HOME + SETTINGS_FILE); + settingsFileIn = new FileInputStream(sf); + } + catch (Exception e) { + final File sf = new File(START_DIR + SETTINGS_FILE); + settingsFileIn = new FileInputStream(sf); + settingsDir = START_DIR; + } + final InputSource src = new InputSource(settingsFileIn); + final DOMSettingsUnmarshaller domUms = new DOMSettingsUnmarshaller(); + final DOMParser parser = new DOMParser(); + parser.parse(src); + final Document doc = parser.getDocument(); + loadedSettings = domUms.unmarshallSettings(doc.getDocumentElement()); + } catch (FileNotFoundException e) { + showMessageDialog(null, + "Settings file not found.\nUsing default settings.", + "Error Loading Settings", INFORMATION_MESSAGE); + loadedSettings = new Settings(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return loadedSettings; + } + + public static void save(Settings newSettings) { + save(newSettings, new JProgressPane()); + } + + public static void save(Settings newSettings, JProgressPane progress) { + final DOMSettingsBuilder builder = new DOMSettingsBuilder(); + try { + final File newDir = new File(settingsDir); + newDir.mkdir(); // Creates directory if it does not exist + final File sf = new File(settingsDir + SETTINGS_FILE); + builder.buildSettings(newSettings, sf, progress, VERSION); + settings = newSettings; + } catch (Exception e) { + // Load the settings from disk. + settings = load(); + throw new RuntimeException(e); + } + } +} diff --git a/java_console/romraider/src/com/romraider/util/ThreadCheckingRepaintManager.java b/java_console/romraider/src/com/romraider/util/ThreadCheckingRepaintManager.java new file mode 100644 index 0000000000..67f111da37 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/ThreadCheckingRepaintManager.java @@ -0,0 +1,96 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import javax.swing.JComponent; +import javax.swing.RepaintManager; +import javax.swing.SwingUtilities; +import java.awt.Component; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +public class ThreadCheckingRepaintManager extends RepaintManager { + private int tabCount = 0; + private boolean checkIsShowing = false; + + public ThreadCheckingRepaintManager() { + } + + public ThreadCheckingRepaintManager(boolean checkIsShowing) { + this.checkIsShowing = checkIsShowing; + } + + public synchronized void addInvalidComponent(JComponent jComponent) { + checkThread(jComponent); + super.addInvalidComponent(jComponent); + } + + private void checkThread(JComponent c) { + if (!SwingUtilities.isEventDispatchThread() && checkIsShowing(c)) { + System.out.println("----------Wrong Thread START"); + System.out.println(getStracktraceAsString(new Exception())); + dumpComponentTree(c); + System.out.println("----------Wrong Thread END"); + } + } + + private String getStracktraceAsString(Exception e) { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(byteArrayOutputStream); + e.printStackTrace(printStream); + printStream.flush(); + return byteArrayOutputStream.toString(); + } + + private boolean checkIsShowing(JComponent c) { + return !this.checkIsShowing || c.isShowing(); + } + + public synchronized void addDirtyRegion(JComponent jComponent, int i, int i1, int i2, int i3) { + checkThread(jComponent); + super.addDirtyRegion(jComponent, i, i1, i2, i3); + } + + private void dumpComponentTree(Component c) { + System.out.println("----------Component Tree"); + resetTabCount(); + for (; c != null; c = c.getParent()) { + printTabIndent(); + System.out.println(c); + printTabIndent(); + System.out.println("Showing:" + c.isShowing() + " Visible: " + c.isVisible()); + incrementTabCount(); + } + } + + private void resetTabCount() { + this.tabCount = 0; + } + + private void incrementTabCount() { + this.tabCount++; + } + + private void printTabIndent() { + for (int i = 0; i < this.tabCount; i++) { + System.out.print("\t"); + } + } +} diff --git a/java_console/romraider/src/com/romraider/util/ThreadUtil.java b/java_console/romraider/src/com/romraider/util/ThreadUtil.java new file mode 100644 index 0000000000..dcc374a1fc --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/ThreadUtil.java @@ -0,0 +1,50 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util; + +import org.apache.log4j.Logger; +import java.util.concurrent.TimeUnit; + +public final class ThreadUtil { + private static final Logger LOGGER = Logger.getLogger(ThreadUtil.class); + + private ThreadUtil() { + throw new UnsupportedOperationException(); + } + + public static void sleep(long millis) { + try { + TimeUnit.MILLISECONDS.sleep(millis); + } catch (InterruptedException e) { + LOGGER.trace("Sleep interrupted", e); + } + } + + public static void run(Runnable runnable) { + new Thread(runnable).start(); + } + + public static void runAsDaemon(Runnable runnable) { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + thread.start(); + } + +} diff --git a/java_console/romraider/src/com/romraider/util/proxy/Proxifier.java b/java_console/romraider/src/com/romraider/util/proxy/Proxifier.java new file mode 100644 index 0000000000..d8b2bed70a --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/proxy/Proxifier.java @@ -0,0 +1,46 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util.proxy; + +import static java.lang.reflect.Proxy.newProxyInstance; +import java.lang.reflect.Constructor; + +public final class Proxifier { + public static T proxy(T t, Class cls) { + Wrapper wrapper = instantiate(cls, t); + return proxy(t, wrapper); + } + + private static T proxy(T t, Wrapper wrapper) { + Class cls = t.getClass(); + ClassLoader loader = cls.getClassLoader(); + Class[] interfaces = cls.getInterfaces(); + return (T) newProxyInstance(loader, interfaces, wrapper); + } + + private static Wrapper instantiate(Class wrapper, T t) { + try { + Constructor constructor = wrapper.getConstructor(Object.class); + return (Wrapper) constructor.newInstance(t); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/java_console/romraider/src/com/romraider/util/proxy/TimerWrapper.java b/java_console/romraider/src/com/romraider/util/proxy/TimerWrapper.java new file mode 100644 index 0000000000..01b8582696 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/proxy/TimerWrapper.java @@ -0,0 +1,52 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util.proxy; + +import static com.romraider.util.ParamChecker.checkNotNull; +import static java.lang.System.currentTimeMillis; +import org.apache.log4j.Logger; +import static org.apache.log4j.Logger.getLogger; +import java.lang.reflect.Method; + +public final class TimerWrapper implements Wrapper { + private static final Logger LOGGER = getLogger(TimerWrapper.class); + private final Object delegate; + + public TimerWrapper(Object delegate) { + checkNotNull(delegate); + this.delegate = delegate; + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + long start = currentTimeMillis(); + try { + return method.invoke(delegate, args); + } finally { + long time = currentTimeMillis() - start; + log(method, time); + } + } + + private void log(Method method, long time) { + String c = delegate.getClass().getSimpleName(); + String m = method.getName(); + LOGGER.error("[TIMER] - " + c + "." + m + ": " + time + "ms"); + } +} diff --git a/java_console/romraider/src/com/romraider/util/proxy/Wrapper.java b/java_console/romraider/src/com/romraider/util/proxy/Wrapper.java new file mode 100644 index 0000000000..3650c03dc2 --- /dev/null +++ b/java_console/romraider/src/com/romraider/util/proxy/Wrapper.java @@ -0,0 +1,25 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.util.proxy; + +import java.lang.reflect.InvocationHandler; + +public interface Wrapper extends InvocationHandler { +} diff --git a/java_console/romraider/src/com/romraider/xml/DOMHelper.java b/java_console/romraider/src/com/romraider/xml/DOMHelper.java new file mode 100644 index 0000000000..ad84a14242 --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/DOMHelper.java @@ -0,0 +1,65 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public final class DOMHelper { + + private DOMHelper() { + } + + public static String unmarshallText(Node textNode) { + StringBuffer buf = new StringBuffer(); + + Node n; + NodeList nodes = textNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == Node.TEXT_NODE) { + buf.append(n.getNodeValue()); + } else { + // expected a text-only node (skip) + } + } + return buf.toString(); + } + + public static String unmarshallAttribute(Node node, String name, String defaultValue) { + Node n = node.getAttributes().getNamedItem(name); + return (n != null) ? (n.getNodeValue()) : (defaultValue); + } + + public static Double unmarshallAttribute(Node node, String name, double defaultValue) { + return Double.parseDouble(unmarshallAttribute(node, name, String.valueOf(defaultValue))); + } + + public static int unmarshallAttribute(Node node, String name, int defaultValue) { + return Integer.parseInt(unmarshallAttribute(node, name, String.valueOf(defaultValue))); + } + + public static boolean unmarshallAttribute(Node node, String name, boolean defaultValue) { + return Boolean.parseBoolean(unmarshallAttribute(node, name, String.valueOf(defaultValue))); + } + +} diff --git a/java_console/romraider/src/com/romraider/xml/DOMRomUnmarshaller.java b/java_console/romraider/src/com/romraider/xml/DOMRomUnmarshaller.java new file mode 100644 index 0000000000..9b60b6454a --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/DOMRomUnmarshaller.java @@ -0,0 +1,617 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +//DOM XML parser for ROMs + +package com.romraider.xml; + +import static com.romraider.xml.DOMHelper.unmarshallAttribute; +import static com.romraider.xml.DOMHelper.unmarshallText; +import static org.w3c.dom.Node.ELEMENT_NODE; + +import java.util.ArrayList; +import java.util.List; + +import javax.management.modelmbean.XMLParseException; +import javax.swing.JOptionPane; + +import org.apache.log4j.Logger; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import com.romraider.Settings; +import com.romraider.editor.ecu.ECUEditorManager; +import com.romraider.maps.DataCell; +import com.romraider.maps.Rom; +import com.romraider.maps.RomID; +import com.romraider.maps.Scale; +import com.romraider.maps.Table; +import com.romraider.maps.Table1D; +import com.romraider.maps.Table2D; +import com.romraider.maps.Table3D; +import com.romraider.maps.TableSwitch; +import com.romraider.swing.DebugPanel; +import com.romraider.swing.JProgressPane; +import com.romraider.util.LogManager; +import com.romraider.util.ObjectCloner; +import com.romraider.util.SettingsManager; + +public final class DOMRomUnmarshaller { + private static final Logger LOGGER = Logger + .getLogger(DOMRomUnmarshaller.class); + private JProgressPane progress = null; + private final List scales = new ArrayList(); + + public DOMRomUnmarshaller() { + } + + public Rom unmarshallXMLDefinition(Node rootNode, byte[] input, + JProgressPane progress) throws RomNotFoundException, + XMLParseException, StackOverflowError, Exception { + + this.progress = progress; + Node n; + NodeList nodes = rootNode.getChildNodes(); + + // unmarshall scales first + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE + && n.getNodeName().equalsIgnoreCase("scalingbase")) { + scales.add(unmarshallScale(n, new Scale())); + } + } + + // now unmarshall roms + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE + && n.getNodeName().equalsIgnoreCase("rom")) { + Node n2; + NodeList nodes2 = n.getChildNodes(); + + for (int z = 0; z < nodes2.getLength(); z++) { + n2 = nodes2.item(z); + if (n2.getNodeType() == ELEMENT_NODE + && n2.getNodeName().equalsIgnoreCase("romid")) { + + RomID romID = unmarshallRomID(n2, new RomID()); + + if (romID.getInternalIdString().length() > 0 + && foundMatch(romID, input)) { + Rom output = unmarshallRom(n, new Rom()); + + // set ram offset + output.getRomID().setRamOffset( + output.getRomID().getFileSize() + - input.length); + return output; + } + } + } + } + } + throw new RomNotFoundException(); + } + + public static boolean foundMatch(RomID romID, byte[] file) { + + String idString = romID.getInternalIdString(); + + // romid is hex string + if (idString.length() > 2 + && idString.substring(0, 2).equalsIgnoreCase("0x")) { + + try { + // put romid in to byte array to check for match + idString = idString.substring(2); // remove "0x" + int[] romIDBytes = new int[idString.length() / 2]; + + for (int i = 0; i < romIDBytes.length; i++) { + // check to see if each byte matches + + if ((file[romID.getInternalIdAddress() + i] & 0xff) != Integer + .parseInt(idString.substring(i * 2, i * 2 + 2), 16)) { + + return false; + } + } + // if no mismatched bytes found, return true + return true; + } catch (Exception ex) { + // if any exception is encountered, names do not match + LOGGER.warn("Error finding match", ex); + return false; + } + + // else romid is NOT hex string + } else { + try { + String ecuID = new String(file, romID.getInternalIdAddress(), + romID.getInternalIdString().length()); + return foundMatchByString(romID, ecuID); + } catch (Exception ex) { + // if any exception is encountered, names do not match + return false; + } + } + } + + public static boolean foundMatchByString(RomID romID, String ecuID) { + + try { + if (ecuID.equalsIgnoreCase(romID.getInternalIdString())) { + return true; + } else { + return false; + } + } catch (Exception ex) { + // if any exception is encountered, names do not match + return false; + } + } + + public static void main(String args[]) { + LogManager.initDebugLogging(); + RomID romID = new RomID(); + romID.setInternalIdString("Asdfd"); + + byte[] file = "Asdfd".getBytes(); + LOGGER.debug(foundMatch(romID, file)); + + file[0] = 1; + file[1] = 1; + file[2] = 1; + file[3] = 1; + LOGGER.debug(foundMatch(romID, file)); + + romID.setInternalIdString("0x010101"); + LOGGER.debug(foundMatch(romID, file)); + } + + public Rom unmarshallRom(Node rootNode, Rom rom) throws XMLParseException, + RomNotFoundException, StackOverflowError, Exception { + Node n; + NodeList nodes = rootNode.getChildNodes(); + + progress.update("Creating tables...", 15); + + if (!unmarshallAttribute(rootNode, "base", "none").equalsIgnoreCase( + "none")) { + rom = getBaseRom(rootNode.getParentNode(), + unmarshallAttribute(rootNode, "base", "none"), rom); + rom.getRomID().setObsolete(false); + } + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + // update progress + int currProgress = (int) ((double) i / (double) nodes.getLength() * 40); + progress.update("Creating tables...", 10 + currProgress); + + if (n.getNodeType() == ELEMENT_NODE) { + if (n.getNodeName().equalsIgnoreCase("romid")) { + rom.setRomID(unmarshallRomID(n, rom.getRomID())); + + } else if (n.getNodeName().equalsIgnoreCase("table")) { + Table table = null; + try { + table = rom.getTableByName(unmarshallAttribute(n, "name", + null)); + } catch (TableNotFoundException e) { + /* + * table does not + * already exist (do + * nothing) + */ + } catch (InvalidTableNameException iex) { + // Table name is null or empty. Do nothing. + } + + try { + table = unmarshallTable(n, table, rom); + //rom.addTableByName(table); + rom.addTable(table); + } catch (TableIsOmittedException ex) { + // table is not supported in inherited def (skip) + if (table != null) { + //rom.removeTableByName(table); + rom.removeTable(table); + } + } catch (XMLParseException ex) { + LOGGER.error("Error unmarshalling rom", ex); + } + + } else { /* unexpected element in Rom (skip) */ + } + } else { /* unexpected node-type in Rom (skip) */ + } + } + return rom; + } + + public Rom getBaseRom(Node rootNode, String xmlID, Rom rom) + throws XMLParseException, RomNotFoundException, StackOverflowError, + Exception { + Node n; + NodeList nodes = rootNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE + && n.getNodeName().equalsIgnoreCase("rom")) { + Node n2; + NodeList nodes2 = n.getChildNodes(); + + for (int z = 0; z < nodes2.getLength(); z++) { + n2 = nodes2.item(z); + if (n2.getNodeType() == ELEMENT_NODE + && n2.getNodeName().equalsIgnoreCase("romid")) { + + RomID romID = unmarshallRomID(n2, new RomID()); + if (romID.getXmlid().equalsIgnoreCase(xmlID)) { + Rom returnrom = unmarshallRom(n, rom); + returnrom.getRomID().setObsolete(false); + return returnrom; + } + } + } + } + } + throw new RomNotFoundException(); + } + + public RomID unmarshallRomID(Node romIDNode, RomID romID) { + Node n; + NodeList nodes = romIDNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE) { + + if (n.getNodeName().equalsIgnoreCase("xmlid")) { + romID.setXmlid(unmarshallText(n)); + + } else if (n.getNodeName() + .equalsIgnoreCase("internalidaddress")) { + romID.setInternalIdAddress(RomAttributeParser + .parseHexString(unmarshallText(n))); + + } else if (n.getNodeName().equalsIgnoreCase("internalidstring")) { + romID.setInternalIdString(unmarshallText(n)); + if (romID.getInternalIdString() == null) { + romID.setInternalIdString(""); + } + + } else if (n.getNodeName().equalsIgnoreCase("caseid")) { + romID.setCaseId(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("ecuid")) { + romID.setEcuId(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("make")) { + romID.setMake(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("market")) { + romID.setMarket(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("model")) { + romID.setModel(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("submodel")) { + romID.setSubModel(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("transmission")) { + romID.setTransmission(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("year")) { + romID.setYear(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("flashmethod")) { + romID.setFlashMethod(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("memmodel")) { + romID.setMemModel(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("filesize")) { + romID.setFileSize(RomAttributeParser + .parseFileSize(unmarshallText(n))); + + } else if (n.getNodeName().equalsIgnoreCase("obsolete")) { + romID.setObsolete(Boolean.parseBoolean(unmarshallText(n))); + + } else { /* unexpected element in RomID (skip) */ + } + } else { /* unexpected node-type in RomID (skip) */ + } + } + return romID; + } + + private Table unmarshallTable(Node tableNode, Table table, Rom rom) + throws XMLParseException, TableIsOmittedException, Exception { + + if (unmarshallAttribute(tableNode, "omit", "false").equalsIgnoreCase( + "true")) { // remove table if omitted + throw new TableIsOmittedException(); + } + + if (!unmarshallAttribute(tableNode, "base", "none").equalsIgnoreCase( + "none")) { // copy base table for inheritance + try { + table = (Table) ObjectCloner + .deepCopy(rom.getTableByName(unmarshallAttribute(tableNode, + "base", "none"))); + + } catch (TableNotFoundException ex) { /* table not found, do nothing */ + + } catch (InvalidTableNameException ex) { // Table name is invalid, do nothing. + + } catch (NullPointerException ex) { + JOptionPane.showMessageDialog(ECUEditorManager.getECUEditor(), + new DebugPanel(ex, SettingsManager.getSettings().getSupportURL()), "Exception", + JOptionPane.ERROR_MESSAGE); + + } + } + + try { + if (table.getType() < 1) { + } + } catch (NullPointerException ex) { // if type is null or less than 0, + // create new instance (otherwise it + // is inherited) + if (unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("3D")) { + table = new Table3D(); + + } else if (unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("2D")) { + table = new Table2D(); + + } else if (unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("1D")) { + table = new Table1D(); + + } else if (unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("X Axis") + || unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("Y Axis")) { + table = new Table1D(); + + } else if (unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("Static Y Axis") + || unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("Static X Axis")) { + table = new Table1D(); + + } else if (unmarshallAttribute(tableNode, "type", "unknown") + .equalsIgnoreCase("Switch")) { + table = new TableSwitch(); + + } else { + throw new XMLParseException("Error loading table, " + + tableNode.getAttributes().getNamedItem("name")); + } + } + + // unmarshall table attributes + table.setName(unmarshallAttribute(tableNode, "name", table.getName())); + table.setType(RomAttributeParser.parseTableType(unmarshallAttribute( + tableNode, "type", String.valueOf(table.getType())))); + if (unmarshallAttribute(tableNode, "beforeram", "false") + .equalsIgnoreCase("true")) { + table.setBeforeRam(true); + } + + table.setCategory(unmarshallAttribute(tableNode, "category", + table.getCategory())); + if (table.getStorageType() < 1) { + table.setSignedData(RomAttributeParser + .parseStorageDataSign(unmarshallAttribute(tableNode, + "storagetype", + String.valueOf(table.getStorageType())))); + } + table.setStorageType(RomAttributeParser + .parseStorageType(unmarshallAttribute(tableNode, "storagetype", + String.valueOf(table.getStorageType())))); + table.setEndian(RomAttributeParser.parseEndian(unmarshallAttribute( + tableNode, "endian", String.valueOf(table.getEndian())))); + table.setStorageAddress(RomAttributeParser + .parseHexString(unmarshallAttribute(tableNode, + "storageaddress", + String.valueOf(table.getStorageAddress())))); + table.setDescription(unmarshallAttribute(tableNode, "description", + table.getDescription())); + table.setDataSize(unmarshallAttribute(tableNode, "sizey", + unmarshallAttribute(tableNode, "sizex", table.getDataSize()))); + table.setFlip(unmarshallAttribute(tableNode, "flipy", + unmarshallAttribute(tableNode, "flipx", table.getFlip()))); + table.setUserLevel(unmarshallAttribute(tableNode, "userlevel", + table.getUserLevel())); + table.setLocked(unmarshallAttribute(tableNode, "locked", + table.isLocked())); + table.setLogParam(unmarshallAttribute(tableNode, "logparam", + table.getLogParam())); + + if (table.getType() == Settings.TABLE_3D) { + ((Table3D) table).setSwapXY(unmarshallAttribute(tableNode, + "swapxy", ((Table3D) table).getSwapXY())); + ((Table3D) table).setFlipX(unmarshallAttribute(tableNode, "flipx", + ((Table3D) table).getFlipX())); + ((Table3D) table).setFlipY(unmarshallAttribute(tableNode, "flipy", + ((Table3D) table).getFlipY())); + ((Table3D) table).setSizeX(unmarshallAttribute(tableNode, "sizex", + ((Table3D) table).getSizeX())); + ((Table3D) table).setSizeY(unmarshallAttribute(tableNode, "sizey", + ((Table3D) table).getSizeY())); + } + + Node n; + NodeList nodes = tableNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE) { + if (n.getNodeName().equalsIgnoreCase("table")) { + + if (table.getType() == Settings.TABLE_2D) { // if table is 2D, + // parse axis + + if (RomAttributeParser + .parseTableType(unmarshallAttribute(n, "type", + "unknown")) == Settings.TABLE_Y_AXIS + || RomAttributeParser + .parseTableType(unmarshallAttribute(n, + "type", "unknown")) == Settings.TABLE_X_AXIS) { + + Table1D tempTable = (Table1D) unmarshallTable(n, + ((Table2D) table).getAxis(), rom); + if (tempTable.getDataSize() != table.getDataSize()) { + tempTable.setDataSize(table.getDataSize()); + } + tempTable.setData(((Table2D) table).getAxis() + .getData()); + ((Table2D) table).setAxis(tempTable); + + } + } else if (table.getType() == Settings.TABLE_3D) { // if table + // is 3D, + // populate + // xAxis + if (RomAttributeParser + .parseTableType(unmarshallAttribute(n, "type", + "unknown")) == Settings.TABLE_X_AXIS) { + + Table1D tempTable = (Table1D) unmarshallTable(n, + ((Table3D) table).getXAxis(), rom); + if (tempTable.getDataSize() != ((Table3D) table) + .getSizeX()) { + tempTable.setDataSize(((Table3D) table) + .getSizeX()); + } + tempTable.setData(((Table3D) table).getXAxis() + .getData()); + ((Table3D) table).setXAxis(tempTable); + + } else if (RomAttributeParser + .parseTableType(unmarshallAttribute(n, "type", + "unknown")) == Settings.TABLE_Y_AXIS) { + + Table1D tempTable = (Table1D) unmarshallTable(n, + ((Table3D) table).getYAxis(), rom); + if (tempTable.getDataSize() != ((Table3D) table) + .getSizeY()) { + tempTable.setDataSize(((Table3D) table) + .getSizeY()); + } + tempTable.setData(((Table3D) table).getYAxis() + .getData()); + ((Table3D) table).setYAxis(tempTable); + + } + } + + } else if (n.getNodeName().equalsIgnoreCase("scaling")) { + // check whether scale already exists. if so, modify, else + // use new instance + Scale baseScale = table.getScale(unmarshallAttribute(n,"name", "Default")); + table.addScale(unmarshallScale(n, baseScale)); + + } else if (n.getNodeName().equalsIgnoreCase("data")) { + // parse and add data to table + DataCell dataCell = new DataCell(table, unmarshallText(n)); + if(table instanceof Table1D) { + ((Table1D)table).addStaticDataCell(dataCell); + } else { + // Why would this happen. Static should only be for axis. + LOGGER.error("Error adding static data cell."); + } + + } else if (n.getNodeName().equalsIgnoreCase("description")) { + table.setDescription(unmarshallText(n)); + + } else if (n.getNodeName().equalsIgnoreCase("state")) { + ((TableSwitch) table).setValues( + unmarshallAttribute(n, "name", ""), + unmarshallAttribute(n, "data", "0.0")); + + } else { /* unexpected element in Table (skip) */ + } + } else { /* unexpected node-type in Table (skip) */ + } + } + + return table; + } + + private Scale unmarshallScale(Node scaleNode, Scale scale) { + + // look for base scale first + String base = unmarshallAttribute(scaleNode, "base", "none"); + if (!base.equalsIgnoreCase("none")) { + for (Scale scaleItem : scales) { + + // check whether name matches base and set scale if so + if (scaleItem.getName().equalsIgnoreCase(base)) { + try { + scale = (Scale) ObjectCloner.deepCopy(scaleItem); + + } catch (Exception ex) { + JOptionPane.showMessageDialog( + ECUEditorManager.getECUEditor(), + new DebugPanel(ex, SettingsManager.getSettings() + .getSupportURL()), "Exception", + JOptionPane.ERROR_MESSAGE); + } + } + } + } + + // set remaining attributes + scale.setName(unmarshallAttribute(scaleNode, "name", "Default")); + scale.setUnit(unmarshallAttribute(scaleNode, "units", scale.getUnit())); + scale.setExpression(unmarshallAttribute(scaleNode, "expression", + scale.getExpression())); + scale.setByteExpression(unmarshallAttribute(scaleNode, "to_byte", + scale.getByteExpression())); + scale.setFormat(unmarshallAttribute(scaleNode, "format", "#")); + scale.setMax(unmarshallAttribute(scaleNode, "max", 0.0)); + scale.setMin(unmarshallAttribute(scaleNode, "min", 0.0)); + + // get coarse increment with new attribute name (coarseincrement), else + // look for old (increment) + scale.setCoarseIncrement(unmarshallAttribute( + scaleNode, + "coarseincrement", + unmarshallAttribute(scaleNode, "increment", + scale.getCoarseIncrement()))); + + scale.setFineIncrement(unmarshallAttribute(scaleNode, "fineincrement", + scale.getFineIncrement())); + + return scale; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/xml/DOMSettingsBuilder.java b/java_console/romraider/src/com/romraider/xml/DOMSettingsBuilder.java new file mode 100644 index 0000000000..46cb8d85aa --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/DOMSettingsBuilder.java @@ -0,0 +1,430 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2013 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Vector; + +import javax.imageio.metadata.IIOMetadataNode; + +import com.romraider.Settings; +//import com.romraider.logger.external.phidget.interfacekit.io.IntfKitSensor; +import com.romraider.swing.JProgressPane; +import com.sun.org.apache.xml.internal.serialize.OutputFormat; +import com.sun.org.apache.xml.internal.serialize.XMLSerializer; + +public final class DOMSettingsBuilder { + + public void buildSettings(Settings settings, File output, JProgressPane progress, String versionNumber) throws IOException { + + IIOMetadataNode settingsNode = new IIOMetadataNode("settings"); + + // create settings + progress.update("Saving window settings...", 15); + settingsNode.appendChild(buildWindow(settings)); + progress.update("Saving file settings...", 30); + settingsNode.appendChild(buildFiles(settings)); + progress.update("Saving options...", 45); + settingsNode.appendChild(buildOptions(settings, versionNumber)); + progress.update("Saving display settings...", 60); + settingsNode.appendChild(buildTableDisplay(settings)); + progress.update("Saving logger settings...", 75); + settingsNode.appendChild(buildLogger(settings)); + progress.update("Saving table clipboard format settings...", 80); + settingsNode.appendChild(buildTableClipboardFormat(settings)); + progress.update("Saving icon scale settings...", 85); + settingsNode.appendChild(buildIcons(settings)); + + OutputFormat of = new OutputFormat("XML", "ISO-8859-1", true); + of.setIndent(1); + of.setIndenting(true); + + progress.update("Writing to file...", 90); + + FileOutputStream fos = new FileOutputStream(output); + try { + XMLSerializer serializer = new XMLSerializer(fos, of); + serializer.serialize(settingsNode); + fos.flush(); + } finally { + fos.close(); + } + } + + private IIOMetadataNode buildWindow(Settings settings) { + IIOMetadataNode windowSettings = new IIOMetadataNode("window"); + + // window maximized + IIOMetadataNode maximized = new IIOMetadataNode("maximized"); + maximized.setAttribute("value", String.valueOf((settings.isWindowMaximized()))); + windowSettings.appendChild(maximized); + + // window size + IIOMetadataNode size = new IIOMetadataNode("size"); + size.setAttribute("x", String.valueOf(((int) settings.getWindowSize().getHeight()))); + size.setAttribute("y", String.valueOf(((int) settings.getWindowSize().getWidth()))); + windowSettings.appendChild(size); + + // window location + IIOMetadataNode location = new IIOMetadataNode("location"); + location.setAttribute("x", String.valueOf(((int) settings.getWindowLocation().getX()))); + location.setAttribute("y", String.valueOf(((int) settings.getWindowLocation().getY()))); + windowSettings.appendChild(location); + + // splitpane location + IIOMetadataNode splitpane = new IIOMetadataNode("splitpane"); + splitpane.setAttribute("location", String.valueOf(settings.getSplitPaneLocation())); + windowSettings.appendChild(splitpane); + + return windowSettings; + } + + private IIOMetadataNode buildFiles(Settings settings) { + IIOMetadataNode files = new IIOMetadataNode("files"); + + // image directory + IIOMetadataNode imageDir = new IIOMetadataNode("image_dir"); + imageDir.setAttribute("path", settings.getLastImageDir().getAbsolutePath()); + files.appendChild(imageDir); + + // repository directory + IIOMetadataNode repositoryDir = new IIOMetadataNode(Settings.REPOSITORY_ELEMENT_NAME); + repositoryDir.setAttribute(Settings.REPOSITORY_ATTRIBUTE_NAME, settings.getLastRepositoryDir().getAbsolutePath()); + files.appendChild(repositoryDir); + + // ecu definition files + Vector defFiles = settings.getEcuDefinitionFiles(); + + for (File defFile : defFiles) { + IIOMetadataNode ecuDef = new IIOMetadataNode("ecudefinitionfile"); + ecuDef.setAttribute("name", defFile.getAbsolutePath()); + files.appendChild(ecuDef); + } + + return files; + } + + private IIOMetadataNode buildOptions(Settings settings, String versionNumber) { + IIOMetadataNode options = new IIOMetadataNode("options"); + + // obsolete warning + IIOMetadataNode obsoleteWarning = new IIOMetadataNode("obsoletewarning"); + obsoleteWarning.setAttribute("value", String.valueOf(settings.isObsoleteWarning())); + options.appendChild(obsoleteWarning); + + // calcultion conflicting warning + IIOMetadataNode calcConflictWarning = new IIOMetadataNode("calcconflictwarning"); + calcConflictWarning.setAttribute("value", String.valueOf(settings.isCalcConflictWarning())); + options.appendChild(calcConflictWarning); + + // debug mode + IIOMetadataNode debug = new IIOMetadataNode("debug"); + debug.setAttribute("value", String.valueOf(settings.isDebug())); + options.appendChild(debug); + + // userlevel + IIOMetadataNode userLevel = new IIOMetadataNode("userlevel"); + userLevel.setAttribute("value", String.valueOf(settings.getUserLevel())); + options.appendChild(userLevel); + + // table click count + IIOMetadataNode tableClickCount = new IIOMetadataNode("tableclickcount"); + tableClickCount.setAttribute("value", String.valueOf(settings.getTableClickCount())); + options.appendChild(tableClickCount); + + // table click behavior + IIOMetadataNode tableClickBehavior = new IIOMetadataNode("tableclickbehavior"); + tableClickBehavior.setAttribute("value", String.valueOf(settings.getTableClickBehavior())); + options.appendChild(tableClickBehavior); + + // last version used + IIOMetadataNode version = new IIOMetadataNode("version"); + version.setAttribute("value", versionNumber); + options.appendChild(version); + + // save debug level tables + IIOMetadataNode saveDebugTables = new IIOMetadataNode("savedebugtables"); + saveDebugTables.setAttribute("value", String.valueOf(settings.isSaveDebugTables())); + options.appendChild(saveDebugTables); + + // display tables higher than userlevel + IIOMetadataNode displayHighTables = new IIOMetadataNode("displayhightables"); + displayHighTables.setAttribute("value", String.valueOf(settings.isDisplayHighTables())); + options.appendChild(displayHighTables); + + // warning when exceeding limits + IIOMetadataNode valueLimitWarning = new IIOMetadataNode("valuelimitwarning"); + valueLimitWarning.setAttribute("value", String.valueOf(settings.isValueLimitWarning())); + options.appendChild(valueLimitWarning); + + // color axis + IIOMetadataNode colorAxis = new IIOMetadataNode("coloraxis"); + colorAxis.setAttribute("value", String.valueOf(settings.isColorAxis())); + options.appendChild(colorAxis); + + // show table toolbar border + IIOMetadataNode showTableToolbarBorder = new IIOMetadataNode("showtabletoolbarborder"); + showTableToolbarBorder.setAttribute("value", String.valueOf(settings.isShowTableToolbarBorder())); + options.appendChild(showTableToolbarBorder); + + // open top level rom node expanded + IIOMetadataNode openRomExpanded = new IIOMetadataNode("openromexpanded"); + openRomExpanded.setAttribute("value", String.valueOf(settings.isOpenExpanded())); + options.appendChild(openRomExpanded); + + // always open at 0 + IIOMetadataNode alwaysOpenTableAtZero = new IIOMetadataNode("alwaysopentableatzero"); + alwaysOpenTableAtZero.setAttribute("value", String.valueOf(settings.isAlwaysOpenTableAtZero())); + options.appendChild(alwaysOpenTableAtZero); + + // defaultScale + IIOMetadataNode defaultScale = new IIOMetadataNode("defaultscale"); + defaultScale.setAttribute("value", String.valueOf(settings.getDefaultScale())); + options.appendChild(defaultScale); + + // scale headers with data + IIOMetadataNode scaleHeaderAndData = new IIOMetadataNode("scaleHeadersAndData"); + scaleHeaderAndData.setAttribute("value", String.valueOf(settings.isScaleHeadersAndData())); + options.appendChild(scaleHeaderAndData); + + return options; + } + + private IIOMetadataNode buildTableDisplay(Settings settings) { + IIOMetadataNode tableDisplay = new IIOMetadataNode("tabledisplay"); + + // font + IIOMetadataNode font = new IIOMetadataNode("font"); + font.setAttribute("face", settings.getTableFont().getName()); + font.setAttribute("size", String.valueOf(settings.getTableFont().getSize())); + font.setAttribute("decoration", String.valueOf(settings.getTableFont().getStyle())); + tableDisplay.appendChild(font); + + // table cell size + IIOMetadataNode cellSize = new IIOMetadataNode("cellsize"); + cellSize.setAttribute("height", String.valueOf((int) settings.getCellSize().getHeight())); + cellSize.setAttribute("width", String.valueOf(((int) settings.getCellSize().getWidth()))); + tableDisplay.appendChild(cellSize); + + // colors + IIOMetadataNode colors = new IIOMetadataNode("colors"); + // max + IIOMetadataNode max = new IIOMetadataNode("max"); + max.setAttribute("r", String.valueOf(settings.getMaxColor().getRed())); + max.setAttribute("g", String.valueOf(settings.getMaxColor().getGreen())); + max.setAttribute("b", String.valueOf(settings.getMaxColor().getBlue())); + colors.appendChild(max); + // min + IIOMetadataNode min = new IIOMetadataNode("min"); + min.setAttribute("r", String.valueOf(settings.getMinColor().getRed())); + min.setAttribute("g", String.valueOf(settings.getMinColor().getGreen())); + min.setAttribute("b", String.valueOf(settings.getMinColor().getBlue())); + colors.appendChild(min); + // highlight + IIOMetadataNode highlight = new IIOMetadataNode("highlight"); + highlight.setAttribute("r", String.valueOf(settings.getHighlightColor().getRed())); + highlight.setAttribute("g", String.valueOf(settings.getHighlightColor().getGreen())); + highlight.setAttribute("b", String.valueOf(settings.getHighlightColor().getBlue())); + colors.appendChild(highlight); + // select + IIOMetadataNode select = new IIOMetadataNode("select"); + select.setAttribute("r", String.valueOf(settings.getSelectColor().getRed())); + select.setAttribute("g", String.valueOf(settings.getSelectColor().getGreen())); + select.setAttribute("b", String.valueOf(settings.getSelectColor().getBlue())); + colors.appendChild(select); + // increased cell border + IIOMetadataNode increaseBorder = new IIOMetadataNode("increaseborder"); + increaseBorder.setAttribute("r", String.valueOf(settings.getIncreaseBorder().getRed())); + increaseBorder.setAttribute("g", String.valueOf(settings.getIncreaseBorder().getGreen())); + increaseBorder.setAttribute("b", String.valueOf(settings.getIncreaseBorder().getBlue())); + colors.appendChild(increaseBorder); + // decreased cell border + IIOMetadataNode decreaseBorder = new IIOMetadataNode("decreaseborder"); + decreaseBorder.setAttribute("r", String.valueOf(settings.getDecreaseBorder().getRed())); + decreaseBorder.setAttribute("g", String.valueOf(settings.getDecreaseBorder().getGreen())); + decreaseBorder.setAttribute("b", String.valueOf(settings.getDecreaseBorder().getBlue())); + colors.appendChild(decreaseBorder); + // axis cells + IIOMetadataNode axis = new IIOMetadataNode("axis"); + axis.setAttribute("r", String.valueOf(settings.getAxisColor().getRed())); + axis.setAttribute("g", String.valueOf(settings.getAxisColor().getGreen())); + axis.setAttribute("b", String.valueOf(settings.getAxisColor().getBlue())); + colors.appendChild(axis); + // warning cells + IIOMetadataNode warning = new IIOMetadataNode("warning"); + warning.setAttribute("r", String.valueOf(settings.getWarningColor().getRed())); + warning.setAttribute("g", String.valueOf(settings.getWarningColor().getGreen())); + warning.setAttribute("b", String.valueOf(settings.getWarningColor().getBlue())); + colors.appendChild(warning); + + tableDisplay.appendChild(colors); + + return tableDisplay; + } + + private IIOMetadataNode buildLogger(Settings settings) { + IIOMetadataNode loggerSettings = new IIOMetadataNode("logger"); + loggerSettings.setAttribute("locale", settings.getLocale()); + + // serial connection + IIOMetadataNode serial = new IIOMetadataNode("serial"); + serial.setAttribute("port", settings.getLoggerPortDefault()); + serial.setAttribute("refresh", String.valueOf(settings.getRefreshMode())); + serial.setAttribute("ecuid", String.valueOf(settings.getDestinationId())); + serial.setAttribute("fastpoll", String.valueOf(settings.isFastPoll())); + loggerSettings.appendChild(serial); + + // Protocol connection + IIOMetadataNode protocol = new IIOMetadataNode("protocol"); + protocol.setAttribute("name", settings.getLoggerProtocol()); + protocol.setAttribute("transport", settings.getTransportProtocol()); + protocol.setAttribute("library", settings.getJ2534Device()); + loggerSettings.appendChild(protocol); + + // window maximized + IIOMetadataNode maximized = new IIOMetadataNode("maximized"); + maximized.setAttribute("value", String.valueOf((settings.isLoggerWindowMaximized()))); + loggerSettings.appendChild(maximized); + + // window size + IIOMetadataNode size = new IIOMetadataNode("size"); + size.setAttribute("x", String.valueOf(((int) settings.getLoggerWindowSize().getHeight()))); + size.setAttribute("y", String.valueOf(((int) settings.getLoggerWindowSize().getWidth()))); + size.setAttribute("divider", String.valueOf(((int) settings.getDividerLocation()))); + loggerSettings.appendChild(size); + + // window location + IIOMetadataNode location = new IIOMetadataNode("location"); + location.setAttribute("x", String.valueOf(((int) settings.getLoggerWindowLocation().getX()))); + location.setAttribute("y", String.valueOf(((int) settings.getLoggerWindowLocation().getY()))); + loggerSettings.appendChild(location); + + // last tab index + IIOMetadataNode tabs = new IIOMetadataNode("tabs"); + tabs.setAttribute("selected", String.valueOf(settings.getLoggerSelectedTabIndex())); + tabs.setAttribute("showlist", String.valueOf(settings.getLoggerParameterListState())); + loggerSettings.appendChild(tabs); + + // definition path + IIOMetadataNode definition = new IIOMetadataNode("definition"); + definition.setAttribute("path", settings.getLoggerDefinitionFilePath()); + loggerSettings.appendChild(definition); + + // profile path + IIOMetadataNode profile = new IIOMetadataNode("profile"); + profile.setAttribute("path", settings.getLoggerProfileFilePath()); + loggerSettings.appendChild(profile); + + // file logging + IIOMetadataNode filelogging = new IIOMetadataNode("filelogging"); + filelogging.setAttribute("path", settings.getLoggerOutputDirPath()); + filelogging.setAttribute("switchid", settings.getFileLoggingControllerSwitchId()); + filelogging.setAttribute("active", String.valueOf(settings.isFileLoggingControllerSwitchActive())); + filelogging.setAttribute("absolutetimestamp", String.valueOf(settings.isFileLoggingAbsoluteTimestamp())); + loggerSettings.appendChild(filelogging); + + // debug level + IIOMetadataNode debug = new IIOMetadataNode("debug"); + debug.setAttribute("level", settings.getLoggerDebuggingLevel()); + loggerSettings.appendChild(debug); + + // plugin ports + Map pluginPorts = settings.getLoggerPluginPorts(); + if (pluginPorts != null && !pluginPorts.isEmpty()) { + IIOMetadataNode plugins = new IIOMetadataNode("plugins"); + for (Map.Entry entry : pluginPorts.entrySet()) { + IIOMetadataNode plugin = new IIOMetadataNode("plugin"); + plugin.setAttribute("id", entry.getKey()); + plugin.setAttribute("port", entry.getValue()); + plugins.appendChild(plugin); + } +// final Map phidgets = settings.getPhidgetSensors(); +// if (phidgets != null && !phidgets.isEmpty()) { +// final Collection sensors = phidgets.values(); +// IIOMetadataNode phidgetsNode = new IIOMetadataNode("phidgets"); +// for (IntfKitSensor entry : sensors) { +// IIOMetadataNode phidgetNode = new IIOMetadataNode("phidget"); +// phidgetNode.setAttribute("name", entry.getInputName()); +// phidgetNode.setAttribute("number", String.valueOf(entry.getInputNumber())); +// phidgetNode.setAttribute("units", entry.getUnits()); +// phidgetNode.setAttribute("expression", entry.getExpression()); +// phidgetNode.setAttribute("format", entry.getFormat()); +// phidgetNode.setAttribute("min", String.valueOf(entry.getMinValue())); +// phidgetNode.setAttribute("max", String.valueOf(entry.getMaxValue())); +// phidgetNode.setAttribute("step", String.valueOf(entry.getStepValue())); +// phidgetsNode.appendChild(phidgetNode); +// } +// plugins.appendChild(phidgetsNode); +// } +// loggerSettings.appendChild(plugins); + } + + return loggerSettings; + } + + private IIOMetadataNode buildTableClipboardFormat(Settings settings) { + // Head Node + IIOMetadataNode tableClipboardFormatSetting = new IIOMetadataNode(Settings.TABLE_CLIPBOARD_FORMAT_ELEMENT); + tableClipboardFormatSetting.setAttribute(Settings.TABLE_CLIPBOARD_FORMAT_ATTRIBUTE, settings.getTableClipboardFormat()); + + // Table Child + IIOMetadataNode tableFormatSetting = new IIOMetadataNode(Settings.TABLE_ELEMENT); + // Table1D Child + IIOMetadataNode table1DFormatSetting = new IIOMetadataNode(Settings.TABLE1D_ELEMENT); + // Table2D Child + IIOMetadataNode table2DFormatSetting = new IIOMetadataNode(Settings.TABLE2D_ELEMENT); + // Table3D Child + IIOMetadataNode table3DFormatSetting = new IIOMetadataNode(Settings.TABLE3D_ELEMENT); + + tableFormatSetting.setAttribute(Settings.TABLE_HEADER_ATTRIBUTE, settings.getTableHeader()); + table1DFormatSetting.setAttribute(Settings.TABLE_HEADER_ATTRIBUTE, settings.getTable1DHeader()); + table2DFormatSetting.setAttribute(Settings.TABLE_HEADER_ATTRIBUTE, settings.getTable2DHeader()); + table3DFormatSetting.setAttribute(Settings.TABLE_HEADER_ATTRIBUTE, settings.getTable3DHeader()); + + tableClipboardFormatSetting.appendChild(tableFormatSetting); + tableClipboardFormatSetting.appendChild(table1DFormatSetting); + tableClipboardFormatSetting.appendChild(table2DFormatSetting); + tableClipboardFormatSetting.appendChild(table3DFormatSetting); + + return tableClipboardFormatSetting; + } + + private IIOMetadataNode buildIcons(Settings settings) { + // Head Node + IIOMetadataNode iconsSettings = new IIOMetadataNode(Settings.ICONS_ELEMENT_NAME); + + // Editor Icons Child + IIOMetadataNode editorIconsScaleSettings = new IIOMetadataNode(Settings.EDITOR_ICONS_ELEMENT_NAME); + editorIconsScaleSettings.setAttribute(Settings.EDITOR_ICONS_SCALE_ATTRIBUTE_NAME, String.valueOf(settings.getEditorIconScale())); + + // Table Icons Child + IIOMetadataNode tableIconsScaleSettings = new IIOMetadataNode(Settings.TABLE_ICONS_ELEMENT_NAME); + tableIconsScaleSettings.setAttribute(Settings.TABLE_ICONS_SCALE_ATTRIBUTE_NAME, String.valueOf(settings.getTableIconScale())); + + iconsSettings.appendChild(editorIconsScaleSettings); + iconsSettings.appendChild(tableIconsScaleSettings); + + return iconsSettings; + } +} diff --git a/java_console/romraider/src/com/romraider/xml/DOMSettingsUnmarshaller.java b/java_console/romraider/src/com/romraider/xml/DOMSettingsUnmarshaller.java new file mode 100644 index 0000000000..6a01918cbb --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/DOMSettingsUnmarshaller.java @@ -0,0 +1,402 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +import static com.romraider.xml.DOMHelper.unmarshallAttribute; +import static java.awt.Font.BOLD; +import static org.w3c.dom.Node.ELEMENT_NODE; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Point; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import com.romraider.Settings; + +public final class DOMSettingsUnmarshaller { + + public Settings unmarshallSettings(Node rootNode) { + Settings settings = new Settings(); + Node n; + NodeList nodes = rootNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("window")) { + settings = unmarshallWindow(n, settings); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("files")) { + settings = unmarshallFiles(n, settings); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("options")) { + settings = unmarshallOptions(n, settings); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("tabledisplay")) { + settings = unmarshallTableDisplay(n, settings); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("logger")) { + settings = unmarshallLogger(n, settings); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase(Settings.TABLE_CLIPBOARD_FORMAT_ELEMENT)) { + settings = this.unmarshallClipboardFormat(n, settings); + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase(Settings.ICONS_ELEMENT_NAME)) { + settings = this.unmarshallIcons(n, settings); + } + } + return settings; + } + + + private Settings unmarshallWindow(Node windowNode, Settings settings) { + Node n; + NodeList nodes = windowNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("maximized")) { + settings.setWindowMaximized(unmarshallAttribute(n, "value", false)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("size")) { + settings.setWindowSize(new Dimension(unmarshallAttribute(n, "y", 600), + unmarshallAttribute(n, "x", 800))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("location")) { + // set default location in top left screen if no settings file found + settings.setWindowLocation(new Point(unmarshallAttribute(n, "x", 0), + unmarshallAttribute(n, "y", 0))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("splitpane")) { + settings.setSplitPaneLocation(unmarshallAttribute(n, "location", 150)); + + } + } + return settings; + } + + private Settings unmarshallFiles(Node urlNode, Settings settings) { + Node n; + NodeList nodes = urlNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("ecudefinitionfile")) { + settings.addEcuDefinitionFile(new File(unmarshallAttribute(n, "name", "ecu_defs.xml"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("image_dir")) { + settings.setLastImageDir(new File(unmarshallAttribute(n, "path", "ecu_defs.xml"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase(Settings.REPOSITORY_ELEMENT_NAME)) { + settings.setLastRepositoryDir(new File(unmarshallAttribute(n, Settings.REPOSITORY_ATTRIBUTE_NAME, "repositories"))); + + } + } + return settings; + } + + private Settings unmarshallOptions(Node optionNode, Settings settings) { + Node n; + NodeList nodes = optionNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("obsoletewarning")) { + settings.setObsoleteWarning(Boolean.parseBoolean(unmarshallAttribute(n, "value", "true"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("debug")) { + settings.setDebug(Boolean.parseBoolean(unmarshallAttribute(n, "value", "true"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("calcconflictwarning")) { + settings.setCalcConflictWarning(Boolean.parseBoolean(unmarshallAttribute(n, "value", "true"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("userlevel")) { + settings.setUserLevel(unmarshallAttribute(n, "value", 1)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("tableclickcount")) { + settings.setTableClickCount(unmarshallAttribute(n, "value", 2)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("tableclickbehavior")) { + settings.setTableClickBehavior(unmarshallAttribute(n, "value", 0)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("version")) { + settings.setRecentVersion(unmarshallAttribute(n, "value", "")); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("savedebugtables")) { + settings.setSaveDebugTables(Boolean.parseBoolean(unmarshallAttribute(n, "value", "false"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("displayhightables")) { + settings.setDisplayHighTables(Boolean.parseBoolean(unmarshallAttribute(n, "value", "false"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("valuelimitwarning")) { + settings.setValueLimitWarning(Boolean.parseBoolean(unmarshallAttribute(n, "value", "true"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("coloraxis")) { + settings.setColorAxis(Boolean.parseBoolean(unmarshallAttribute(n, "value", "false"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("showtabletoolbarborder")) { + settings.setShowTableToolbarBorder(Boolean.parseBoolean(unmarshallAttribute(n, "value", "false"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("openromexpanded")) { + settings.setOpenExpanded(Boolean.parseBoolean(unmarshallAttribute(n, "value", "true"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("alwaysopentableatzero")) { + settings.setAlwaysOpenTableAtZero(Boolean.parseBoolean(unmarshallAttribute(n, "value", "false"))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("defaultscale")) { + settings.setDefaultScale(unmarshallAttribute(n, "value", "Metric")); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("scaleHeadersAndData")) { + settings.setScaleHeadersAndData(Boolean.parseBoolean(unmarshallAttribute(n, "value", "true"))); + + } + } + return settings; + } + + private Settings unmarshallTableDisplay(Node tableDisplayNode, Settings settings) { + Node n; + NodeList nodes = tableDisplayNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("font")) { + settings.setTableFont(new Font(unmarshallAttribute(n, "face", "Arial"), + unmarshallAttribute(n, "decoration", BOLD), + unmarshallAttribute(n, "size", 12))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("cellsize")) { + settings.setCellSize(new Dimension(unmarshallAttribute(n, "width", 42), + unmarshallAttribute(n, "height", 18))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("colors")) { + settings = unmarshallColors(n, settings); + + } + } + return settings; + } + + private Settings unmarshallColors(Node colorNode, Settings settings) { + Node n; + NodeList nodes = colorNode.getChildNodes(); + + for (int i = 0; i < nodes.getLength(); i++) { + n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("max")) { + settings.setMaxColor(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("min")) { + settings.setMinColor(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("highlight")) { + settings.setHighlightColor(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("select")) { + settings.setSelectColor(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("increaseborder")) { + settings.setIncreaseBorder(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("decreaseborder")) { + settings.setDecreaseBorder(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("axis")) { + settings.setAxisColor(unmarshallColor(n)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("warning")) { + settings.setWarningColor(unmarshallColor(n)); + + } + } + return settings; + } + + + private Settings unmarshallLogger(Node loggerNode, Settings settings) { + NodeList nodes = loggerNode.getChildNodes(); + if (loggerNode.getNodeType() == ELEMENT_NODE && loggerNode.getNodeName().equalsIgnoreCase("logger")) { + settings.setLocale(unmarshallAttribute(loggerNode, "locale", "system")); + } + + for (int i = 0; i < nodes.getLength(); i++) { + Node n = nodes.item(i); + + if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("serial")) { + settings.setLoggerPortDefault(unmarshallAttribute(n, "port", "")); + settings.setRefreshMode(unmarshallAttribute(n, "refresh", false)); + settings.setDestinationId((byte) unmarshallAttribute(n, "ecuid", (byte) 0x10)); + settings.setFastPoll(unmarshallAttribute(n, "fastpoll", true)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("protocol")) { + settings.setLoggerProtocol(unmarshallAttribute(n, "name", "SSM")); + settings.setTransportProtocol(unmarshallAttribute(n, "transport", "ISO9141")); + settings.setJ2534Device(unmarshallAttribute(n, "library", null)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("maximized")) { + settings.setLoggerWindowMaximized(unmarshallAttribute(n, "value", false)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("size")) { + settings.setLoggerWindowSize(new Dimension(unmarshallAttribute(n, "y", 600), + unmarshallAttribute(n, "x", 1000))); + settings.setLoggerDividerLocation(unmarshallAttribute(n, "divider", 500)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("location")) { + settings.setLoggerWindowLocation(new Point(unmarshallAttribute(n, "x", 150), + unmarshallAttribute(n, "y", 150))); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("tabs")) { + settings.setLoggerSelectedTabIndex(unmarshallAttribute(n, "selected", 0)); + settings.setLoggerParameterListState(unmarshallAttribute(n, "showlist", true)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("definition")) { + settings.setLoggerDefinitionFilePath(unmarshallAttribute(n, "path", settings.getLoggerDefinitionFilePath())); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("profile")) { + settings.setLoggerProfileFilePath(unmarshallAttribute(n, "path", "")); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("filelogging")) { + settings.setLoggerOutputDirPath(unmarshallAttribute(n, "path", "")); + settings.setFileLoggingControllerSwitchId(unmarshallAttribute(n, "switchid", settings.getFileLoggingControllerSwitchId())); + settings.setFileLoggingControllerSwitchActive(unmarshallAttribute(n, "active", true)); + settings.setFileLoggingAbsoluteTimestamp(unmarshallAttribute(n, "absolutetimestamp", false)); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("debug")) { + settings.setLoggerDebuggingLevel(unmarshallAttribute(n, "level", "info")); + + } else if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("plugins")) { + Map pluginPorts = new HashMap(); + NodeList pluginNodes = n.getChildNodes(); + for (int j = 0; j < pluginNodes.getLength(); j++) { + Node pluginNode = pluginNodes.item(j); + if (pluginNode.getNodeType() == ELEMENT_NODE && pluginNode.getNodeName().equalsIgnoreCase("plugin")) { + String id = unmarshallAttribute(pluginNode, "id", null); + if (id == null || id.trim().length() == 0) continue; + String port = unmarshallAttribute(pluginNode, "port", null); + if (port == null || port.trim().length() == 0) continue; + pluginPorts.put(id.trim(), port.trim()); + } + else if (pluginNode.getNodeType() == ELEMENT_NODE && pluginNode.getNodeName().equalsIgnoreCase("phidgets")) { +// final Map phidgets = new HashMap(); +// NodeList sensorNodes = pluginNode.getChildNodes(); +// for (int k = 0; k < sensorNodes.getLength(); k++) { +// Node sensorNode = sensorNodes.item(k); +// if (sensorNode.getNodeType() == ELEMENT_NODE && sensorNode.getNodeName().equalsIgnoreCase("phidget")) { +// final String name = unmarshallAttribute(sensorNode, "name", null); +// final int number = unmarshallAttribute(sensorNode, "number", -1); +// final String units = unmarshallAttribute(sensorNode, "units", null); +// final String expression = unmarshallAttribute(sensorNode, "expression", null); +// final String format = unmarshallAttribute(sensorNode, "format", null); +// final float min = Float.parseFloat(unmarshallAttribute(sensorNode, "min", "-1.0")); +// final float max = Float.parseFloat(unmarshallAttribute(sensorNode, "max", "-1.0")); +// final float step = Float.parseFloat(unmarshallAttribute(sensorNode, "step", "-1.0")); +// if (name != null && number != -1) { +// final String inputName = name.replaceAll("Phidget IK Sensor ", ""); +// final IntfKitSensor sensor = new IntfKitSensor(); +// sensor.setInputNumber(number); +// sensor.setInputName(name); +// sensor.setUnits(units); +// sensor.setExpression(expression); +// sensor.setFormat(format); +// sensor.setMinValue(min); +// sensor.setMaxValue(max); +// sensor.setStepValue(step); +// phidgets.put(inputName, sensor); +// } +// } +// } +// settings.setPhidgetSensors(phidgets); + } + } + settings.setLoggerPluginPorts(pluginPorts); + } + } + return settings; + } + + private Color unmarshallColor(Node colorNode) { + return new Color(unmarshallAttribute(colorNode, "r", 155), + unmarshallAttribute(colorNode, "g", 155), + unmarshallAttribute(colorNode, "b", 155)); + } + + private Settings unmarshallClipboardFormat(Node formatNode, Settings settings) { + String tableClipboardFormat = unmarshallAttribute(formatNode, Settings.TABLE_CLIPBOARD_FORMAT_ATTRIBUTE, Settings.DEFAULT_CLIPBOARD_FORMAT); + if(tableClipboardFormat.equalsIgnoreCase(Settings.CUSTOM_CLIPBOARD_FORMAT)) { + settings.setTableClipboardFormat(Settings.CUSTOM_CLIPBOARD_FORMAT); + } else if (tableClipboardFormat.equalsIgnoreCase(Settings.AIRBOYS_CLIPBOARD_FORMAT)) { + settings.setAirboysFormat(); + return settings; + } else { + settings.setDefaultFormat(); + return settings; + } + + NodeList tableFormats = formatNode.getChildNodes(); + for( int i = 0; i < tableFormats.getLength(); i++) { + Node tableNode = tableFormats.item(i); + if(tableNode.getNodeType() == ELEMENT_NODE) { + if(tableNode.getNodeName().equalsIgnoreCase(Settings.TABLE_ELEMENT)) { + settings.setTableHeader(unmarshallAttribute(tableNode, Settings.TABLE_HEADER_ATTRIBUTE, Settings.DEFAULT_TABLE_HEADER)); + } else if(tableNode.getNodeName().equalsIgnoreCase(Settings.TABLE1D_ELEMENT)) { + settings.setTable1DHeader(unmarshallAttribute(tableNode, Settings.TABLE_HEADER_ATTRIBUTE, Settings.DEFAULT_TABLE1D_HEADER)); + } else if(tableNode.getNodeName().equalsIgnoreCase(Settings.TABLE2D_ELEMENT)) { + settings.setTable2DHeader(unmarshallAttribute(tableNode, Settings.TABLE_HEADER_ATTRIBUTE, Settings.DEFAULT_TABLE2D_HEADER)); + } else if(tableNode.getNodeName().equalsIgnoreCase(Settings.TABLE3D_ELEMENT)) { + settings.setTable3DHeader(unmarshallAttribute(tableNode, Settings.TABLE_HEADER_ATTRIBUTE, Settings.DEFAULT_TABLE3D_HEADER)); + } + } + } + return settings; + } + + private Settings unmarshallIcons(Node iconsNode, Settings settings) { + NodeList iconScales = iconsNode.getChildNodes(); + for(int i = 0; i < iconScales.getLength(); i++) { + Node scaleNode = iconScales.item(i); + if(scaleNode.getNodeType() == ELEMENT_NODE) { + if(scaleNode.getNodeName().equalsIgnoreCase(Settings.EDITOR_ICONS_ELEMENT_NAME)) { + try{ + settings.setEditorIconScale(unmarshallAttribute(scaleNode, Settings.EDITOR_ICONS_SCALE_ATTRIBUTE_NAME, Settings.DEFAULT_EDITOR_ICON_SCALE)); + } catch(NumberFormatException ex) { + settings.setEditorIconScale(Settings.DEFAULT_EDITOR_ICON_SCALE); + } + } else if(scaleNode.getNodeName().equalsIgnoreCase(Settings.TABLE_ICONS_ELEMENT_NAME)) { + try{ + settings.setTableIconScale(unmarshallAttribute(scaleNode, Settings.TABLE_ICONS_SCALE_ATTRIBUTE_NAME, Settings.DEFAULT_TABLE_ICON_SCALE)); + } catch(NumberFormatException ex) { + settings.setTableIconScale(Settings.DEFAULT_TABLE_ICON_SCALE); + } + } + } + } + return settings; + } +} diff --git a/java_console/romraider/src/com/romraider/xml/InvalidTableNameException.java b/java_console/romraider/src/com/romraider/xml/InvalidTableNameException.java new file mode 100644 index 0000000000..7ba33c51be --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/InvalidTableNameException.java @@ -0,0 +1,30 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +public final class InvalidTableNameException extends Exception { + + private static final long serialVersionUID = 5189492974906792046L; + + @Override + public String getMessage() { + return "Invalid table name."; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/xml/RomAttributeParser.java b/java_console/romraider/src/com/romraider/xml/RomAttributeParser.java new file mode 100644 index 0000000000..b914ebd60a --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/RomAttributeParser.java @@ -0,0 +1,202 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +// Parses attributes from ROM XML + +package com.romraider.xml; + +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import com.romraider.Settings; + +public final class RomAttributeParser { + + private RomAttributeParser() { + } + + public static int parseEndian(String input) { + if (input.equalsIgnoreCase("big") || input.equalsIgnoreCase(String.valueOf(Settings.ENDIAN_BIG))) { + return Settings.ENDIAN_BIG; + } + else if (input.equalsIgnoreCase("little") || input.equalsIgnoreCase(String.valueOf(Settings.ENDIAN_LITTLE))) { + return Settings.ENDIAN_LITTLE; + } + else { + return Settings.ENDIAN_LITTLE; + } + } + + public static int parseHexString(String input) { + if (input.equals("0")) { + return 0; + } + else if (input.length() > 2 && input.substring(0, 2).equalsIgnoreCase("0x")) { + return Integer.parseInt(input.substring(2), 16); + } + else { + return Integer.parseInt(input, 16); + } + } + + public static int parseStorageType(String input) { + if (input.equalsIgnoreCase("float")) { + return Settings.STORAGE_TYPE_FLOAT; + } + else if (input.startsWith("uint")) { + return Integer.parseInt(input.substring(4)) / 8; + } + else if (input.startsWith("int")) { + return Integer.parseInt(input.substring(3)) / 8; + } + else { + return Integer.parseInt(input); + } + } + + public static boolean parseStorageDataSign(String input) { + if (input.startsWith("int")) { + return true; + } + else { + return false; + } + } + + public static int parseScaleType(String input) { + if (input.equalsIgnoreCase("inverse")) { + return Settings.INVERSE; + } + else { + return Settings.LINEAR; + } + } + + public static int parseTableType(String input) { + if (input.equalsIgnoreCase("3D") || input.equalsIgnoreCase(String.valueOf(Settings.TABLE_3D))) { + return Settings.TABLE_3D; + } + else if (input.equalsIgnoreCase("2D") || input.equalsIgnoreCase(String.valueOf(Settings.TABLE_2D))) { + return Settings.TABLE_2D; + } + else if (input.equalsIgnoreCase("X Axis") || input.equalsIgnoreCase("Static X Axis") || input.equalsIgnoreCase(String.valueOf(Settings.TABLE_X_AXIS))) { + return Settings.TABLE_X_AXIS; + } + else if (input.equalsIgnoreCase("Y Axis") || input.equalsIgnoreCase("Static Y Axis") || input.equalsIgnoreCase(String.valueOf(Settings.TABLE_Y_AXIS))) { + return Settings.TABLE_Y_AXIS; + } + else { + return Settings.TABLE_1D; + } + } + + public static long parseByteValue(byte[] input, int endian, int address, int length, boolean signed) throws ArrayIndexOutOfBoundsException, IndexOutOfBoundsException { + try { + long output = 0L; + ByteBuffer bb = ByteBuffer.wrap(input, address, length); + if (endian == Settings.ENDIAN_LITTLE) { + bb.order(ByteOrder.LITTLE_ENDIAN); + } + switch (length) { + case 1: + output = bb.get(); + break; + case 2: + output = bb.getShort(); + break; + case 4: + output = bb.getInt(); + break; + } + if (!signed) { + switch (length) { + case 1: + output = output & 0xff; + break; + case 2: + output = output & 0xffff; + break; + case 4: + output = output & 0xffffffffL; + break; + } + } + return output; + } catch (IndexOutOfBoundsException ex) { + throw new IndexOutOfBoundsException(); + } + } + + public static byte[] parseIntegerValue(int input, int endian, int length) { + try { + ByteBuffer bb = ByteBuffer.allocate(length); + if (endian == Settings.ENDIAN_LITTLE) { + bb.order(ByteOrder.LITTLE_ENDIAN); + } + switch (length) { + case 1: + bb.put((byte) input); + break; + case 2: + bb.putShort((short) input); + break; + case 4: + bb.putInt(input); + break; + } + return bb.array(); + } + catch (BufferOverflowException ex) { + throw new BufferOverflowException(); + } + } + + public static int parseFileSize(String input) throws NumberFormatException { + try { + return Integer.parseInt(input); + } catch (NumberFormatException ex) { + if (input.substring(input.length() - 2).equalsIgnoreCase("kb")) { + return Integer.parseInt(input.substring(0, input.length() - 2)) * 1024; + } + else if (input.substring(input.length() - 2).equalsIgnoreCase("mb")) { + return Integer.parseInt(input.substring(0, input.length() - 2)) * 1024 * 1024; + } + throw new NumberFormatException(); + } + } + + public static byte[] floatToByte(float input, int endian) { + byte[] output = new byte[4]; + ByteBuffer bb = ByteBuffer.wrap(output, 0, 4); + if (endian == Settings.ENDIAN_LITTLE) { + bb.order(ByteOrder.BIG_ENDIAN); + } + bb.putFloat(input); + return bb.array(); + } + + public static float byteToFloat(byte[] input, int endian) { + ByteBuffer bb = ByteBuffer.wrap(input, 0, 4); + if (endian == Settings.ENDIAN_LITTLE) { + bb.order(ByteOrder.BIG_ENDIAN); + } + return bb.getFloat(); + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/xml/RomNotFoundException.java b/java_console/romraider/src/com/romraider/xml/RomNotFoundException.java new file mode 100644 index 0000000000..e595821b94 --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/RomNotFoundException.java @@ -0,0 +1,28 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +public final class RomNotFoundException extends Exception { + + private static final long serialVersionUID = -5434546006966986885L; + + public RomNotFoundException() { + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/xml/TableIsOmittedException.java b/java_console/romraider/src/com/romraider/xml/TableIsOmittedException.java new file mode 100644 index 0000000000..7b0e6c29d8 --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/TableIsOmittedException.java @@ -0,0 +1,32 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +public final class TableIsOmittedException extends Exception { + + private static final long serialVersionUID = -2128531751395058602L; + + public TableIsOmittedException() { + } + + public String getMessage() { + return "Table omitted."; + } +} \ No newline at end of file diff --git a/java_console/romraider/src/com/romraider/xml/TableNotFoundException.java b/java_console/romraider/src/com/romraider/xml/TableNotFoundException.java new file mode 100644 index 0000000000..c1c6c32a28 --- /dev/null +++ b/java_console/romraider/src/com/romraider/xml/TableNotFoundException.java @@ -0,0 +1,29 @@ +/* + * RomRaider Open-Source Tuning, Logging and Reflashing + * Copyright (C) 2006-2012 RomRaider.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +package com.romraider.xml; + +public final class TableNotFoundException extends Exception { + + private static final long serialVersionUID = -7492075561444288417L; + + public String getMessage() { + return "Table not found."; + } +} \ No newline at end of file