Esempio n. 1
0
 private Dim getDim(Element shape) {
   return new Dim(
       Integer.parseInt(shape.getAttribute(ATR_X)),
       Integer.parseInt(shape.getAttribute(ATR_Y)),
       Integer.parseInt(shape.getAttribute(ATR_WIDTH)),
       Integer.parseInt(shape.getAttribute(ATR_HEIGHT)));
 }
  /**
   * WhiteboardObjectTextJabberImpl constructor.
   *
   * @param xml the XML string object to parse.
   */
  public WhiteboardObjectTextJabberImpl(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      InputStream in = new ByteArrayInputStream(xml.getBytes());
      Document doc = builder.parse(in);

      Element e = doc.getDocumentElement();
      String elementName = e.getNodeName();
      if (elementName.equals("text")) {
        // we have a text
        String id = e.getAttribute("id");
        double x = Double.parseDouble(e.getAttribute("x"));
        double y = Double.parseDouble(e.getAttribute("y"));
        String fill = e.getAttribute("fill");
        String fontFamily = e.getAttribute("font-family");
        int fontSize = Integer.parseInt(e.getAttribute("font-size"));
        String text = e.getTextContent();

        this.setID(id);
        this.setWhiteboardPoint(new WhiteboardPoint(x, y));
        this.setFontName(fontFamily);
        this.setFontSize(fontSize);
        this.setText(text);
        this.setColor(Color.decode(fill).getRGB());
      }
    } catch (ParserConfigurationException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (Exception ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    }
  }
Esempio n. 3
0
    private FixedCoords getFixedCoords(Element shape, int width, int height, String suffix) {
      if (suffix == null) suffix = "";
      // parse the coordinates and check if they are fixed or reverse fixed
      String val = shape.getAttribute(ATR_X + suffix);
      int x, y, fixedX = 0, fixedY = 0;
      if (val.endsWith(VAL_RF)) {
        x = width;
        fixedX = x - Integer.parseInt(val.substring(0, val.length() - 2));
      } else if (val.endsWith(VAL_F)) {
        x = Integer.parseInt(val.substring(0, val.length() - 1));
        fixedX = -1;
      } else {
        x = Integer.parseInt(val);
      }
      val = shape.getAttribute(ATR_Y + suffix);
      if (val.endsWith(VAL_RF)) {
        y = height;
        fixedY = y - Integer.parseInt(val.substring(0, val.length() - 2));
      } else if (val.endsWith(VAL_F)) {
        y = Integer.parseInt(val.substring(0, val.length() - 1));
        fixedY = -1;
      } else {
        y = Integer.parseInt(val);
      }

      return new FixedCoords(x, fixedX, y, fixedY);
    }
Esempio n. 4
0
 private Lineprops getLineProps(Element shape) {
   return new Lineprops(
       shape.hasAttribute(ATR_STROKE)
           ? Float.parseFloat(shape.getAttribute(ATR_STROKE))
           : IMPLIED_STROKE,
       shape.hasAttribute(ATR_LINETYPE)
           ? Float.parseFloat(shape.getAttribute(ATR_LINETYPE))
           : IMPLIED_LINE);
 }
Esempio n. 5
0
  private void processPanel(Session session, Element element, HashMap additionalInformation) {
    panelElementPresent = true;
    String panelName = element.getAttribute("name");
    if (panelName == null) {
      panelName = "Panel" + panelCounter++;
    }

    List<Track> panelTracks = new ArrayList();
    NodeList elements = element.getChildNodes();
    for (int i = 0; i < elements.getLength(); i++) {
      Node childNode = elements.item(i);
      if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText())
          || // Is this a track?
          childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) {

        List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation);
        if (tracks != null) {
          panelTracks.addAll(tracks);
        }
      } else {
        process(session, childNode, additionalInformation);
      }
    }

    TrackPanel panel = IGV.getInstance().getTrackPanel(panelName);
    panel.addTracks(panelTracks);
  }
Esempio n. 6
0
 private String getAttribute(Element element, String key) {
   String value = element.getAttribute(key);
   if (value != null) {
     if (value.trim().equals("")) {
       value = null;
     }
   }
   return value;
 }
Esempio n. 7
0
    private Text makeText(Element textNode, ClassGraphics graphics) {
      String str = textNode.getAttribute(ATR_STRING);

      String fontName = textNode.getAttribute(ATR_FONTNAME);
      int fontStyle = Integer.parseInt(textNode.getAttribute(ATR_FONTSTYLE));
      int fontSize = Integer.parseInt(textNode.getAttribute(ATR_FONTSIZE));

      Font font = new Font(fontName, fontStyle, fontSize);

      FixedCoords fc =
          getFixedCoords(textNode, graphics.getBoundWidth(), graphics.getBoundHeight(), null);

      Text newText = new Text(fc.x, fc.y, font, getColor(textNode), str, isShapeFixed(textNode));
      newText.setFixedX(fc.fx);
      newText.setFixedY(fc.fy);

      return newText;
    }
Esempio n. 8
0
  /**
   * Carries out preprocessing that makes JEuclid handle the document better.
   *
   * @param doc Document
   */
  static void preprocessForJEuclid(Document doc) {
    // underbrace and overbrace
    NodeList list = doc.getElementsByTagName("mo");
    for (int i = 0; i < list.getLength(); i++) {
      Element mo = (Element) list.item(i);
      String parentName = ((Element) mo.getParentNode()).getTagName();
      if (parentName == null) {
        continue;
      }
      if (parentName.equals("munder") && isTextChild(mo, "\ufe38")) {
        mo.setAttribute("stretchy", "true");
        mo.removeChild(mo.getFirstChild());
        mo.appendChild(doc.createTextNode("\u23df"));
      } else if (parentName.equals("mover") && isTextChild(mo, "\ufe37")) {
        mo.setAttribute("stretchy", "true");
        mo.removeChild(mo.getFirstChild());
        mo.appendChild(doc.createTextNode("\u23de"));
      }
    }

    // menclose for long division doesn't allow enough top padding. Oh, and
    // <mpadded> isn't implemented. And there isn't enough padding to left of
    // the bar either. Solve by adding an <mover> with just an <mspace> over#
    // the longdiv, contained within an mrow that adds a <mspace> before it.
    list = doc.getElementsByTagName("menclose");
    for (int i = 0; i < list.getLength(); i++) {
      Element menclose = (Element) list.item(i);
      // Only for longdiv
      if (!"longdiv".equals(menclose.getAttribute("notation"))) {
        continue;
      }
      Element mrow = doc.createElementNS(WebMathsService.NS, "mrow");
      Element mover = doc.createElementNS(WebMathsService.NS, "mover");
      Element mspace = doc.createElementNS(WebMathsService.NS, "mspace");
      Element mspaceW = doc.createElementNS(WebMathsService.NS, "mspace");
      boolean previousElement = false;
      for (Node previous = menclose.getPreviousSibling();
          previous != null;
          previous = previous.getPreviousSibling()) {
        if (previous.getNodeType() == Node.ELEMENT_NODE) {
          previousElement = true;
          break;
        }
      }
      if (previousElement) {
        mspaceW.setAttribute("width", "4px");
      }
      menclose.getParentNode().insertBefore(mrow, menclose);
      menclose.getParentNode().removeChild(menclose);
      mrow.appendChild(mspaceW);
      mrow.appendChild(mover);
      mover.appendChild(menclose);
      mover.appendChild(mspace);
    }
  }
Esempio n. 9
0
    private Color getColor(Element shape) {
      Color color;
      if (shape.hasAttribute(ATR_COLOUR)) {
        String s = shape.getAttribute(ATR_COLOUR);
        if (s.indexOf(',') > -1) {
          String[] rgb = s.split(",");
          color =
              new Color(
                  Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2]));
        } else {
          color = new Color(Integer.parseInt(s));
        }
      } else color = IMPLIED_COLOR;

      if (shape.hasAttribute(ATR_TRANSPARENCY)) {
        int alpha = Integer.parseInt(shape.getAttribute(ATR_TRANSPARENCY));
        if (alpha < 255) return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
      }

      return color;
    }
Esempio n. 10
0
  /**
   * XML Circuit constructor
   *
   * @param file the file that contains the XML description of the circuit
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public CircuitUI(File file, Graphics g) throws CircuitLoadingException {
    this("");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    Element root;

    Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>();

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.parse(file);
    } catch (SAXException sxe) {
      throw new CircuitLoadingException("SAX exception raised, invalid XML file.");
    } catch (ParserConfigurationException pce) {
      throw new CircuitLoadingException(
          "Parser exception raised, parser configuration is invalid.");
    } catch (IOException ioe) {
      throw new CircuitLoadingException("I/O exception, file cannot be loaded.");
    }

    root = (Element) doc.getElementsByTagName("Circuit").item(0);
    this.setName(root.getAttribute("name"));

    NodeList nl = root.getElementsByTagName("Node");
    Element e;
    Node n;
    Class cl;

    for (int i = 0; i < nl.getLength(); ++i) {
      e = (Element) nl.item(i);

      try {
        cl = Class.forName(e.getAttribute("class"));
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      try {
        n = ((Node) cl.newInstance());
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      this.nodes.add(n);
      n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y")));

      if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name"));

      if (n instanceof giraffe.ui.CompositeNode) {
        try {
          ((CompositeNode) n)
              .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g);
        } catch (Exception exc) {
          /* try to load from the lib */
          ((CompositeNode) n)
              .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g);
        }
      }

      NodeList nlist = e.getElementsByTagName("Anchor");
      Element el;

      for (int j = 0; j < nlist.getLength(); ++j) {
        el = (Element) nlist.item(j);

        Anchor a = n.getAnchor(new Integer(el.getAttribute("id")));
        NodeList linklist = el.getElementsByTagName("Link");
        Element link;
        Link l;

        for (int k = 0; k < linklist.getLength(); ++k) {
          link = (Element) linklist.item(k);
          int id = new Integer(link.getAttribute("id"));
          int index = new Integer(link.getAttribute("index"));

          if (id >= this.linkID) linkID = id + 1;

          if (linkstable.containsKey(id)) {
            l = linkstable.get(id);
            l.addLinkedAnchorAt(a, index);
            a.addLink(l);
          } else {
            l = new Link(id);
            l.addLinkedAnchorAt(a, index);
            this.links.add(l);
            linkstable.put(id, l);
            a.addLink(l);
          }
        }
      }
    }
  }
Esempio n. 11
0
  private void parseField(PackageClass newClass, Element fieldNode) {
    String name = fieldNode.getAttribute(ATR_NAME);
    String type = fieldNode.getAttribute(ATR_TYPE);

    ClassField newField;

    if (newClass.getComponentType().hasSpec()) {
      if (name.indexOf(".") > -1) {
        // TODO - temporarily do not dig into hierarchy
        int idx = name.indexOf(".");
        String root = name.substring(0, idx);

        if (newClass.getSpecField(root) == null) {
          collector.collectDiagnostic(
              "Field "
                  + root
                  + " in class "
                  + newClass.getName()
                  + " is not declared in the specification, variable "
                  + type
                  + " "
                  + name
                  + " ignored ");
          return;
        }

        newField = new ClassField(name, type);
        newClass.addSpecField(newField);
      } else {
        newField = newClass.getSpecField(name);

        if (newField == null) {

          collector.collectDiagnostic(
              "Field "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " is not declared in the specification");
          return;
        } else if (!newField.getType().equals(type)) {

          collector.collectDiagnostic(
              "Field "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " does not match the field declared in the specification: "
                  + newField.getType()
                  + " "
                  + newField.getName());
          return;
        }
      }
    } else {
      newField = new ClassField(name, type);
      newClass.addSpecField(newField);
    }

    newField.setValue(fieldNode.hasAttribute(ATR_VALUE) ? fieldNode.getAttribute(ATR_VALUE) : null);
    newField.setDescription(fieldNode.getAttribute(ATR_DESCRIPTION));
    newField.setHidden(Boolean.parseBoolean(fieldNode.getAttribute(ATR_HIDDEN)));

    String nature = fieldNode.getAttribute(ATR_NATURE);
    if ("input".equals(nature)) newField.setInput(true);
    else if ("goal".equals(nature)) newField.setGoal(true);

    newClass.addField(newField);

    Element gr;
    // known
    if ((gr = getElementByName(fieldNode, EL_KNOWN)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newField.setKnownGraphics(getGraphicsParser().parse(gr));
    }
    // default
    if ((gr = getElementByName(fieldNode, EL_DEFAULT)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newField.setDefaultGraphics(getGraphicsParser().parse(gr));
    }
  }
Esempio n. 12
0
  private void parsePort(PackageClass newClass, Element portNode) {
    String name = portNode.getAttribute(ATR_NAME);
    String type = portNode.getAttribute(ATR_TYPE);
    String x = portNode.getAttribute(ATR_X);
    String y = portNode.getAttribute(ATR_Y);
    String portConnection = portNode.getAttribute(ATR_PORT_CONNECTION);
    String strict = portNode.getAttribute(ATR_STRICT);
    String multi = portNode.getAttribute(ATR_MULTI);

    ClassField cf = newClass.getSpecField(name);

    if (newClass.getComponentType().hasSpec()) {

      if (name.indexOf(".") > -1) {
        // TODO - temporarily do not dig into hierarchy
        int idx = name.indexOf(".");
        String root = name.substring(0, idx);

        if (newClass.getSpecField(root) == null) {
          collector.collectDiagnostic(
              "Field "
                  + root
                  + " in class "
                  + newClass.getName()
                  + " is not declared in the specification, variable "
                  + type
                  + " "
                  + name
                  + " ignored ");
          return;
        }

        newClass.addSpecField(new ClassField(name, type));
      } else if (!TypeUtil.TYPE_THIS.equalsIgnoreCase(name)) {
        if (cf == null) {

          collector.collectDiagnostic(
              "Port "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " does not have the corresponding field in the specification");
        } else if (!cf.getType().equals(type)
            // type may be declared as "alias", however cf.getType() returns e.g. "double[]", ignore
            // it
            && !(cf.isAlias() && TypeUtil.TYPE_ALIAS.equals(type))) {

          collector.collectDiagnostic(
              "Port "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " does not match the field declared in the specification: "
                  + cf.getType()
                  + " "
                  + cf.getName());
        }
      }
    }

    Port newPort =
        new Port(
            name,
            type,
            Integer.parseInt(x),
            Integer.parseInt(y),
            portConnection,
            Boolean.parseBoolean(strict),
            Boolean.parseBoolean(multi));

    if (portNode.hasAttribute(ATR_ID)) newPort.setId(portNode.getAttribute(ATR_ID));

    Element gr;
    // open
    if ((gr = getElementByName(portNode, EL_OPEN)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newPort.setOpenGraphics(getGraphicsParser().parse(gr));
    }

    // closed
    if ((gr = getElementByName(portNode, EL_CLOSED)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newPort.setClosedGraphics(getGraphicsParser().parse(gr));
    }

    newClass.addPort(newPort);
  }
  @Override
  protected void initChildren(Element eThis) throws OmException {
    Node nPrevious = eThis.getPreviousSibling();
    if (nPrevious != null && nPrevious instanceof Text) {
      String sText = ((Text) nPrevious).getData();
      if (sText.length() > 0 && Character.isWhitespace(sText.charAt(sText.length() - 1)))
        bSpaceBefore = true;
    }
    Node nAfter = eThis.getNextSibling();
    if (nAfter != null && nAfter instanceof Text) {
      String sText = ((Text) nAfter).getData();
      if (sText.length() > 0 && Character.isWhitespace(sText.charAt(0))) bSpaceAfter = true;
    }

    List<Place> lPlaces = new LinkedList<Place>();
    int iPlace = 0;
    StringBuffer sbText = new StringBuffer();
    for (Node n = eThis.getFirstChild(); n != null; n = n.getNextSibling()) {
      if (n instanceof Element) {
        Element eplace = (Element) n;
        if (!eplace.getTagName().equals("eplace"))
          throw new OmFormatException("<equation> may only contain text and <eplace> tags");
        Element[] aeChildren = XML.getChildren(eplace);
        QComponent qcChild;
        boolean bImplicit = false;
        if (aeChildren.length != 1) // Treats more than one child as inside <t>
        {
          qcChild = getQDocument().build(this, eplace, "t");
          bImplicit = true;
        } else // Treats single child as specific component (auto-sizing works)
        qcChild = getQDocument().build(this, aeChildren[0], null);
        addChild(qcChild); // Must be stored in standard child array so it
        // can be found etc.

        // See if width/height is specified
        int iWidth, iHeight;
        if (eplace.hasAttribute("width") && eplace.hasAttribute("height")) {
          try {
            iWidth = Integer.parseInt(eplace.getAttribute("width"));
            iHeight = Integer.parseInt(eplace.getAttribute("height"));
          } catch (NumberFormatException nfe) {
            throw new OmFormatException("<equation> <eplace>: width= and height= must be integers");
          }
        } else {
          Dimension d = qcChild.getApproximatePixelSize();
          if (d == null)
            throw new OmFormatException(
                "<equation> <eplace>: Except for components that support automatic "
                    + "size estimation and fixing, <eplace> must include width= and height=");
          iWidth = d.width;
          iHeight = d.height;
        }

        Place p = new Place();
        p.sID = "p" + (iPlace++);
        p.qc = qcChild;
        p.iWidth = iWidth;
        p.iHeight = iHeight;
        p.bImplicit = bImplicit;
        if (!eplace.hasAttribute("label"))
          throw new OmFormatException("<equation> <eplace>: Must include label=");
        if (eplace.hasAttribute("label")) p.sLabel = eplace.getAttribute("label");
        else p.sLabel = null;
        if (eplace.hasAttribute("for")) p.sLabelFor = eplace.getAttribute("for");
        else if (qcChild instanceof Labelable) p.sLabelFor = qcChild.getID();
        lPlaces.add(p);

        // Add in the equation format text representing the placeholder
        sbText.append("\\placeholder{" + p.sID + "}{" + p.iWidth + "," + p.iHeight + "}");
      } else if (n instanceof Text) {
        sbText.append(n.getNodeValue());
      }
    }
    sEquation = sbText.toString();
    apPlaces = lPlaces.toArray(new Place[0]);
  }
Esempio n. 14
0
  /**
   * creates a new image
   *
   * @param svgHandle a svg handle
   * @param resourceId the id of the resource from which the image will be created
   */
  protected void createNewImage(SVGHandle svgHandle, String resourceId) {

    if (svgHandle != null && resourceId != null && !resourceId.equals("")) {

      Element resourceElement = null;

      resourceElement =
          svgHandle.getScrollPane().getSVGCanvas().getDocument().getElementById(resourceId);

      final String fresourceId = resourceId;

      if (resourceElement != null) {

        final SVGHandle fhandle = svgHandle;

        // creating the canvas and setting its properties
        final JSVGCanvas canvas =
            new JSVGCanvas() {

              @Override
              public void dispose() {

                removeKeyListener(listener);
                removeMouseMotionListener(listener);
                removeMouseListener(listener);
                disableInteractions = true;
                selectableText = false;
                userAgent = null;

                bridgeContext.dispose();
                super.dispose();
              }
            };

        // the element to be added
        Element elementToAdd = null;

        canvas.setDocumentState(JSVGComponent.ALWAYS_STATIC);
        canvas.setDisableInteractions(true);

        // creating the new document
        final String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        final SVGDocument doc = (SVGDocument) resourceElement.getOwnerDocument().cloneNode(false);

        // creating the root element
        final Element root =
            (Element)
                doc.importNode(resourceElement.getOwnerDocument().getDocumentElement(), false);
        doc.appendChild(root);

        // removing all the attributes of the root element
        NamedNodeMap attributes = doc.getDocumentElement().getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {

          if (attributes.item(i) != null) {

            doc.getDocumentElement().removeAttribute(attributes.item(i).getNodeName());
          }
        }

        // adding the new attributes for the root
        root.setAttributeNS(null, "width", imageSize.width + "");
        root.setAttributeNS(null, "height", imageSize.height + "");
        root.setAttributeNS(null, "viewBox", "0 0 " + imageSize.width + " " + imageSize.height);

        // the defs element that will contain the cloned resource node
        final Element defs = (Element) doc.importNode(resourceElement.getParentNode(), true);
        root.appendChild(defs);

        if (resourceElement.getNodeName().equals("linearGradient")
            || resourceElement.getNodeName().equals("radialGradient")
            || resourceElement.getNodeName().equals("pattern")) {

          // the rectangle that will be drawn
          final Element rect = doc.createElementNS(svgNS, "rect");
          rect.setAttributeNS(null, "x", "0");
          rect.setAttributeNS(null, "y", "0");
          rect.setAttributeNS(null, "width", imageSize.width + "");
          rect.setAttributeNS(null, "height", imageSize.height + "");

          elementToAdd = rect;

          // setting that the rectangle uses the resource
          String id = resourceElement.getAttribute("id");

          if (id == null) {

            id = "";
          }

          rect.setAttributeNS(null, "style", "fill:url(#" + id + ");");

          // getting the cloned resource node
          Node cur = null;
          Element clonedResourceElement = null;
          String id2 = "";

          for (cur = defs.getFirstChild(); cur != null; cur = cur.getNextSibling()) {

            if (cur instanceof Element) {

              id2 = ((Element) cur).getAttribute("id");

              if (id2 != null && id.equals(id2)) {

                clonedResourceElement = (Element) cur;
              }
            }
          }

          if (clonedResourceElement != null) {

            // getting the root element of the initial resource
            // element
            Element initialRoot = resourceElement.getOwnerDocument().getDocumentElement();

            // getting the width and height of the initial root
            // element
            double initialWidth = 0, initialHeight = 0;

            try {
              initialWidth =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "width"));
              initialHeight =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "height"));
            } catch (DOMException ex) {
              ex.printStackTrace();
            }

            if (resourceElement.getNodeName().equals("linearGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  x1 = Double.parseDouble(resourceElement.getAttributeNS(null, "x1"));
                  y1 = Double.parseDouble(resourceElement.getAttributeNS(null, "y1"));
                  x2 = Double.parseDouble(resourceElement.getAttributeNS(null, "x2"));
                  y2 = Double.parseDouble(resourceElement.getAttributeNS(null, "y2"));

                  x1 = x1 / initialWidth * imageSize.width;
                  y1 = y1 / initialHeight * imageSize.height;
                  x2 = x2 / initialWidth * imageSize.width;
                  y2 = y2 / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x1", format.format(x1));
                clonedResourceElement.setAttributeNS(null, "y1", format.format(y1));
                clonedResourceElement.setAttributeNS(null, "x2", format.format(x2));
                clonedResourceElement.setAttributeNS(null, "y2", format.format(y2));
              }

            } else if (resourceElement.getNodeName().equals("radialGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double cx = 0, cy = 0, r = 0, fx = 0, fy = 0;

                // normalizing the values for the circle to fit
                // the rectangle
                try {
                  cx = Double.parseDouble(resourceElement.getAttributeNS(null, "cx"));
                  cy = Double.parseDouble(resourceElement.getAttributeNS(null, "cy"));
                  r = Double.parseDouble(resourceElement.getAttributeNS(null, "r"));
                  fx = Double.parseDouble(resourceElement.getAttributeNS(null, "fx"));
                  fy = Double.parseDouble(resourceElement.getAttributeNS(null, "fy"));

                  cx = cx / initialWidth * imageSize.width;
                  cy = cy / initialHeight * imageSize.height;

                  r =
                      r
                          / (Math.abs(
                              Math.sqrt(Math.pow(initialWidth, 2) + Math.pow(initialHeight, 2))))
                          * Math.abs(
                              Math.sqrt(
                                  Math.pow(imageSize.width, 2) + Math.pow(imageSize.width, 2)));

                  fx = fx / initialWidth * imageSize.width;
                  fy = fy / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "cx", format.format(cx));
                clonedResourceElement.setAttributeNS(null, "cy", format.format(cy));
                clonedResourceElement.setAttributeNS(null, "r", format.format(r));
                clonedResourceElement.setAttributeNS(null, "fx", format.format(fx));
                clonedResourceElement.setAttributeNS(null, "fy", format.format(fy));
              }

            } else if (resourceElement.getNodeName().equals("pattern")) {

              if (resourceElement.getAttributeNS(null, "patternUnits").equals("userSpaceOnUse")) {

                double x = 0, y = 0, w = 0, h = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  String xString = resourceElement.getAttributeNS(null, "x");
                  if (!xString.equals("")) {
                    x = Double.parseDouble(xString);
                  }
                  String yString = resourceElement.getAttributeNS(null, "y");
                  if (!yString.equals("")) {
                    y = Double.parseDouble(yString);
                  }
                  String wString = resourceElement.getAttributeNS(null, "w");
                  if (!wString.equals("")) {
                    w = Double.parseDouble(wString);
                  }
                  String hString = resourceElement.getAttributeNS(null, "h");
                  if (!hString.equals("")) {
                    h = Double.parseDouble(hString);
                  }

                  x = x / initialWidth * imageSize.width;
                  y = y / initialHeight * imageSize.height;
                  w = w / initialWidth * imageSize.width;
                  h = h / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x", format.format(x));
                clonedResourceElement.setAttributeNS(null, "y", format.format(y));
                clonedResourceElement.setAttributeNS(null, "width", format.format(w));
                clonedResourceElement.setAttributeNS(null, "height", format.format(h));
              }
            }
          }

        } else if (resourceElement.getNodeName().equals("marker")) {

          // the line that will be drawn
          final Element line = doc.createElementNS(svgNS, "line");
          line.setAttributeNS(null, "x1", (((double) imageSize.width) / 2) + "");
          line.setAttributeNS(null, "y1", (((double) imageSize.height) / 2) + "");
          line.setAttributeNS(null, "x2", ((double) imageSize.width / 2) + "");
          line.setAttributeNS(null, "y2", imageSize.height + "");

          elementToAdd = line;

          // setting that the line uses the resource
          String id = resourceElement.getAttribute("id");
          if (id == null) id = "";
          line.setAttributeNS(
              null, "style", "stroke:none;fill:none;marker-start:url(#" + id + ");");
        }

        root.appendChild(elementToAdd);

        // adding a rendering listener to the canvas
        GVTTreeRendererAdapter gVTTreeRendererAdapter =
            new GVTTreeRendererAdapter() {

              @Override
              public void gvtRenderingCompleted(GVTTreeRendererEvent evt) {

                Image bufferedImage = canvas.getOffScreen();

                if (bufferedImage != null) {

                  Graphics g = bufferedImage.getGraphics();
                  Color borderColor = MetalLookAndFeel.getSeparatorForeground();

                  g.setColor(borderColor);
                  g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
                }

                setImage(fhandle, fresourceId, bufferedImage);

                // refreshing the panels that have been created when no
                // image was available for them
                Image image = null;

                for (ResourceRepresentation resourceRepresentation :
                    new LinkedList<ResourceRepresentation>(resourceRepresentationList)) {

                  if (resourceRepresentation != null) {

                    resourceRepresentation.refreshRepresentation();
                    image = resourceRepresentation.getImage();

                    if (image != null) {

                      resourceRepresentationList.remove(resourceRepresentation);
                    }
                  }
                }

                canvas.removeGVTTreeRendererListener(this);
                canvas.stopProcessing();
                canvas.dispose();
              }
            };

        canvas.addGVTTreeRendererListener(gVTTreeRendererAdapter);

        // setting the document for the canvas
        canvas.setSVGDocument(doc);

        canvas.setBackground(Color.white);
        canvas.setBounds(1, 1, imageSize.width, imageSize.height);
      }
    }
  }
Esempio n. 15
0
 private boolean isShapeFixed(Element shape) {
   return Boolean.parseBoolean(shape.getAttribute(ATR_FIXED));
 }
Esempio n. 16
0
    private ClassGraphics parse(Element grNode /*, boolean isRelation*/) {
      ClassGraphics newGraphics = new ClassGraphics();
      newGraphics.setShowFields(Boolean.parseBoolean(grNode.getAttribute(ATR_SHOW_FIELDS)));
      // newGraphics.setRelation( isRelation );

      NodeList list = grNode.getChildNodes();
      for (int k = 0; k < list.getLength(); k++) {
        if (list.item(k).getNodeType() != Node.ELEMENT_NODE) continue;
        Element node = (Element) list.item(k);
        String nodeName = node.getNodeName();

        Shape shape = null;
        if (EL_BOUNDS.equals(nodeName)) {
          Dim dim = getDim(node);
          newGraphics.setBounds(dim.x, dim.y, dim.width, dim.height);
          continue;
        } else if (EL_LINE.equals(nodeName)) {

          shape = makeLine(node, newGraphics);

        } else if (EL_RECT.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Rect(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_OVAL.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Oval(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_ARC.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          int startAngle = Integer.parseInt(node.getAttribute(ATR_START_ANGLE));
          int arcAngle = Integer.parseInt(node.getAttribute(ATR_ARC_ANGLE));
          shape =
              new Arc(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  startAngle,
                  arcAngle,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_POLYGON.equals(nodeName)) {
          Lineprops lp = getLineProps(node);

          Polygon polygon =
              new Polygon(getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType);

          // points
          NodeList points = node.getElementsByTagName(EL_POINT);
          int pointCount = points.getLength();
          // arrays of polygon points
          int[] xs = new int[pointCount];
          int[] ys = new int[pointCount];
          // arrays of FIXED information about polygon points
          int[] fxs = new int[pointCount];
          int[] fys = new int[pointCount];
          int width = newGraphics.getBoundWidth();
          int height = newGraphics.getBoundHeight();

          for (int j = 0; j < pointCount; j++) {
            FixedCoords fc = getFixedCoords((Element) points.item(j), width, height, null);
            xs[j] = fc.x;
            fxs[j] = fc.fx;
            ys[j] = fc.y;
            fys[j] = fc.fy;
          }

          polygon.setPoints(xs, ys, fxs, fys);
          shape = polygon;

        } else if (EL_IMAGE.equals(nodeName)) {

          Dim dim = getDim(node);
          // image path should be relative to the package xml
          String imgPath = node.getAttribute(ATR_PATH);
          String fullPath = FileFuncs.preparePathOS(getWorkingDir() + imgPath);
          shape = new Image(dim.x, dim.y, fullPath, imgPath, isShapeFixed(node));

        } else if (EL_TEXT.equals(nodeName)) {
          shape = makeText(node, newGraphics);
          /*
           * if (str.equals("*self")) newText.name = "self"; else if
           * (str.equals("*selfWithName")) newText.name = "selfName";
           */
        }

        if (shape != null) newGraphics.addShape(shape);
      }

      return newGraphics;
    }
Esempio n. 17
0
  private PackageClass parseClass(Element classNode) {
    PackageClass newClass = new PackageClass();
    _package.getClasses().add(newClass);

    newClass.setComponentType(PackageClass.ComponentType.getType(classNode.getAttribute(ATR_TYPE)));
    newClass.setStatic(Boolean.parseBoolean(classNode.getAttribute(ATR_STATIC)));
    newClass.setName(getElementByName(classNode, EL_NAME).getTextContent());
    final String source = getElementStringByName(classNode, EL_FILE);
    if (source != null) {
      newClass.setSource(source);
    }
    newClass.setTarget(getElementStringByName(classNode, EL_EXTENDS));
    newClass.setDescription(getElementByName(classNode, EL_DESCRIPTION).getTextContent());
    newClass.setIcon(getElementByName(classNode, EL_ICON).getTextContent());

    // parse all variables declared in the corresponding specification
    if (newClass.getComponentType().hasSpec()) {
      final String newClassName = newClass.getName();
      try {
        switch (RuntimeProperties.getSpecParserKind()) {
          case REGEXP:
            {
              ClassList classList = new ClassList();
              SpecParser.parseSpecClass(newClassName, getWorkingDir(), classList);
              newClass.setSpecFields(classList.getType(newClassName).getFields());
              break;
            }
          case ANTLR:
            {
              if (specificationLoader == null) {
                specificationLoader =
                    new SpecificationLoader(new PackageSpecSourceProvider(_package), null);
              }
              final AnnotatedClass annotatedClass =
                  specificationLoader.getSpecification(newClassName);
              newClass.setSpecFields(annotatedClass.getFields());
              break;
            }
          default:
            throw new IllegalStateException("Undefined specification language parser");
        }
      } catch (SpecParseException e) {
        final String msg = "Unable to parse the specification of class " + newClassName;
        logger.error(msg, e);
        collector.collectDiagnostic(msg + "\nReason: " + e.getMessage() + "\nLine: " + e.getLine());
      }
    }

    // Graphics
    Element grNode = getElementByName(classNode, EL_GRAPHICS);
    newClass.addGraphics(
        getGraphicsParser().parse(grNode/*, newClass.getComponentType() == ComponentType.REL*/ ));

    Element painter;
    if ((painter = getElementByName(grNode, EL_PAINTER)) != null) {
      newClass.setPainterName(painter.getTextContent());
    }

    // Ports
    NodeList ports = classNode.getElementsByTagName(EL_PORT);
    for (int i = 0; i < ports.getLength(); i++) {
      parsePort(newClass, (Element) ports.item(i));
    }

    // Fields
    NodeList fields = classNode.getElementsByTagName(EL_FIELD);
    for (int i = 0; i < fields.getLength(); i++) {
      parseField(newClass, (Element) fields.item(i));
    }

    return newClass;
  }