Package fbench.graph.popup

Source Code of fbench.graph.popup.FBNetworkDialog$AddConnectionButtonListener

package fbench.graph.popup;

import static javax.swing.GroupLayout.Alignment.CENTER;
import static javax.swing.GroupLayout.Alignment.LEADING;
import static javax.swing.GroupLayout.Alignment.TRAILING;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.DesignMode;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import fbench.IconFactory;
import fbench.Library;
import fbench.graph.Connection;
import fbench.graph.ECState;
import fbench.graph.FB;
import fbench.graph.GraphElement;
import fbench.graph.GraphLayout;
import fbench.graph.GraphView;
import fbench.graph.model.GraphModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
* Dialog which extends DialogModel for adding, editing and
* deleting components of <B>FBNetwork GraphModel</B>.</br>
* <B>FBNetwork</B> consists of:
*     <TT>FB</TT> and
*     <TT>Connection</TT>
*
* @author JP
* @version 20070228/JP
*/
@SuppressWarnings("serial")
public class FBNetworkDialog extends DialogModel{
  private JLabel commentLabel = new JLabel("Comment :");
  private JLabel connectionType = new JLabel("Connection Type : ");
  private JLabel nameLabel = new JLabel("Name :");
  private JLabel typeLabel = new JLabel("Type :");
 
  private ImageIcon fbIcon = IconFactory.getIcon("Import16.gif");
  private JLabel addFBButton = new JLabel(fbIcon);
 
  private JTextField commentField = new JTextField();
  private JTextField nameField = new JTextField();
  private JTextField typeField = new JTextField();
 
  Dimension fbBoxDimension = new Dimension(135, 25);
  Dimension fbVariableDimension = new Dimension(75, 25);
 
  private JComboBox destinationInputBox, destinationFBBox, sourceOutputBox, sourceFBBox;
  private JPanel fbPreviewPane, sourcePanel, destinationPanel;
  private JRadioButton eventButton, variableButton;
 
  private JButton acceptButton;
  private JButton cancelButton = new JButton("Cancel");
  private JButton helpButton = new JButton("Help");
 
  private String sourceFBName = null;
  private String destinationFBName = null;
 
  /**
   * element is GraphModel element when FBNetworkDialog is created for
   * the purpose of <B>adding</B> a new FB or connection,
   * otherwise (if its purpose is for <b>editing</b> or <b>deleting</b>),
   * element is the selected GraphElement element.
   */
  public FBNetworkDialog(Element element, MouseEvent mouseEvt){
    super(element, mouseEvt);
  }

  @Override
  public void create(String command) {
    if(command.equals("Add Function Block")){
      createDialogForFB(null);
    } else if(command.equals("Add Connection")){
      createDialogForConnection(null);
    }
   
    else if(command.equals("Edit Function Block")){
      Element functionBlock = rearrangeElement();
      createDialogForFB(functionBlock);
    } else if(command.equals("Edit Connection")) {
      Element connection = rearrangeElement();
      createDialogForConnection(connection);
    }
   
    else if(command.equals("Delete Function Block") || command.equals("Delete Connection")){
      createRemoveDialog();
    }
    setVisible(true);
  }

  private boolean isForAddingConn = false;
  private Element connectionElement = null;
  private void createDialogForConnection(Element connectionElem) {
    connectionElement = connectionElem;
    if(connectionElem == null)
      isForAddingConn = true;
    else
      isForAddingConn = false;
   
    setTitle(isForAddingConn ? "Add Connection" : "Editing Connection");
    setDialogSize(500, 200);
       
    Vector<String> fbNameList = getFBNameList();

    //Components for the type selection part
    eventButton = new JRadioButton("Event");
    eventButton.addActionListener(new ActionListener(){
      public void actionPerformed(final ActionEvent evt) {
        String sourceFBName = sourceFBBox.getSelectedItem().toString();
        String destinationFBName = destinationFBBox.getSelectedItem().toString();

        sourceOutputBox.setModel(new DefaultComboBoxModel(
            getFBTypeComponentList(sourceFBName, true, false)));
        destinationInputBox.setModel(new DefaultComboBoxModel(
            getFBTypeComponentList(destinationFBName, true, true)));
      }
    });

    variableButton = new JRadioButton("Variable");
    variableButton.addActionListener(new ActionListener(){
      public void actionPerformed(final ActionEvent evt) {
        String sourceFBName = sourceFBBox.getSelectedItem().toString();
        String destinationFBName = destinationFBBox.getSelectedItem().toString();

        sourceOutputBox.setModel(new DefaultComboBoxModel(
            getFBTypeComponentList(sourceFBName, false, false)));
        destinationInputBox.setModel(new DefaultComboBoxModel(
            getFBTypeComponentList(destinationFBName, false, true)));
      }
    });

    ButtonGroup typeButtons = new ButtonGroup();
    typeButtons.add(eventButton);
    typeButtons.add(variableButton);
    eventButton.setSelected(true);
   
    //Components for the selection of Source FB and its input
    sourcePanel = createSourcePane(fbNameList);

    //Components for the selection of Destination FB and its output
    destinationPanel = createDestinationPane(fbNameList);

    acceptButton = new JButton(isForAddingFB ? "Add" : "Accept");
    acceptButton.addActionListener(new AddConnectionButtonListener());
    cancelButton.addActionListener(new CancelButtonActionListener());

    setLayoutForConnection();
  }

  private void setLayoutForConnection() {
    layout.linkSize(SwingConstants.HORIZONTAL, eventButton, variableButton);
    layout.linkSize(SwingConstants.HORIZONTAL, acceptButton, cancelButton, helpButton);

    layout.setHorizontalGroup(layout.createParallelGroup(LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(connectionType)
            .addComponent(eventButton)
            .addComponent(variableButton))
        .addGroup(layout.createParallelGroup(CENTER)
            .addGroup(layout.createSequentialGroup()
                .addComponent(sourcePanel)
                .addComponent(destinationPanel))
            .addGroup(layout.createSequentialGroup()
                .addComponent(commentLabel)
                .addComponent(commentField))
            .addGroup(layout.createParallelGroup(CENTER))
            .addGroup(layout.createSequentialGroup()
                .addComponent(acceptButton)
                .addComponent(cancelButton)
                .addComponent(helpButton))));

    layout.setVerticalGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(CENTER)
            .addComponent(connectionType)
            .addComponent(eventButton)
            .addComponent(variableButton))
        .addGroup(layout.createParallelGroup(LEADING)
            .addComponent(sourcePanel)
            .addComponent(destinationPanel))
        .addGroup(layout.createParallelGroup(CENTER)
            .addComponent(commentLabel)
        .addComponent(commentField))
        .addGroup(layout.createParallelGroup(LEADING)
            .addComponent(acceptButton)
            .addComponent(cancelButton)
            .addComponent(helpButton)));
    if(!isForAddingConn){
      NodeList eventConns = document.getElementsByTagName("EventConnections").item(0).getChildNodes();
      boolean isConnectionForEvent = false;
      for(int i = 0; i < eventConns.getLength(); i++){
        if(eventConns.item(i).equals(connectionElement)){
          isConnectionForEvent = true;
          break;
        }
      }
      eventButton.setSelected(isConnectionForEvent);
      variableButton.setSelected(!isConnectionForEvent);
      String source = connectionElement.getAttribute("Source");
      String destination = connectionElement.getAttribute("Destination");
     
     
      sourceFBBox.setSelectedItem(source.substring(0, source.indexOf(".")));
      sourceOutputBox.setSelectedItem(source.substring(source.indexOf(".")+1,source.length()));
      destinationFBBox.setSelectedItem(destination.substring(0, destination.indexOf(".")));
      destinationInputBox.setSelectedItem(destination.substring(destination.indexOf(".")+1,destination.length()));
    }
    else {
      if(sourceFBName != null){
        this.sourceFBBox.setSelectedItem(sourceFBName);
      }
      if(destinationFBName != null){
        this.destinationFBBox.setSelectedItem(destinationFBName);
      }
    }
  }

  private JPanel createDestinationPane(Vector<String> fbNameList) {
    JPanel contentPane = new JPanel();
    TitledBorder destinationPaneBorder = new TitledBorder(" Destination ");
    destinationPaneBorder.setTitleFont(destinationPaneBorder.getTitleFont().deriveFont(new Float(10)));
    contentPane.setBorder(destinationPaneBorder);
    GroupLayout destinationLayout = new GroupLayout(contentPane);
    contentPane.setLayout(destinationLayout);

    JLabel fbLabel2 = new JLabel("Function Block");
    JLabel inputLabel = new JLabel("Input");
    JLabel separatorLabel3 = new JLabel(" : ");
    JLabel separatorLabel4 = new JLabel(" : ");
    destinationFBBox = new JComboBox(fbNameList);
    destinationFBBox.setSelectedIndex(fbNameList.size()-1);
    setComponentSize(destinationFBBox, fbBoxDimension);

    destinationFBBox.addActionListener(new ActionListener(){
      public void actionPerformed( ActionEvent evt){
        boolean isEvent = eventButton.isSelected();
        destinationInputBox.setModel(new DefaultComboBoxModel(
            getFBTypeComponentList(destinationFBBox.getSelectedItem().toString(),
                isEvent, true)));
      }
    });

    String destinationFBName = destinationFBBox.getSelectedItem().toString();
    Vector<String> inputList =
      getFBTypeComponentList(destinationFBName, eventButton.isSelected(), true);
    destinationInputBox = new JComboBox(inputList);
    setComponentSize(destinationInputBox, fbVariableDimension);

    destinationLayout.setHorizontalGroup(destinationLayout.createSequentialGroup()
        .addGroup(destinationLayout.createParallelGroup(CENTER)
            .addComponent(fbLabel2)
            .addComponent(destinationFBBox))
            .addGroup(destinationLayout.createParallelGroup(CENTER)
                .addComponent(separatorLabel3)
                .addComponent(separatorLabel4))
                .addGroup(destinationLayout.createParallelGroup(CENTER)
                    .addComponent(inputLabel)
                    .addComponent(destinationInputBox))
    );
    destinationLayout.setVerticalGroup(destinationLayout.createSequentialGroup()
        .addGroup(destinationLayout.createParallelGroup(LEADING)
            .addComponent(fbLabel2)
            .addComponent(separatorLabel3)
            .addComponent(inputLabel))
            .addGroup(destinationLayout.createParallelGroup(LEADING)
                .addComponent(destinationFBBox)
                .addComponent(separatorLabel4)
                .addComponent(destinationInputBox))
    );
    return contentPane;
  }

  private JPanel createSourcePane(Vector<String> fbNameList) {
    JPanel contentPane = new JPanel();
    TitledBorder sourcePaneBorder = new TitledBorder(" Source ");
    sourcePaneBorder.setTitleFont(sourcePaneBorder.getTitleFont().deriveFont(new Float(10)));
    contentPane.setBorder(sourcePaneBorder);
    GroupLayout sourceLayout = new GroupLayout(contentPane);
    contentPane.setLayout(sourceLayout);

    JLabel fbLabel1 = new JLabel("Function Block");
    JLabel outputLabel = new JLabel("Output");
    JLabel separatorLabel1 = new JLabel(" : ");
    JLabel separatorLabel2 = new JLabel(" : ");

    sourceFBBox = new JComboBox(fbNameList);
    sourceFBBox.setSelectedIndex(0);
    setComponentSize(sourceFBBox, fbBoxDimension, fbVariableDimension);

    sourceFBBox.addActionListener(new ActionListener(){
      public void actionPerformed( ActionEvent evt){
        boolean isEvent = eventButton.isSelected();
        sourceOutputBox.setModel(new DefaultComboBoxModel(
            getFBTypeComponentList(sourceFBBox.getSelectedItem().toString(),
                isEvent, false)));
      }
    });
   
    Object selected = sourceFBBox.getSelectedItem();
    String sourceFBName = selected.toString();
    Vector<String> outputList = getFBTypeComponentList(sourceFBName, eventButton.isSelected(), false);

    System.out.println(outputList);
   
    sourceOutputBox = new JComboBox(outputList);
    //sourceOutputBox = new JComboBox();
    setComponentSize(sourceOutputBox, fbVariableDimension);

    sourceLayout.setHorizontalGroup(sourceLayout.createSequentialGroup()
        .addGroup(sourceLayout.createParallelGroup(CENTER)
            .addComponent(fbLabel1)
            .addComponent(sourceFBBox))
            .addGroup(sourceLayout.createParallelGroup(CENTER)
                .addComponent(separatorLabel1)
                .addComponent(separatorLabel2))
                .addGroup(sourceLayout.createParallelGroup(CENTER)
                    .addComponent(outputLabel)
                    .addComponent(sourceOutputBox))
    );
    sourceLayout.setVerticalGroup(sourceLayout.createSequentialGroup()
        .addGroup(sourceLayout.createParallelGroup(CENTER)
            .addComponent(fbLabel1)
            .addComponent(separatorLabel1)
            .addComponent(outputLabel))
            .addGroup(sourceLayout.createParallelGroup(CENTER)
                .addComponent(sourceFBBox)
                .addComponent(separatorLabel2)
                .addComponent(sourceOutputBox))
    );
    return contentPane;
  }
 
  private Vector<String> getFBNameList() {
    Vector<String> fbNameList = new Vector<String>();
   
    fbNameList.add("START");
   
    NodeList childrenList = getElement().getChildNodes();
    if(getElement().getParentNode().getNodeName().equals("Resource")){
      String resourceFileName = ((Element) getElement().getParentNode()).getAttribute("Type");
      Document resourceDoc = Library.getDocument(resourceFileName);
      if(resourceDoc != null){
        Element resourceFBNetwork = (Element) resourceDoc.getElementsByTagName("FBNetwork").item(0);
        NodeList resourceFBNL = resourceFBNetwork.getChildNodes();
        fbNameList.addAll(extractFBNames(resourceFBNL));
      }
    }
    fbNameList.addAll(extractFBNames(childrenList));
    return fbNameList;
  }

  private Vector<String> extractFBNames (NodeList nl){
    Vector<String> fbNames = new Vector<String>();
    for(int i = 0; i < nl.getLength(); i++)
      if(nl.item(i).getNodeName().equals("FB"))
        fbNames.add(((Element)nl.item(i)).getAttribute("Name"));
    return fbNames;
  }
 
  private boolean isNameNotAcceptable( String fbName,  NodeList childrenList){
    for(int i = 0; i < childrenList.getLength(); i++)
      if(((Element)childrenList.item(i)).getAttribute("Name").equals(fbName))
        return true;
    return false;
  }

  private Vector<String> getFBTypeComponentList( String fbName,
      boolean isEvent, boolean isInput){
    boolean isResource = getElement().getParentNode().getNodeName().equalsIgnoreCase("Resource");
    GraphModel model = GraphModel.forElement(isResource ?
        (Element) getElement().getParentNode() : getElement());
    Vector<String> fbTypeComponentList = new Vector<String>();

    String connectionType = new String();
    if(isEvent && isInput)
      connectionType = "EventInputs";
    else if(isEvent && !isInput)
      connectionType = "EventOutputs";
    else if(!isEvent && isInput)
      connectionType = "InputVars";
    else if(!isEvent&& !isInput)
      connectionType = "OutputVars";

    for ( Enumeration els = model.getGraph().elements(); els.hasMoreElements();) {
      GraphElement ge = (GraphElement) els.nextElement();
      if(ge instanceof FB){
        FB fb = (FB)ge;
        if(fb.getMainLabel().getText().equals(fbName)){
          Document fbDocument = Library.getDocument(fb.getFBType() + ".fbt");
          if(fbDocument != null){
            NodeList connectionTypeNL = fbDocument.getElementsByTagName(connectionType);
            if(connectionTypeNL.getLength() == 0)
              return fbTypeComponentList;
            NodeList interfaceNodes = connectionTypeNL.item(0).getChildNodes();
            for(int i = 0; i < interfaceNodes.getLength(); i++){
              String compName = ((Element)interfaceNodes.item(i)).getAttribute("Name");
              fbTypeComponentList.add(compName);
            }
          }
          return fbTypeComponentList;
        }
      }
    }
    return fbTypeComponentList;
  }
 
 
  private Element fbElement = null;
  private boolean isForAddingFB = false;
  private void createDialogForFB(Element fbElem) {
    if(fbElem == null)
      isForAddingFB = true;
    fbElement = fbElem;

    typeField.setEditable(false);
   
    setTitle(isForAddingFB ? "Add Function Block" : "Edit Function Block");
    setDialogSize(500, 155);
   
    acceptButton = new JButton(isForAddingFB ? "Add" : "Apply");
    acceptButton.addActionListener(new AcceptButtonActionListener());
    cancelButton.addActionListener(new CancelButtonActionListener());

    TitledBorder fbTypeBorder = BorderFactory.createTitledBorder(" FB Preview ");
    Font titleFont = fbTypeBorder.getTitleFont();
    fbTypeBorder.setTitleFont(titleFont.deriveFont(new Float(10)));
    fbPreviewPane = new JPanel();
    fbPreviewPane.setPreferredSize(new Dimension(100,150));
    fbPreviewPane.setLayout(new GraphLayout());
    fbPreviewPane.setBackground(Color.white);
    fbPreviewPane.setBorder(fbTypeBorder);

    addFBButton.setToolTipText("Load function block");
    addFBButton.setBorder(new BevelBorder(BevelBorder.RAISED));
    addFBButton.addMouseListener(new AddFBButtonMouseAdapter());

    setLayoutForFB();
  }

  private void setLayoutForFB() {
    layout.linkSize(SwingConstants.HORIZONTAL, acceptButton, cancelButton, helpButton);

    layout.setHorizontalGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(CENTER)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(nameLabel)
                    .addComponent(typeLabel)
                    .addComponent(commentLabel))
                .addGroup(layout.createParallelGroup(LEADING)
                    .addComponent(nameField)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(typeField)
                        .addComponent(addFBButton))
                    .addComponent(commentField)))
            .addGroup(layout.createSequentialGroup()
                .addComponent(acceptButton)
                .addComponent(cancelButton)
                .addComponent(helpButton)))
        .addComponent(fbPreviewPane));

    layout.setVerticalGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(CENTER)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createBaselineGroup(false, true)
                    .addComponent(nameLabel)
                    .addComponent(nameField))
                .addGroup(layout.createBaselineGroup(false, false)
                    .addComponent(typeLabel)
                    .addComponent(typeField)
                    .addComponent(addFBButton))
                .addGroup(layout.createParallelGroup(TRAILING)
                    .addComponent(commentLabel)
                .addComponent(commentField))
            .addGroup(layout.createParallelGroup(LEADING)
                .addComponent(acceptButton)
                .addComponent(cancelButton)
                .addComponent(helpButton)))
        .addComponent(fbPreviewPane)));
   
    if(!isForAddingFB){
      nameField.setText(fbElement.getAttribute("Name"));
      typeField.setText(fbElement.getAttribute("Type"));
      if(fbElement.hasAttribute("Comment"))
        commentField.setText(fbElement.getAttribute("Comment"));
      drawFBPreviewPane(typeField.getText()+".fbt");
    }
  }

  private void drawFBPreviewPane(String filename){
    typeField.setText(filename);
    Element docElement = Library.getDocument(filename).getDocumentElement();

    fbPreviewPane.removeAll();
    GraphModel model = GraphModel.forElement(docElement);
    if (model != null) {
      for ( Enumeration els = model.getGraph().elements(); els.hasMoreElements();) {
        GraphElement ge = (GraphElement) els.nextElement();
        fbPreviewPane.add(ge);
      }
    }
    Dimension fbPaneSize =
      fbPreviewPane.getLayout().preferredLayoutSize(fbPreviewPane);
    Dimension preferredFBPaneSize =
      new Dimension(fbPaneSize.width, fbPaneSize.height+10);
    setComponentSize(fbPreviewPane, preferredFBPaneSize);
    fbPreviewPane.validate();
    fbPreviewPane.doLayout();
    fbPreviewPane.repaint();
    fbPreviewPane.getParent().validate();
    int dialogHeight = Math.max(preferredFBPaneSize.height+50, 155);
    me.setSize(300+fbPaneSize.width+5, dialogHeight);
  }
 
  public void setSourceFBName(String source) {
    sourceFBName = source;
  }
 
  public void setDestinationFBName (String destination) {
    destinationFBName = destination;
  }

  private class AcceptButtonActionListener implements ActionListener {
    public void actionPerformed( ActionEvent evt) {
      NodeList childrenList = getElement().getChildNodes();

      if(nameField.getText().length() == 0){
        JOptionPane.showMessageDialog(me,
            "Enter Function Block Name",
            "Warning: Empty name",
            JOptionPane.WARNING_MESSAGE);
      } else if(isForAddingFB && isNameNotAcceptable(nameField.getText(), childrenList)){
        JOptionPane.showMessageDialog(me,
            "There exists a FB with the same name",
            "Warning: Try different name",
            JOptionPane.WARNING_MESSAGE);
      }
      else if(typeField.getText().length() == 0){
        JOptionPane.showMessageDialog(me,
            "Select a function block",
            "Warning: No Function Block",
            JOptionPane.WARNING_MESSAGE);
      }
      else {
        //String name = nameField.getText().toUpperCase();
        String name = nameField.getText();
        //String type = typeField.getText().replaceFirst(".fbt", "").toUpperCase();
        String type = typeField.getText().replaceFirst(".fbt", "");
        String comment = commentField.getText();
        if(isForAddingFB){
          Element newFB = document.createElement("FB");
          newFB.setAttribute("Name", name);
          newFB.setAttribute("Type", type);
          if(comment.length() > 0)
            newFB.setAttribute("Comment", comment);
          newFB.setAttribute("x", ""+getMouseEvent().getX()/scaleFactor);
          newFB.setAttribute("y", ""+getMouseEvent().getY()/scaleFactor);


          boolean isAdded = false;
          if(childrenList.getLength() == 0)
            getElement().appendChild(newFB);
          else{
            for(int i = 0; i < childrenList.getLength(); i++){
              if(childrenList.getLength() == 1){
                if(childrenList.item(i).getNodeName().equals("FB")){
                  getElement().insertBefore(newFB, childrenList.item(i+1));
                  isAdded = true;
                }
              } else if(!isAdded && i != childrenList.getLength()-1){
                if(childrenList.item(i).getNodeName().equals("FB") &&
                    !childrenList.item(i+1).getNodeName().equals("FB")){
                  getElement().insertBefore(newFB, childrenList.item(i+1));
                  isAdded = true;
                }

              } else if(!isAdded && i == childrenList.getLength()-1){
                if(childrenList.item(i).getNodeName().equals("FB")){
                  getElement().appendChild(newFB);
                  isAdded = true;
                }
              }
            }
          }
        }
        else {
          String oldName = fbElement.getAttribute("Name");
          fbElement.setAttribute("Name", name);
          fbElement.setAttribute("Type", type);
          fbElement.setAttribute("Comment", comment);
         
          NodeList connectionList = document.getElementsByTagName("Connection");
          for(int i = 0 ; i < connectionList.getLength(); i++){
            Element connection = ((Element)connectionList.item(i));
            String source = connection.getAttribute("Source");
            String destination = connection.getAttribute("Destination");
            if(connection.getAttribute("Source").startsWith(oldName)){
              source = source.replaceFirst(oldName, name);
              connection.setAttribute("Source", source);
            }
            if(connection.getAttribute("Destination").startsWith(oldName)){
              destination = destination.replaceFirst(oldName, name);
              connection.setAttribute("Destination", destination);
            }
          }
        }
       
        if(getElement().getParentNode().getNodeName().equals("Resource"))
          getGraphView().setElement((Element) getElement().getParentNode());
        else
          getGraphView().setElement(getElement());
        me.dispose();
      }
    }
  }

  private class AddFBButtonMouseAdapter extends MouseAdapter{
    public void mousePressed( MouseEvent mevt){
      ((JLabel) mevt.getComponent()).setBorder(new BevelBorder(BevelBorder.LOWERED));
    }
    public void mouseReleased( MouseEvent mevt){
      ((JLabel) mevt.getComponent()).setBorder(new BevelBorder(BevelBorder.RAISED));
    }
    public void mouseClicked( MouseEvent mevt){
      JFileChooser chooser = new JFileChooser("src/");
      FileNameExtensionFilter filter = new FileNameExtensionFilter(
          "IEC61499 Function Block (.fbt)", "fbt");
      chooser.setFileFilter(filter);
      int returnVal = chooser.showOpenDialog(me);

      if(returnVal == JFileChooser.APPROVE_OPTION) {
        String filename = chooser.getSelectedFile().getName();
        drawFBPreviewPane(filename);
      }
    }
  }
 
  class AddConnectionButtonListener implements ActionListener{
    public void actionPerformed( ActionEvent evt) {
      boolean addNewConnection = true;

      NodeList nl = getElement().getChildNodes();

      String newSource = new String();
      String newDestination = new String();
     
      if(sourceFBBox.getSelectedIndex() == destinationFBBox.getSelectedIndex()){
        JOptionPane.showMessageDialog(me,
            "Warning: SourceFB and DestinationFB are the same",
            "Transition Warning",
            JOptionPane.WARNING_MESSAGE);
        return;
      }
       
     
      /**
       * Check if any of ComboBoxes has a null value.
       */
      if(sourceFBBox.getItemCount() > 0 && sourceOutputBox.getItemCount() > 0 &&
          destinationFBBox.getItemCount() > 0 && destinationInputBox.getItemCount() > 0){
        newSource =
          sourceFBBox.getSelectedItem().toString()+"."+
          sourceOutputBox.getSelectedItem().toString();
        newDestination =
          destinationFBBox.getSelectedItem().toString()+"."+
          destinationInputBox.getSelectedItem().toString();
      } else{
        JOptionPane.showMessageDialog(me,
            "Empty Field Exists",
            "Warning: There is an Empty Field.",
            JOptionPane.WARNING_MESSAGE);

        addNewConnection = false;
      }

      /**
       * Loop through each element and check whether there already exists a
       * Connection with the same source and destination.
       */
      for(int i = 0; i < nl.getLength() && addNewConnection; i++){
        if(nl.item(i).getNodeName().equals("EventConnections") && eventButton.isSelected()
            || nl.item(i).getNodeName().equals("DataConnections") && !eventButton.isSelected()){
          NodeList tmpNodeList = nl.item(i).getChildNodes();
          for(int j = 0; j < tmpNodeList.getLength(); j++){
            Element tmpElem = (Element)tmpNodeList.item(j);
            if(addNewConnection && tmpElem.getAttribute("Source").equals(newSource) &&
                tmpElem.getAttribute("Destination").equals(newDestination)){
              JOptionPane.showMessageDialog(me,
                  "There already exists the same connection",
                  "Warning: The Connection Already Exists",
                  JOptionPane.WARNING_MESSAGE);
              addNewConnection = false;
            }
          }
        }
      }
     
      /**
       * Add Connection element it has passed all the tests from above.
       */
      if(addNewConnection){
        if(isForAddingConn)
          appendNewConnection();
        else {
          modifyConnection();
        }
        getGraphView().setElement(getElement());
        dispose();
      }
    }
    private void modifyConnection(){
      NodeList eventConnections = document.getElementsByTagName("EventConnections")
          .item(0).getChildNodes();
      boolean isOriginallyEventConnection = false;
      for(int i = 0; i < eventConnections.getLength(); i++){
        if(eventConnections.item(i).equals(connectionElement)){
          isOriginallyEventConnection = true;
          break;
        }
      }
      String source = sourceFBBox.getSelectedItem().toString() + "."
                + sourceOutputBox.getSelectedItem().toString();
      String destination = destinationFBBox.getSelectedItem().toString() + "."
                + destinationInputBox.getSelectedItem().toString();
      connectionElement.setAttribute("Source", source);
      connectionElement.setAttribute("Destination", destination);
      if(eventButton.isSelected() && !isOriginallyEventConnection){
        Element dataConnElem =
          (Element) document.getElementsByTagName("DataConnections").item(0);
        Element eventConnElem =
          (Element) document.getElementsByTagName("EventConnectionS").item(0);
        eventConnElem.appendChild(dataConnElem.removeChild(connectionElement));
      }
      else if(!variableButton.isSelected() && isOriginallyEventConnection){
        Element dataConnElem =
          (Element) document.getElementsByTagName("DataConnections").item(0);
        Element eventConnElem =
          (Element) document.getElementsByTagName("EventConnections").item(0);
        Node removedNode = eventConnElem.removeChild(connectionElement);
        dataConnElem.appendChild(removedNode);
      }
    }
    private void appendNewConnection(){
      String nodeToSelect = new String();
      if(eventButton.isSelected())
        nodeToSelect = "EventConnections";
      else
        nodeToSelect = "DataConnections";

      Element newConnectionElement = document.createElement("Connection");

      newConnectionElement.setAttribute("Source",
          sourceFBBox.getSelectedItem().toString()+"."+
          sourceOutputBox.getSelectedItem().toString());

      newConnectionElement.setAttribute("Destination",
          destinationFBBox.getSelectedItem().toString()+"."+
          destinationInputBox.getSelectedItem().toString());


      String sourceFBName = sourceFBBox.getSelectedItem().toString();
      String destinationFBName = destinationFBBox.getSelectedItem().toString();
      int connectionStartPt = 0;
      int connectionEndPt = 0;
      GraphModel model = GraphModel.forElement(getElement());
      for ( Enumeration els = model.getGraph().elements(); els.hasMoreElements();) {
        GraphElement ge = (GraphElement) els.nextElement();
        if(ge instanceof FB){
          FB fb = (FB)ge;
          if(fb.getMainLabel().getText().equals(sourceFBName))
            connectionStartPt = fb.getPreferredBounds().x;
          else if(fb.getMainLabel().getText().equals(destinationFBName))
            connectionEndPt = fb.getPreferredBounds().x;
        }
      }       
      float dx1 = connectionStartPt + (Math.abs(connectionEndPt - connectionStartPt)/2) / scaleFactor;
      newConnectionElement.setAttribute("dx1", ""+dx1);

      NodeList childrenList = getElement().getChildNodes();
      boolean connectionListNodeFound = false;
      for(int i = 0; i < childrenList.getLength(); i++){
        if(childrenList.item(i).getNodeName().equals(nodeToSelect)){
          childrenList.item(i).appendChild(newConnectionElement);
          connectionListNodeFound = true;
        }
      }
      if(!connectionListNodeFound){
        Element newConnectionList =
          document.createElement(nodeToSelect);
        newConnectionList.appendChild(newConnectionElement);
        if(eventButton.isSelected()){
          if(childrenList.item(childrenList.getLength()-1)
              .getNodeName().equals("DataConnections")){
            getElement().insertBefore(newConnectionList,
                childrenList.item(childrenList.getLength()-1));
          } else {
            getElement().appendChild(newConnectionList);
          }
        } else
          getElement().appendChild(newConnectionList);
      }

    }
  }
}
TOP

Related Classes of fbench.graph.popup.FBNetworkDialog$AddConnectionButtonListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.