Search in sources :

Example 1 with XmlAdapter

use of jmri.configurexml.XmlAdapter in project JMRI by JMRI.

the class SwitchboardEditorXml method load.

/**
     * Create a SwitchboardEditor object, then register and fill it, then pop it in a
     * JFrame
     *
     * @param shared Top level Element to unpack.
     * @return true if successful
     */
@Override
public boolean load(Element shared, Element perNode) {
    boolean result = true;
    // find coordinates
    int x = 0;
    int y = 0;
    int height = 400;
    int width = 300;
    int rangemin = 1;
    int rangemax = 32;
    int columns = 4;
    String type = "T";
    String connection = "I";
    String shape = "key";
    String name;
    try {
        x = shared.getAttribute("x").getIntValue();
        y = shared.getAttribute("y").getIntValue();
        height = shared.getAttribute("height").getIntValue();
        width = shared.getAttribute("width").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
        log.error("failed to convert Switchboard's attribute");
        result = false;
    }
    // find the name
    // this will be replaced by the name as stored NOI18N
    name = "Switchboard";
    if (shared.getAttribute("name") != null) {
        name = shared.getAttribute("name").getValue();
    }
    // confirm that panel hasn't already been loaded
    if (jmri.jmrit.display.PanelMenu.instance().isPanelNameUsed(name)) {
        log.warn("File contains a panel with the same name (" + name + ") as an existing panel");
        result = false;
    }
    SwitchboardEditor panel = new SwitchboardEditor(name);
    //panel.makeFrame(name);
    jmri.jmrit.display.PanelMenu.instance().addEditorPanel(panel);
    panel.getTargetFrame().setLocation(x, y);
    panel.getTargetFrame().setSize(width, height);
    panel.setTitle();
    // Load editor option flags. This has to be done before the content
    // items are loaded, to preserve the individual item settings.
    Attribute a;
    boolean value = true;
    if ((a = shared.getAttribute("editable")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllEditable(value);
    value = true;
    if ((a = shared.getAttribute("showtooltips")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllShowTooltip(value);
    value = true;
    if ((a = shared.getAttribute("controlling")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllControlling(value);
    value = false;
    if ((a = shared.getAttribute("hide")) != null && a.getValue().equals("yes")) {
        value = true;
    }
    panel.setShowHidden(value);
    value = true;
    if ((a = shared.getAttribute("panelmenu")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setPanelMenuVisible(value);
    String state = "both";
    if ((a = shared.getAttribute("scrollable")) != null) {
        state = a.getValue();
    }
    panel.setScroll(state);
    value = false;
    if ((a = shared.getAttribute("hideunconnected")) != null && a.getValue().equals("yes")) {
        value = true;
    }
    panel.setHideUnconnected(value);
    try {
        rangemin = shared.getAttribute("rangemin").getIntValue();
        rangemax = shared.getAttribute("rangemax").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
        log.error("failed to convert Switchboard's range");
        result = false;
    }
    panel.setPanelMenuRangeMin(rangemin);
    panel.setPanelMenuRangeMax(rangemax);
    type = shared.getAttribute("type").getValue();
    panel.setSwitchType(type);
    connection = shared.getAttribute("connection").getValue();
    panel.setSwitchManu(connection);
    shape = shared.getAttribute("shape").getValue();
    panel.setSwitchShape(shape);
    try {
        columns = shared.getAttribute("columns").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
        log.error("failed to convert Switchboard's column count");
        result = false;
    }
    panel.setColumns(columns);
    String defaultTextColor = "black";
    if (shared.getAttribute("defaulttextcolor") != null) {
        defaultTextColor = shared.getAttribute("defaulttextcolor").getValue();
    }
    panel.setDefaultTextColor(defaultTextColor);
    // set color if needed
    try {
        int red = shared.getAttribute("redBackground").getIntValue();
        int blue = shared.getAttribute("blueBackground").getIntValue();
        int green = shared.getAttribute("greenBackground").getIntValue();
        //panel.setBackground(new Color(red, green, blue));
        panel.setDefaultBackgroundColor(new Color(red, green, blue));
    } catch (org.jdom2.DataConversionException e) {
        log.warn("Could not parse color attributes!");
    } catch (NullPointerException e) {
    // considered normal if the attributes are not present
    }
    //set the (global) editor display widgets to their flag settings
    panel.initView();
    // load the contents with their individual option settings
    List<Element> items = shared.getChildren();
    for (int i = 0; i < items.size(); i++) {
        // get the class, hence the adapter object to do loading
        Element item = items.get(i);
        String adapterName = item.getAttribute("class").getValue();
        log.debug("load via " + adapterName);
        try {
            XmlAdapter adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
            // and do it
            adapter.load(item, panel);
            if (!panel.loadOK()) {
                result = false;
            }
        } catch (Exception e) {
            log.error("Exception while loading " + item.getName() + ":" + e);
            result = false;
            e.printStackTrace();
        }
    }
    // dispose of url correction data
    panel.disposeLoadData();
    // display the results, with the editor in back
    panel.pack();
    panel.setAllEditable(panel.isEditable());
    // we don't pack the target frame here, because size was specified
    // TODO: Work out why, when calling this method, panel size is increased
    // vertically (at least on MS Windows)
    // always show the panel
    panel.getTargetFrame().setVisible(true);
    // register the resulting panel for later configuration
    ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
    if (cm != null) {
        cm.registerUser(panel);
    }
    // reset the size and position, in case the display caused it to change
    panel.getTargetFrame().setLocation(x, y);
    panel.getTargetFrame().setSize(width, height);
    panel.updatePressed();
    return result;
}
Also used : Attribute(org.jdom2.Attribute) Color(java.awt.Color) Element(org.jdom2.Element) Point(java.awt.Point) SwitchboardEditor(jmri.jmrit.display.switchboardEditor.SwitchboardEditor) ConfigureManager(jmri.ConfigureManager) AbstractXmlAdapter(jmri.configurexml.AbstractXmlAdapter) XmlAdapter(jmri.configurexml.XmlAdapter)

Example 2 with XmlAdapter

use of jmri.configurexml.XmlAdapter in project JMRI by JMRI.

the class ConnectionConfigManager method initialize.

@Override
public void initialize(Profile profile) throws InitializationException {
    if (!isInitialized(profile)) {
        log.debug("Initializing...");
        Element sharedConnections = null;
        Element perNodeConnections = null;
        try {
            sharedConnections = JDOMUtil.toJDOMElement(ProfileUtils.getAuxiliaryConfiguration(profile).getConfigurationFragment(CONNECTIONS, NAMESPACE, true));
        } catch (NullPointerException ex) {
            // Normal if this is a new profile
            log.info("No connections configured.");
            log.debug("Null pointer thrown reading shared configuration.", ex);
        }
        if (sharedConnections != null) {
            try {
                perNodeConnections = JDOMUtil.toJDOMElement(ProfileUtils.getAuxiliaryConfiguration(profile).getConfigurationFragment(CONNECTIONS, NAMESPACE, false));
            } catch (NullPointerException ex) {
                // Normal if the profile has not been used on this computer
                log.info("No local configuration found.");
                log.debug("Null pointer thrown reading local configuration.", ex);
            // TODO: notify user
            }
            for (Element shared : sharedConnections.getChildren(CONNECTION)) {
                Element perNode = shared;
                String className = shared.getAttributeValue(CLASS);
                // NOI18N
                String userName = shared.getAttributeValue(USER_NAME, "");
                // NOI18N
                String systemName = shared.getAttributeValue(SYSTEM_NAME, "");
                // NOI18N
                String manufacturer = shared.getAttributeValue(MANUFACTURER, "");
                log.debug("Read shared connection {}:{} ({}) class {}", userName, systemName, manufacturer, className);
                if (perNodeConnections != null) {
                    for (Element e : perNodeConnections.getChildren(CONNECTION)) {
                        if (systemName.equals(e.getAttributeValue(SYSTEM_NAME))) {
                            perNode = e;
                            className = perNode.getAttributeValue(CLASS);
                            // NOI18N
                            userName = perNode.getAttributeValue(USER_NAME, "");
                            // NOI18N
                            manufacturer = perNode.getAttributeValue(MANUFACTURER, "");
                            log.debug("Read perNode connection {}:{} ({}) class {}", userName, systemName, manufacturer, className);
                        }
                    }
                }
                try {
                    log.debug("Creating connection {}:{} ({}) class {}", userName, systemName, manufacturer, className);
                    XmlAdapter adapter = (XmlAdapter) Class.forName(className).newInstance();
                    ConnectionConfigManagerErrorHandler handler = new ConnectionConfigManagerErrorHandler();
                    adapter.setExceptionHandler(handler);
                    if (!adapter.load(shared, perNode)) {
                        log.error("Unable to create {} for {}, load returned false", className, shared);
                        // NOI18N
                        String english = Bundle.getMessage(Locale.ENGLISH, "ErrorSingleConnection", userName, systemName);
                        // NOI18N
                        String localized = Bundle.getMessage("ErrorSingleConnection", userName, systemName);
                        this.addInitializationException(profile, new InitializationException(english, localized));
                    }
                    handler.exceptions.forEach((exception) -> {
                        this.addInitializationException(profile, exception);
                    });
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
                    log.error("Unable to create {} for {}", className, shared, ex);
                    // NOI18N
                    String english = Bundle.getMessage(Locale.ENGLISH, "ErrorSingleConnection", userName, systemName);
                    // NOI18N
                    String localized = Bundle.getMessage("ErrorSingleConnection", userName, systemName);
                    this.addInitializationException(profile, new InitializationException(english, localized, ex));
                } catch (Exception ex) {
                    log.error("Unable to load {} into {}", shared, className, ex);
                    // NOI18N
                    String english = Bundle.getMessage(Locale.ENGLISH, "ErrorSingleConnection", userName, systemName);
                    // NOI18N
                    String localized = Bundle.getMessage("ErrorSingleConnection", userName, systemName);
                    this.addInitializationException(profile, new InitializationException(english, localized, ex));
                }
            }
        }
        setInitialized(profile, true);
        List<Exception> exceptions = this.getInitializationExceptions(profile);
        if (exceptions.size() == 1) {
            if (exceptions.get(0) instanceof InitializationException) {
                throw (InitializationException) exceptions.get(0);
            } else {
                throw new InitializationException(exceptions.get(0));
            }
        } else if (exceptions.size() > 1) {
            // NOI18N
            String english = Bundle.getMessage(Locale.ENGLISH, "ErrorMultipleConnections");
            // NOI18N
            String localized = Bundle.getMessage("ErrorMultipleConnections");
            throw new InitializationException(english, localized);
        }
        log.debug("Initialized...");
    }
}
Also used : Element(org.jdom2.Element) InitializationException(jmri.util.prefs.InitializationException) XmlAdapter(jmri.configurexml.XmlAdapter) InitializationException(jmri.util.prefs.InitializationException) JDOMException(org.jdom2.JDOMException)

Example 3 with XmlAdapter

use of jmri.configurexml.XmlAdapter in project JMRI by JMRI.

the class ControlPanelEditorXml method load.

/**
     * Create a ControlPanelEditor object, then register and fill it, then pop
     * it in a JFrame
     *
     * @param shared Top level Element to unpack.
     * @return true if successful
     */
@Override
public boolean load(Element shared, Element perNode) {
    boolean result = true;
    // find coordinates
    int x = 0;
    int y = 0;
    int height = 400;
    int width = 300;
    try {
        x = shared.getAttribute("x").getIntValue();
        y = shared.getAttribute("y").getIntValue();
        height = shared.getAttribute("height").getIntValue();
        width = shared.getAttribute("width").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
        log.error("failed to convert ControlPanelEditor's attribute");
        result = false;
    }
    // find the name
    String name = "Control Panel";
    if (shared.getAttribute("name") != null) {
        name = shared.getAttribute("name").getValue();
    }
    // confirm that panel hasn't already been loaded
    if (jmri.jmrit.display.PanelMenu.instance().isPanelNameUsed(name)) {
        log.warn("File contains a panel with the same name ({}) as an existing panel", name);
        result = false;
    }
    ControlPanelEditor panel = new ControlPanelEditor(name);
    // save painting until last
    panel.getTargetFrame().setVisible(false);
    jmri.jmrit.display.PanelMenu.instance().addEditorPanel(panel);
    // Load editor option flags. This has to be done before the content 
    // items are loaded, to preserve the individual item settings
    Attribute a;
    boolean value = true;
    if ((a = shared.getAttribute("editable")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllEditable(value);
    value = true;
    if ((a = shared.getAttribute("positionable")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllPositionable(value);
    /*
         value = false;
         if ((a = element.getAttribute("showcoordinates"))!=null && a.getValue().equals("yes"))
         value = true;
         panel.setShowCoordinates(value);
         */
    value = true;
    if ((a = shared.getAttribute("showtooltips")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllShowTooltip(value);
    value = true;
    if ((a = shared.getAttribute("controlling")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllControlling(value);
    value = false;
    if ((a = shared.getAttribute("hide")) != null && a.getValue().equals("yes")) {
        value = true;
    }
    panel.setShowHidden(value);
    value = true;
    if ((a = shared.getAttribute("panelmenu")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setPanelMenuVisible(value);
    value = true;
    if ((a = shared.getAttribute("shapeSelect")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setShapeSelect(value);
    if ((a = shared.getAttribute("state")) != null) {
        try {
            int xState = a.getIntValue();
            panel.setExtendedState(xState);
        } catch (org.jdom2.DataConversionException e) {
            log.error("failed to convert ControlPanelEditor's extended State");
            result = false;
        }
    }
    String state = "both";
    if ((a = shared.getAttribute("scrollable")) != null) {
        state = a.getValue();
    }
    panel.setScroll(state);
    try {
        int red = shared.getAttribute("redBackground").getIntValue();
        int blue = shared.getAttribute("blueBackground").getIntValue();
        int green = shared.getAttribute("greenBackground").getIntValue();
        panel.setBackgroundColor(new Color(red, green, blue));
    } catch (org.jdom2.DataConversionException e) {
        log.warn("Could not parse color attributes!");
    } catch (NullPointerException e) {
    // considered normal if the attributes are not present
    }
    Element icons = shared.getChild("icons");
    /*        if (icons != null) {
            HashMap<String, NamedIcon> portalIconMap = new HashMap<String, NamedIcon>();
            portalIconMap.put(PortalIcon.VISIBLE, loadIcon("visible", icons, panel));
            portalIconMap.put(PortalIcon.PATH, loadIcon("path_edit", icons, panel));
            portalIconMap.put(PortalIcon.HIDDEN, loadIcon("hidden", icons, panel));
            portalIconMap.put(PortalIcon.TO_ARROW, loadIcon("to_arrow", icons, panel));
            portalIconMap.put(PortalIcon.FROM_ARROW, loadIcon("from_arrow", icons, panel));
            panel.setDefaultPortalIcons(portalIconMap);
        }*/
    shared.removeChild("icons");
    //set the (global) editor display widgets to their flag settings
    panel.initView();
    // load the contents
    List<Element> items = shared.getChildren();
    for (Element item : items) {
        String adapterName = item.getAttribute("class").getValue();
        log.debug("load via {}", adapterName);
        try {
            XmlAdapter adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
            // and do it
            adapter.load(item, panel);
            if (!panel.loadOK()) {
                result = false;
            }
        } catch (Exception e) {
            log.error("Exception while loading {}: {}", item.getName(), e.getMessage(), e);
            result = false;
        }
    }
    if (icons != null) {
        HashMap<String, NamedIcon> portalIconMap = new HashMap<String, NamedIcon>();
        portalIconMap.put(PortalIcon.VISIBLE, loadIcon("visible", icons, panel));
        portalIconMap.put(PortalIcon.PATH, loadIcon("path_edit", icons, panel));
        portalIconMap.put(PortalIcon.HIDDEN, loadIcon("hidden", icons, panel));
        portalIconMap.put(PortalIcon.TO_ARROW, loadIcon("to_arrow", icons, panel));
        portalIconMap.put(PortalIcon.FROM_ARROW, loadIcon("from_arrow", icons, panel));
        panel.setDefaultPortalIcons(portalIconMap);
    }
    // dispose of url correction data
    panel.disposeLoadData();
    // display the results, with the editor in back
    panel.pack();
    panel.setAllEditable(panel.isEditable());
    // register the resulting panel for later configuration
    ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
    if (cm != null) {
        cm.registerUser(panel);
    }
    // reset the size and position, in case the display caused it to change
    panel.getTargetFrame().setLocation(x, y);
    panel.getTargetFrame().setSize(width, height);
    panel.setTitle();
    // always show the panel
    panel.getTargetFrame().setVisible(true);
    // do last to set putItem override - unused.
    panel.loadComplete();
    return result;
}
Also used : NamedIcon(jmri.jmrit.catalog.NamedIcon) ControlPanelEditor(jmri.jmrit.display.controlPanelEditor.ControlPanelEditor) Attribute(org.jdom2.Attribute) HashMap(java.util.HashMap) Color(java.awt.Color) Element(org.jdom2.Element) Point(java.awt.Point) ConfigureManager(jmri.ConfigureManager) AbstractXmlAdapter(jmri.configurexml.AbstractXmlAdapter) XmlAdapter(jmri.configurexml.XmlAdapter)

Example 4 with XmlAdapter

use of jmri.configurexml.XmlAdapter in project JMRI by JMRI.

the class LayoutEditorXml method load.

/**
     * Create a LayoutEditor object, then register and fill it, then pop it in a
     * JFrame
     *
     * @param shared Top level Element to unpack.
     */
@Override
public boolean load(Element shared, Element perNode) {
    boolean result = true;
    Attribute a;
    // find coordinates
    int x = 0;
    int y = 0;
    // From this version onwards separate sizes for window and panel are used
    int windowHeight = 400;
    int windowWidth = 300;
    int panelHeight = 340;
    int panelWidth = 280;
    int sidetrackwidth = 3;
    int mainlinetrackwidth = 3;
    try {
        x = shared.getAttribute("x").getIntValue();
        y = shared.getAttribute("y").getIntValue();
        // For compatibility with previous versions, try and see if height and width tags are contained in the file
        if ((a = shared.getAttribute("height")) != null) {
            windowHeight = a.getIntValue();
            panelHeight = windowHeight - 60;
        }
        if ((a = shared.getAttribute("width")) != null) {
            windowWidth = a.getIntValue();
            panelWidth = windowWidth - 18;
        }
        // For files created by the new version, retrieve window and panel sizes
        if ((a = shared.getAttribute("windowheight")) != null) {
            windowHeight = a.getIntValue();
        }
        if ((a = shared.getAttribute("windowwidth")) != null) {
            windowWidth = a.getIntValue();
        }
        if ((a = shared.getAttribute("panelheight")) != null) {
            panelHeight = a.getIntValue();
        }
        if ((a = shared.getAttribute("panelwidth")) != null) {
            panelWidth = a.getIntValue();
        }
        mainlinetrackwidth = shared.getAttribute("mainlinetrackwidth").getIntValue();
        sidetrackwidth = shared.getAttribute("sidetrackwidth").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
        log.error("failed to convert LayoutEditor's attribute");
        result = false;
    }
    double xScale = 1.0;
    double yScale = 1.0;
    a = shared.getAttribute("xscale");
    if (a != null) {
        try {
            xScale = (Float.parseFloat(a.getValue()));
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    a = shared.getAttribute("yscale");
    if (a != null) {
        try {
            yScale = (Float.parseFloat(a.getValue()));
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    // find the name and default track color
    String name = "";
    if (shared.getAttribute("name") != null) {
        name = shared.getAttribute("name").getValue();
    }
    if (jmri.jmrit.display.PanelMenu.instance().isPanelNameUsed(name)) {
        JFrame frame = new JFrame("DialogDemo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        log.warn("File contains a panel with the same name (" + name + ") as an existing panel");
        int n = JOptionPane.showConfirmDialog(frame, java.text.MessageFormat.format(rb.getString("DuplicatePanel"), new Object[] { name }), rb.getString("DuplicatePanelTitle"), JOptionPane.YES_NO_OPTION);
        if (n == JOptionPane.NO_OPTION) {
            return false;
        }
    }
    String defaultColor = "black";
    String defaultTextColor = "black";
    if (shared.getAttribute("defaulttrackcolor") != null) {
        defaultColor = shared.getAttribute("defaulttrackcolor").getValue();
    }
    if (shared.getAttribute("defaulttextcolor") != null) {
        defaultTextColor = shared.getAttribute("defaulttextcolor").getValue();
    }
    //default to using use default track color for circle color
    String turnoutCircleColor = "track";
    if (shared.getAttribute("turnoutcirclecolor") != null) {
        turnoutCircleColor = shared.getAttribute("turnoutcirclecolor").getValue();
    }
    int turnoutCircleSize = 2;
    if (shared.getAttribute("turnoutcirclesize") != null) {
        try {
            turnoutCircleSize = shared.getAttribute("turnoutcirclesize").getIntValue();
        } catch (DataConversionException e1) {
            //leave at default if cannot convert
            log.warn("unable to convert turnoutcirclesize");
        }
    }
    boolean turnoutDrawUnselectedLeg = true;
    if ((a = shared.getAttribute("turnoutdrawunselectedleg")) != null && a.getValue().equals("no")) {
        turnoutDrawUnselectedLeg = false;
    }
    // create the objects
    LayoutEditor panel = new LayoutEditor(name);
    panel.setLayoutName(name);
    panel.setMainlineTrackWidth(mainlinetrackwidth);
    panel.setSideTrackWidth(sidetrackwidth);
    panel.setDefaultTrackColor(defaultColor);
    panel.setDefaultTextColor(defaultTextColor);
    panel.setTurnoutCircleColor(turnoutCircleColor);
    panel.setTurnoutCircleSize(turnoutCircleSize);
    panel.setTurnoutDrawUnselectedLeg(turnoutDrawUnselectedLeg);
    panel.setXScale(xScale);
    panel.setYScale(yScale);
    // turnout size parameters
    double sz = 20.0;
    a = shared.getAttribute("turnoutbx");
    if (a != null) {
        try {
            sz = (Float.parseFloat(a.getValue()));
            panel.setTurnoutBX(sz);
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    a = shared.getAttribute("turnoutcx");
    if (a != null) {
        try {
            sz = (Float.parseFloat(a.getValue()));
            panel.setTurnoutCX(sz);
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    a = shared.getAttribute("turnoutwid");
    if (a != null) {
        try {
            sz = (Float.parseFloat(a.getValue()));
            panel.setTurnoutWid(sz);
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    a = shared.getAttribute("xoverlong");
    if (a != null) {
        try {
            sz = (Float.parseFloat(a.getValue()));
            panel.setXOverLong(sz);
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    a = shared.getAttribute("xoverhwid");
    if (a != null) {
        try {
            sz = (Float.parseFloat(a.getValue()));
            panel.setXOverHWid(sz);
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    a = shared.getAttribute("xovershort");
    if (a != null) {
        try {
            sz = (Float.parseFloat(a.getValue()));
            panel.setXOverShort(sz);
        } catch (Exception e) {
            log.error("failed to convert to float - " + a.getValue());
            result = false;
        }
    }
    // grid size parameter
    // this value is never used but it's the default
    int iz = 10;
    a = shared.getAttribute("gridSize");
    if (a != null) {
        try {
            iz = (Integer.parseInt(a.getValue()));
            panel.setGridSize(iz);
        } catch (Exception e) {
            log.error("failed to convert to int - " + a.getValue());
            result = false;
        }
    }
    // second grid size parameter
    // this value is never used but it's the default
    iz = 10;
    a = shared.getAttribute("gridSize2nd");
    if (a != null) {
        try {
            iz = (Integer.parseInt(a.getValue()));
            panel.setGridSize2nd(iz);
        } catch (Exception e) {
            log.error("failed to convert to int - " + a.getValue());
            result = false;
        }
    }
    // set contents state
    String slValue = "both";
    if ((a = shared.getAttribute("sliders")) != null && a.getValue().equals("no")) {
        slValue = "none";
    }
    if ((a = shared.getAttribute("scrollable")) != null) {
        slValue = a.getValue();
    }
    boolean edValue = true;
    if ((a = shared.getAttribute("editable")) != null && a.getValue().equals("no")) {
        edValue = false;
    }
    boolean value = true;
    if ((a = shared.getAttribute("positionable")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllPositionable(value);
    value = true;
    if ((a = shared.getAttribute("controlling")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setAllControlling(value);
    value = true;
    if ((a = shared.getAttribute("animating")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setTurnoutAnimation(value);
    boolean hbValue = true;
    if ((a = shared.getAttribute("showhelpbar")) != null && a.getValue().equals("no")) {
        hbValue = false;
    }
    boolean dgValue = false;
    if ((a = shared.getAttribute("drawgrid")) != null && a.getValue().equals("yes")) {
        dgValue = true;
    }
    boolean sgaValue = false;
    if ((a = shared.getAttribute("snaponadd")) != null && a.getValue().equals("yes")) {
        sgaValue = true;
    }
    boolean sgmValue = false;
    if ((a = shared.getAttribute("snaponmove")) != null && a.getValue().equals("yes")) {
        sgmValue = true;
    }
    boolean aaValue = false;
    if ((a = shared.getAttribute("antialiasing")) != null && a.getValue().equals("yes")) {
        aaValue = true;
    }
    value = false;
    if ((a = shared.getAttribute("turnoutcircles")) != null && a.getValue().equals("yes")) {
        value = true;
    }
    panel.setTurnoutCircles(value);
    value = false;
    if ((a = shared.getAttribute("tooltipsnotedit")) != null && a.getValue().equals("yes")) {
        value = true;
    }
    panel.setTooltipsNotEdit(value);
    value = false;
    if ((a = shared.getAttribute("autoblkgenerate")) != null && a.getValue().equals("yes")) {
        value = true;
    }
    panel.setAutoBlockAssignment(value);
    value = true;
    if ((a = shared.getAttribute("tooltipsinedit")) != null && a.getValue().equals("no")) {
        value = false;
    }
    panel.setTooltipsInEdit(value);
    // set default track color
    if ((a = shared.getAttribute("defaulttrackcolor")) != null) {
        panel.setDefaultTrackColor(a.getValue());
    }
    // set default track color
    if ((a = shared.getAttribute("defaultoccupiedtrackcolor")) != null) {
        panel.setDefaultOccupiedTrackColor(a.getValue());
    }
    // set default track color
    if ((a = shared.getAttribute("defaultalternativetrackcolor")) != null) {
        panel.setDefaultAlternativeTrackColor(a.getValue());
    }
    try {
        int red = shared.getAttribute("redBackground").getIntValue();
        int blue = shared.getAttribute("blueBackground").getIntValue();
        int green = shared.getAttribute("greenBackground").getIntValue();
        panel.setDefaultBackgroundColor(ColorUtil.colorToString(new Color(red, green, blue)));
        panel.setBackgroundColor(new Color(red, green, blue));
    } catch (org.jdom2.DataConversionException e) {
        log.warn("Could not parse color attributes!");
    } catch (NullPointerException e) {
    // considered normal if the attributes are not present
    }
    if (shared.getAttribute("useDirectTurnoutControl") != null) {
        if (shared.getAttribute("useDirectTurnoutControl").getValue().equals("yes")) {
            panel.setDirectTurnoutControl(true);
        }
    }
    // note: moving zoom attribute into per-window user preference
    //if (shared.getAttribute("zoom") != null) {
    //    panel.setZoom(Double.valueOf(shared.getAttribute("zoom").getValue()));
    //}
    // Set editor's option flags, load content after
    // this so that individual item flags are set as saved
    panel.initView();
    // load the contents
    List<Element> items = shared.getChildren();
    for (int i = 0; i < items.size(); i++) {
        // get the class, hence the adapter object to do loading
        Element item = items.get(i);
        String adapterName = item.getAttribute("class").getValue();
        if (log.isDebugEnabled()) {
            String id = "<null>";
            try {
                id = item.getAttribute("ident").getValue();
                log.debug("Load " + id + " for [" + panel.getName() + "] via " + adapterName);
            } catch (Exception e) {
                log.debug("Load layout object for [" + panel.getName() + "] via " + adapterName);
            }
        }
        try {
            XmlAdapter adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
            // and do it
            adapter.load(item, panel);
            if (!panel.loadOK()) {
                result = false;
            }
        } catch (Exception e) {
            log.error("Exception while loading " + item.getName() + ":" + e);
            result = false;
            e.printStackTrace();
        }
    }
    // dispose of url correction data
    panel.disposeLoadData();
    // final initialization of objects
    panel.setConnections();
    // display the results
    // set first since other attribute use this setting
    panel.setAllEditable(edValue);
    panel.setShowHelpBar(hbValue);
    panel.setDrawGrid(dgValue);
    panel.setSnapOnAdd(sgaValue);
    panel.setSnapOnMove(sgmValue);
    panel.setAntialiasingOn(aaValue);
    panel.setScroll(slValue);
    panel.pack();
    panel.setLayoutDimensions(windowWidth, windowHeight, x, y, panelWidth, panelHeight);
    // always show the panel
    panel.setVisible(true);
    panel.resetDirty();
    // register the resulting panel for later configuration
    ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
    if (cm != null) {
        cm.registerUser(panel);
    }
    //open Dispatcher frame if any Transits are defined, and open Dispatcher flag set on
    if (jmri.InstanceManager.getDefault(jmri.TransitManager.class).getSystemNameList().size() > 0) {
        if (shared.getAttribute("openDispatcher") != null) {
            if (shared.getAttribute("openDispatcher").getValue().equals("yes")) {
                panel.setOpenDispatcherOnLoad(true);
                jmri.jmrit.dispatcher.DispatcherFrame df = jmri.jmrit.dispatcher.DispatcherFrame.instance();
                df.loadAtStartup();
            } else {
                panel.setOpenDispatcherOnLoad(false);
            }
        }
    }
    return result;
}
Also used : LayoutEditor(jmri.jmrit.display.layoutEditor.LayoutEditor) Attribute(org.jdom2.Attribute) Color(java.awt.Color) Element(org.jdom2.Element) DataConversionException(org.jdom2.DataConversionException) ConfigureManager(jmri.ConfigureManager) JFrame(javax.swing.JFrame) DataConversionException(org.jdom2.DataConversionException) DataConversionException(org.jdom2.DataConversionException) AbstractXmlAdapter(jmri.configurexml.AbstractXmlAdapter) XmlAdapter(jmri.configurexml.XmlAdapter)

Example 5 with XmlAdapter

use of jmri.configurexml.XmlAdapter in project JMRI by JMRI.

the class PanelEditor method pasteItem.

protected void pasteItem(MouseEvent e) {
    pasteItemFlag = true;
    XmlAdapter adapter;
    String className;
    int x;
    int y;
    int xOrig;
    int yOrig;
    if (_multiItemCopyGroup != null) {
        JComponent copied;
        int xoffset;
        int yoffset;
        x = _multiItemCopyGroup.get(0).getX();
        y = _multiItemCopyGroup.get(0).getY();
        xoffset = e.getX() - x;
        yoffset = e.getY() - y;
        /*We make a copy of the selected items and work off of that copy
             as amendments are made to the multiItemCopyGroup during this process
             which can result in a loop*/
        ArrayList<Positionable> _copyOfMultiItemCopyGroup = new ArrayList<Positionable>(_multiItemCopyGroup);
        Collections.copy(_copyOfMultiItemCopyGroup, _multiItemCopyGroup);
        for (Positionable comp : _copyOfMultiItemCopyGroup) {
            copied = (JComponent) comp;
            xOrig = copied.getX();
            yOrig = copied.getY();
            x = xOrig + xoffset;
            y = yOrig + yoffset;
            if (x < 0) {
                x = 1;
            }
            if (y < 0) {
                y = 1;
            }
            className = ConfigXmlManager.adapterName(copied);
            copied.setLocation(x, y);
            try {
                adapter = (XmlAdapter) Class.forName(className).newInstance();
                Element el = adapter.store(copied);
                adapter.load(el, this);
            } catch (Exception ex) {
                log.debug(ex.getLocalizedMessage(), ex);
            }
            /*We remove the original item from the list, so we end up with
                 just the new items selected and allow the items to be moved around */
            amendSelectionGroup(comp);
            copied.setLocation(xOrig, yOrig);
        }
        _selectionGroup = null;
    }
    pasteItemFlag = false;
    _targetPanel.repaint();
}
Also used : Element(org.jdom2.Element) JComponent(javax.swing.JComponent) ArrayList(java.util.ArrayList) Positionable(jmri.jmrit.display.Positionable) XmlAdapter(jmri.configurexml.XmlAdapter)

Aggregations

XmlAdapter (jmri.configurexml.XmlAdapter)10 Element (org.jdom2.Element)9 AbstractXmlAdapter (jmri.configurexml.AbstractXmlAdapter)5 Color (java.awt.Color)4 ConfigureManager (jmri.ConfigureManager)4 Attribute (org.jdom2.Attribute)4 Point (java.awt.Point)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 InitializationException (jmri.util.prefs.InitializationException)2 JDOMException (org.jdom2.JDOMException)2 GuiLafPreferencesManager (apps.gui.GuiLafPreferencesManager)1 StartupActionModelUtil (apps.startup.StartupActionModelUtil)1 StartupModel (apps.startup.StartupModel)1 StartupModelFactory (apps.startup.StartupModelFactory)1 List (java.util.List)1 Locale (java.util.Locale)1 ServiceLoader (java.util.ServiceLoader)1 Set (java.util.Set)1 JComponent (javax.swing.JComponent)1