private void updateTemplateFromEditor(PrintfTemplate template) { ArrayList params = new ArrayList(); String format = null; int text_length = editorPane.getDocument().getLength(); try { format = editorPane.getDocument().getText(0, text_length); } catch (BadLocationException ex1) { } Element section_el = editorPane.getDocument().getDefaultRootElement(); // Get number of paragraphs. int num_para = section_el.getElementCount(); for (int p_count = 0; p_count < num_para; p_count++) { Element para_el = section_el.getElement(p_count); // Enumerate the content elements int num_cont = para_el.getElementCount(); for (int c_count = 0; c_count < num_cont; c_count++) { Element content_el = para_el.getElement(c_count); AttributeSet attr = content_el.getAttributes(); // Get the name of the style applied to this content element; may be null String sn = (String) attr.getAttribute(StyleConstants.NameAttribute); // Check if style name match if (sn != null && sn.startsWith("Parameter")) { // we extract the label. JLabel l = (JLabel) StyleConstants.getComponent(attr); if (l != null) { params.add(l.getName()); } } } } template.setFormat(format); template.setTokens(params); }
/** * Highlight lines to start or end delimiter. * * @param content the content to parse * @param line the line number * @throws BadLocationException if offsets are wrong */ protected void highlightLinesAfter(String content, int line) throws BadLocationException { int offset = m_RootElement.getElement(line).getEndOffset(); // Start/End delimiter not found, nothing to do int startDelimiter = -1; int endDelimiter = -1; if (getMultiLineComment()) { startDelimiter = indexOf(content, getMultiLineCommentStart(), offset); endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset); } if (startDelimiter < 0) startDelimiter = content.length(); if (endDelimiter < 0) endDelimiter = content.length(); int delimiter = Math.min(startDelimiter, endDelimiter); if (delimiter < offset) return; // Start/End delimiter found, reapply highlighting int endLine = m_RootElement.getElementIndex(delimiter); for (int i = line + 1; i < endLine; i++) { Element branch = m_RootElement.getElement(i); Element leaf = m_Self.getCharacterElement(branch.getStartOffset()); AttributeSet as = leaf.getAttributes(); if (as.isEqual(DEFAULT_COMMENT)) applyHighlighting(content, i); } }
@Override public void mouseClicked(MouseEvent me) { Element el = doc.getCharacterElement(viewToModel(me.getPoint())); if (el == null) return; AttributeSet as = el.getAttributes(); if (as.isDefined("ip")) { String ip = (String) as.getAttribute("ip"); ScriptException se = (ScriptException) as.getAttribute("exception"); Node node = net.getAtIP(ip); if (node == null) { Utility.displayError("Error", "Computer does not exist"); return; } String errorString = "--ERROR--\n" + "Error at line number " + se.getLineNumber() + " and column number " + se.getColumnNumber() + "\n" + se.getMessage(); new ScriptDialog( parentFrame, str -> { if (str != null) { node.setScript(str); } }, node.getScript(), errorString) .setVisible(true); } }
/** * Performs layout for the minor axis of the box (i.e. the axis orthogonal to the axis that it * represents). The results of the layout (the offset and span for each children) are placed in * the given arrays which represent the allocations to the children along the minor axis. * * @param targetSpan the total span given to the view, which would be used to layout the children. * @param axis the axis being layed out * @param offsets the offsets from the origin of the view for each of the child views; this is a * return value and is filled in by the implementation of this method * @param spans the span of each child view; this is a return value and is filled in by the * implementation of this method */ protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) { int n = getViewCount(); Object key = (axis == X_AXIS) ? CSS.Attribute.WIDTH : CSS.Attribute.HEIGHT; for (int i = 0; i < n; i++) { View v = getView(i); int min = (int) v.getMinimumSpan(axis); int max; // check for percentage span AttributeSet a = v.getAttributes(); CSS.LengthValue lv = (CSS.LengthValue) a.getAttribute(key); if ((lv != null) && lv.isPercentage()) { // bound the span to the percentage specified min = Math.max((int) lv.getValue(targetSpan), min); max = min; } else { max = (int) v.getMaximumSpan(axis); } // assign the offset and span for the child if (max < targetSpan) { // can't make the child this wide, align it float align = v.getAlignment(axis); offsets[i] = (int) ((targetSpan - max) * align); spans[i] = max; } else { // make it the target width, or as small as it can get. offsets[i] = 0; spans[i] = Math.max(min, targetSpan); } } }
/** * Searches for embedded tags in the AttributeSet and writes them out. It also stores these tags * in a vector so that when appropriate the corresponding end tags can be written out. * * @exception IOException on any I/O error */ protected void writeEmbeddedTags(AttributeSet attr) throws IOException { // translate css attributes to html attr = convertToHTML(attr, oConvAttr); Enumeration names = attr.getAttributeNames(); while (names.hasMoreElements()) { Object name = names.nextElement(); if (name instanceof HTML.Tag) { HTML.Tag tag = (HTML.Tag) name; if (tag == HTML.Tag.FORM || tags.contains(tag)) { continue; } write('<'); write(tag.toString()); Object o = attr.getAttribute(tag); if (o != null && o instanceof AttributeSet) { writeAttributes((AttributeSet) o); } write('>'); tags.addElement(tag); tagValues.addElement(o); } } }
public void scrollToReference(final String ref) { Document doc = getDocument(); if (ref == null || !(doc instanceof HTMLDocument)) { return; } HTMLDocument.Iterator it = ((HTMLDocument) doc).getIterator(HTML.Tag.A); int offset = 0; while (it.isValid()) { AttributeSet set = it.getAttributes(); Object name = set.getAttribute(HTML.Attribute.NAME); if (ref.equals(name)) { offset = it.getStartOffset(); break; } it.next(); } Rectangle rect = null; try { rect = modelToView(offset); } catch (BadLocationException e) { } Rectangle visibleRect = getVisibleRect(); if (visibleRect != null) { rect.height = visibleRect.height; } scrollRectToVisible(rect); }
/** Is this image within a link? */ boolean isLink() { // ! It would be nice to cache this but in an editor it can change // See if I have an HREF attribute courtesy of the enclosing A tag: AttributeSet anchorAttr = (AttributeSet) fElement.getAttributes().getAttribute(HTML.Tag.A); if (anchorAttr != null) { return anchorAttr.isDefined(HTML.Attribute.HREF); } return false; }
@Override public void mouseMoved(MouseEvent me) { Element el = doc.getCharacterElement(viewToModel(me.getPoint())); if (el == null) return; AttributeSet as = el.getAttributes(); if (as.isDefined("ip")) { setCursor(handCursor); } else { setCursor(defaultCursor); } }
/** * Writes out comments. * * @param elem an Element * @exception IOException on any I/O error * @exception BadLocationException if pos represents an invalid location within the document. */ protected void comment(Element elem) throws BadLocationException, IOException { AttributeSet as = elem.getAttributes(); if (matchNameAttribute(as, HTML.Tag.COMMENT)) { Object comment = as.getAttribute(HTML.Attribute.COMMENT); if (comment instanceof String) { writeComment((String) comment); } else { writeComment(null); } } }
/** * Checks whether the hyperlink event originated on a <a ...> element with a relative href * consisting of a URL fragment only, i.e. <a href="#thisIsALocalFragment">. If so, * replies the fragment, i.e. "thisIsALocalFragment". * * <p>Otherwise, replies <code>null</code> * * @param e the hyperlink event * @return the local fragment or <code>null</code> */ protected String getUrlFragment(HyperlinkEvent e) { AttributeSet set = e.getSourceElement().getAttributes(); Object value = set.getAttribute(Tag.A); if (!(value instanceof SimpleAttributeSet)) return null; SimpleAttributeSet atts = (SimpleAttributeSet) value; value = atts.getAttribute(javax.swing.text.html.HTML.Attribute.HREF); if (value == null) return null; String s = (String) value; if (s.matches("#.*")) return s.substring(1); return null; }
/** * Searches the attribute set for a tag, both of which are passed in as a parameter. Returns true * if no match is found and false otherwise. */ private boolean noMatchForTagInAttributes(AttributeSet attr, HTML.Tag t, Object tagValue) { if (attr != null && attr.isDefined(t)) { Object newValue = attr.getAttribute(t); if ((tagValue == null) ? (newValue == null) : (newValue != null && tagValue.equals(newValue))) { return false; } } return true; }
/** * {@inheritDoc} * * @see JTextComponent#getToolTipText(MouseEvent) */ @SuppressWarnings("unchecked") @Override public final String getToolTipText(MouseEvent event) { int index = viewToModel(event.getPoint()); if (index < getDocument().getLength()) { StyledParserDocument<E> document = (StyledParserDocument) getDocument(); AttributeSet set = document.getCharacterElement(index).getAttributes(); Object exception = set.getAttribute("exception"); // $NON-NLS-1$ if (exception != null && exception instanceof Exception) { return ((Exception) exception).getMessage(); } } return super.getToolTipText(event); }
/** Return the border width for the given side. */ private int getBorderWidth(int side) { int width = 0; BorderStyle bs = (BorderStyle) attrs.getAttribute(ATTRIBUTES[STYLE][side]); if ((bs != null) && (bs.getValue() != Value.NONE)) { // The 'border-style' value of "none" forces the computed value // of 'border-width' to be 0 (CSS2 8.5.3) LengthValue bw = (LengthValue) attrs.getAttribute(ATTRIBUTES[WIDTH][side]); if (bw == null) { bw = (LengthValue) DEFAULTS[WIDTH]; } width = (int) bw.getValue(true); } return width; }
/** * Copies the given AttributeSet to a new set, converting any CSS attributes found to arguments of * an HTML style attribute. */ private static void convertToHTML40(AttributeSet from, MutableAttributeSet to) { Enumeration keys = from.getAttributeNames(); String value = ""; while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof CSS.Attribute) { value = value + " " + key + "=" + from.getAttribute(key) + ";"; } else { to.addAttribute(key, from.getAttribute(key)); } } if (value.length() > 0) { to.addAttribute(HTML.Attribute.STYLE, value); } }
/** Look up an integer-valued attribute. <b>Not</b> recursive. */ private int getIntAttr(HTML.Attribute name, int deflt) { AttributeSet attr = fElement.getAttributes(); if (attr.isDefined(name)) { // does not check parents! int i; String val = (String) attr.getAttribute(name); if (val == null) i = deflt; else try { i = Math.max(0, Integer.parseInt(val)); } catch (NumberFormatException x) { i = deflt; } return i; } else return deflt; }
private void displayElements(Element el, int level) { for (int x = 0; x < level; x++) System.err.print("-"); System.err.println(); System.err.println("Element name " + el.getName()); AttributeSet attrSet = el.getAttributes(); Enumeration enumAttr = attrSet.getAttributeNames(); while (enumAttr != null && enumAttr.hasMoreElements()) { System.err.println(" attr value " + enumAttr.nextElement().toString()); } int childElemCt = el.getElementCount(); for (int ix = 0; ix < childElemCt; ix++) { Element el1 = el.getElement(ix); displayElements(el1, ++level); } }
@Override public void mouseMoved(MouseEvent event) { JTextPane textPane = (JTextPane) event.getSource(); Point point = new Point(event.getX(), event.getY()); int position = textPane.viewToModel(point); DefaultStyledDocument document = (DefaultStyledDocument) textPane.getDocument(); Element element = document.getCharacterElement(position); AttributeSet attributeSet = element.getAttributes(); String sLink = (String) attributeSet.getAttribute("link"); if (sLink != null) { textPane.setCursor(handCursor); } else { textPane.setCursor(textCursor); } }
/** Return the border color for the given side. */ private Color getBorderColor(int side) { Object o = attrs.getAttribute(ATTRIBUTES[COLOR][side]); ColorValue cv; if (o instanceof ColorValue) { cv = (ColorValue) o; } else { // Marker for the default value. Use 'color' property value as the // computed value of the 'border-color' property (CSS2 8.5.2) cv = (ColorValue) attrs.getAttribute(Attribute.COLOR); if (cv == null) { cv = (ColorValue) PARSERS[COLOR].parseCssValue(Attribute.COLOR.getDefaultValue()); } } return cv.getValue(); }
/** @param formatter */ protected void setFormatterFromTextPane(final DataObjSwitchFormatter formatter) { // visit every character in the document text looking for fields // store characters not associated with components (jbutton) to make up the separator text DefaultStyledDocument doc = (DefaultStyledDocument) formatEditor.getStyledDocument(); String text = formatEditor.getText(); int docLen = doc.getLength(); int lastFieldPos = 0; Vector<DataObjDataField> fields = new Vector<DataObjDataField>(); // int cnt = 0; for (int i = 0; i < docLen; ++i) { Element element = doc.getCharacterElement(i); AttributeSet attrs = element.getAttributes(); Object obj = attrs.getAttribute(StyleConstants.ComponentAttribute); // System.out.print(String.format("i: %d, lastFieldPos: %d cnt: %d, F: %s", i, lastFieldPos, // cnt, (obj instanceof FieldDefinitionComp ? "Y" : "N"))); if (obj instanceof FieldDefinitionComp) { // System.out.println(cnt+" "+(obj instanceof FieldDefinitionComp)); // found button at the current position // create corresponding field String sepStr = (lastFieldPos <= i - 1) ? text.substring(lastFieldPos, i) : ""; FieldDefinitionComp fieldDefBtn = (FieldDefinitionComp) obj; DataObjDataField fmtField = fieldDefBtn.getValue(); fmtField.setSep(sepStr); fields.add(fmtField); // System.out.print(" Sep: ["+sepStr+"]"); lastFieldPos = i + 1; // cnt++; } } // XXX: what do we do with the remaining of the text? right now we ignore it // That's because we can't create an empty formatter field just to use the separator... DataObjDataField[] fieldsArray = new DataObjDataField[fields.size()]; for (int i = 0; i < fields.size(); ++i) { fieldsArray[i] = fields.elementAt(i); } DataObjDataFieldFormat singleFormatter = fieldsArray.length == 0 ? null : new DataObjDataFieldFormat("", tableInfo.getClassObj(), false, "", "", fieldsArray); formatter.setSingle(singleFormatter); }
private Element getChildElementByTagName( Element element, HTML.Tag searchTag, Map<String, String> searchAtrib) { int count = element.getElementCount(); for (int i = 0; i < count; i++) { Element childElem = element.getElement(i); AttributeSet attributes = childElem.getAttributes(); Object obj = attributes.getAttribute(StyleConstants.NameAttribute); if ((obj instanceof HTML.Tag) && ((obj == searchTag))) if (searchAtrib != null) { if (isElementAtribOk(childElem, searchAtrib)) return childElem; } else { return childElem; } } return null; }
/** * Creates and returns an instance of RegionContainment that can be used to test if a particular * point lies inside a region. */ protected RegionContainment createRegionContainment(AttributeSet attributes) { Object shape = attributes.getAttribute(HTML.Attribute.SHAPE); if (shape == null) { shape = "rect"; } if (shape instanceof String) { String shapeString = ((String) shape).toLowerCase(); RegionContainment rc = null; try { if (shapeString.equals("rect")) { rc = new RectangleRegionContainment(attributes); } else if (shapeString.equals("circle")) { rc = new CircleRegionContainment(attributes); } else if (shapeString.equals("poly")) { rc = new PolygonRegionContainment(attributes); } else if (shapeString.equals("default")) { rc = DefaultRegionContainment.sharedInstance(); } } catch (RuntimeException re) { // Something wrong with attributes. rc = null; } return rc; } return null; }
/** Return the border style for the given side. */ private Value getBorderStyle(int side) { BorderStyle style = (BorderStyle) attrs.getAttribute(ATTRIBUTES[STYLE][side]); if (style == null) { style = (BorderStyle) DEFAULTS[STYLE]; } return style.getValue(); }
private void printAtribute(Element elem) { logger.debug("--------------------------------------------"); logger.debug("Elemn name : " + elem.getName()); AttributeSet as = elem.getAttributes(); Enumeration e = as.getAttributeNames(); while (e.hasMoreElements()) { Object key = e.nextElement(); if (key != null) { System.out.print(" atrName : " + key.toString() + " , "); Object val = as.getAttribute(key); if (val != null) System.out.print(" atrVal : " + val.toString()); logger.debug(" "); } } logger.debug("--------------------------------------------"); }
private Map<String, String> getAtributes(Element element, List<String> questionReadAtrib) { Map<String, String> foundAtrib = new HashMap<String, String>(); AttributeSet as = element.getAttributes(); Enumeration e = as.getAttributeNames(); while (e.hasMoreElements()) { Object keyObj = e.nextElement(); if (keyObj != null) { Object valObj = as.getAttribute(keyObj); if (valObj != null) if (questionReadAtrib.contains(String.valueOf(keyObj))) foundAtrib.put(String.valueOf(keyObj), String.valueOf(valObj)); } } return foundAtrib; }
private List<Element> getChildElementsByTagName( Element element, HTML.Tag searchTag, Map<String, String> searchAtrib) { int count = element.getElementCount(); List<Element> elemnts = new ArrayList<Element>(); for (int i = 0; i < count; i++) { Element childElem = element.getElement(i); AttributeSet attributes = childElem.getAttributes(); Object obj = attributes.getAttribute(StyleConstants.NameAttribute); if ((obj instanceof HTML.Tag) && ((obj == searchTag))) if (searchAtrib != null) { if (isElementAtribOk(childElem, searchAtrib)) elemnts.add(childElem); } else { elemnts.add(childElem); } } return elemnts; }
/** * Determines if the HTML.Tag associated with the element is a block tag. * * @param attr an AttributeSet * @return true if tag is block tag, false otherwise. */ protected boolean isBlockTag(AttributeSet attr) { Object o = attr.getAttribute(StyleConstants.NameAttribute); if (o instanceof HTML.Tag) { HTML.Tag name = (HTML.Tag) o; return name.isBlock(); } return false; }
/** * Asserts that the style is still set correctly on a styled document after encoding the document * into a string representation and decoding it back into a styled document again. */ public void assertStyleRoundtrip(Object style) throws BadLocationException { m_doc.insertString(0, "Foobar Test", SimpleAttributeSet.EMPTY); SimpleAttributeSet actualAttr = new SimpleAttributeSet(); actualAttr.addAttribute(style, Boolean.TRUE); m_doc.setCharacterAttributes(2, 2, actualAttr, true); StyledDocument doc = roundtrip(m_doc); AttributeSet exceptedAttr = doc.getCharacterElement(2).getAttributes(); Boolean hasStyle = (Boolean) exceptedAttr.getAttribute(style); if (hasStyle != null) { assertTrue(hasStyle.booleanValue()); } else { fail("Style not set"); } }
/** @return */ public int findFieldButtonPosition() { DefaultStyledDocument doc = (DefaultStyledDocument) formatEditor.getStyledDocument(); int i, n = doc.getLength(); Object obj = null; for (i = 0; i < n; ++i) { Element element = doc.getCharacterElement(i); AttributeSet attrs = element.getAttributes(); obj = attrs.getAttribute(StyleConstants.ComponentAttribute); if (obj == this) { // found button at this position return i; } } // this should never happen because the button clicked must be inside text pane throw new RuntimeException("Button representing field in text pane was not found."); }
void editorPane_keyPressed(KeyEvent e) { StyledDocument doc = editorPane.getStyledDocument(); int pos = editorPane.getCaretPosition(); int code = e.getKeyCode(); Element el; switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: if (pos == 0) return; // we want to get the element to the left of position. el = doc.getCharacterElement(pos - 1); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: // we want to get the element to the right of position. el = doc.getCharacterElement(pos + 1); break; default: return; // bail we don't handle it. } AttributeSet attr = el.getAttributes(); String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute); int el_range = el.getEndOffset() - el.getStartOffset() - 1; if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) { try { switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: doc.remove(el.getStartOffset(), el_range); break; case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: editorPane.setCaretPosition(pos - el_range); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: editorPane.setCaretPosition(pos + (el_range)); break; } } catch (BadLocationException ex) { } } }
/** Defines a region of the Map, based on the passed in AttributeSet. */ public void addArea(AttributeSet as) { if (as == null) { return; } if (areaAttributes == null) { areaAttributes = new Vector<AttributeSet>(2); } areaAttributes.addElement(as.copyAttributes()); }