List of usage examples for javax.swing.text Element getAttributes
public AttributeSet getAttributes();
From source file:com.hexidec.ekit.component.HTMLUtilities.java
/** Diese Methode fgt durch String-Manipulation in jtpSource * ein neues Listenelement hinzu, content ist dabei der Text der in dem neuen * Element stehen soll/* ww w . j ava2s . com*/ */ public void insertListElement(String content) { int pos = parent.getCaretPosition(); String source = parent.getSourcePane().getText(); boolean hit = false; String idString; int counter = 0; do { hit = false; idString = "diesisteineidzumsuchenimsource" + counter; if (source.indexOf(idString) > -1) { counter++; hit = true; if (counter > 10000) { return; } } } while (hit); Element element = getListItemParent(); if (element == null) { return; } SimpleAttributeSet sa = new SimpleAttributeSet(element.getAttributes()); sa.addAttribute("id", idString); parent.getExtendedHtmlDoc().replaceAttributes(element, sa, HTML.Tag.LI); parent.refreshOnUpdate(); source = parent.getSourcePane().getText(); StringBuffer newHtmlString = new StringBuffer(); int[] positions = getPositions(element, source, true, idString); newHtmlString.append(source.substring(0, positions[3])); newHtmlString.append("<li>"); newHtmlString.append(content); newHtmlString.append("</li>"); newHtmlString.append(source.substring(positions[3] + 1, source.length())); parent.getTextPane().setText(newHtmlString.toString()); parent.refreshOnUpdate(); parent.setCaretPosition(pos - 1); element = getListItemParent(); if (element != null) { sa = new SimpleAttributeSet(element.getAttributes()); sa = removeAttributeByKey(sa, "id"); parent.getExtendedHtmlDoc().replaceAttributes(element, sa, HTML.Tag.LI); } }
From source file:EditorPaneExample16.java
public URL[] findLinks(Document doc, String protocol) { Vector links = new Vector(); Vector urlNames = new Vector(); URL baseURL = (URL) doc.getProperty(Document.StreamDescriptionProperty); if (doc instanceof HTMLDocument) { Element elem = doc.getDefaultRootElement(); ElementIterator iterator = new ElementIterator(elem); while ((elem = iterator.next()) != null) { AttributeSet attrs = elem.getAttributes(); Object link = attrs.getAttribute(HTML.Tag.A); if (link instanceof AttributeSet) { Object linkAttr = ((AttributeSet) link).getAttribute(HTML.Attribute.HREF); if (linkAttr instanceof String) { try { URL linkURL = new URL(baseURL, (String) linkAttr); if (protocol == null || protocol.equalsIgnoreCase(linkURL.getProtocol())) { String linkURLName = linkURL.toString(); if (urlNames.contains(linkURLName) == false) { urlNames.addElement(linkURLName); links.addElement(linkURL); }/*from ww w .java 2 s . c o m*/ } } catch (MalformedURLException e) { // Ignore invalid links } } } } } URL[] urls = new URL[links.size()]; links.copyInto(urls); links.removeAllElements(); urlNames.removeAllElements(); return urls; }
From source file:com.hexidec.ekit.component.ExtendedHTMLDocument.java
public void replaceAttributes(Element e, AttributeSet a, Tag tag) { if ((e != null) && (a != null)) { try {/*w w w .ja v a2s. c o m*/ writeLock(); int start = e.getStartOffset(); DefaultDocumentEvent changes = new DefaultDocumentEvent(start, e.getEndOffset() - start, DocumentEvent.EventType.CHANGE); AttributeSet sCopy = a.copyAttributes(); changes.addEdit(new AttributeUndoableEdit(e, sCopy, false)); MutableAttributeSet attr = (MutableAttributeSet) e.getAttributes(); Enumeration aNames = attr.getAttributeNames(); Object value; Object aName; while (aNames.hasMoreElements()) { aName = aNames.nextElement(); value = attr.getAttribute(aName); if (value != null && !value.toString().equalsIgnoreCase(tag.toString())) { attr.removeAttribute(aName); } } attr.addAttributes(a); changes.end(); fireChangedUpdate(changes); fireUndoableEditUpdate(new UndoableEditEvent(this, changes)); } finally { writeUnlock(); } } }
From source file:com.hexidec.ekit.action.ListAutomationAction.java
private void revertList(Element element) { //log.debug("Reverting list " + element.toString()); if (element == null) { return;/*from w ww .j a v a 2s .c om*/ } int pos = parentEkit.getCaretPosition(); HTML.Tag tag = htmlUtilities.getHTMLTag(element); String source = parentEkit.getSourcePane().getText(); boolean hit = false; String idString; int counter = 0; do { hit = false; idString = "revertomatictaggen" + counter; if (source.indexOf(idString) > -1) { counter++; hit = true; if (counter > 10000) { return; } } } while (hit); SimpleAttributeSet sa = new SimpleAttributeSet(element.getAttributes()); sa.addAttribute("id", idString); parentEkit.getExtendedHtmlDoc().replaceAttributes(element, sa, tag); parentEkit.refreshOnUpdate(); source = parentEkit.getSourcePane().getText(); StringBuffer newHtmlString = new StringBuffer(); int[] position = htmlUtilities.getPositions(element, source, true, idString); if (position == null) { return; } for (int i = 0; i < position.length; i++) { if (position[i] < 0) { return; } } int beginStartTag = position[0]; int endStartTag = position[1]; int beginEndTag = position[2]; int endEndTag = position[3]; newHtmlString.append(source.substring(0, beginStartTag)); String listText = source.substring(endStartTag, beginEndTag); //log.debug("Affected text is :" + listText); if (parentEkit.getEnterKeyIsBreak()) { listText = listText.replaceAll("<li>", ""); listText = listText.replaceAll("</li>", "<br/>"); newHtmlString.append("<br/>" + listText); } else { listText = listText.replaceAll("<li>", "<p style=\"margin-top: 0\">"); listText = listText.replaceAll("</li>", "</p>"); newHtmlString.append(listText); } //log.debug("Updated text is :" + listText); newHtmlString.append(source.substring(endEndTag, source.length())); parentEkit.getTextPane().setText(newHtmlString.toString()); parentEkit.refreshOnUpdate(); }
From source file:net.sf.jasperreports.engine.util.JEditorPaneHtmlMarkupProcessor.java
@Override public String convert(String srcText) { JEditorPane editorPane = new JEditorPane("text/html", srcText); editorPane.setEditable(false);/*from ww w . j av a2 s. c o m*/ List<Element> elements = new ArrayList<Element>(); Document document = editorPane.getDocument(); Element root = document.getDefaultRootElement(); if (root != null) { addElements(elements, root); } int startOffset = 0; int endOffset = 0; int crtOffset = 0; String chunk = null; JRPrintHyperlink hyperlink = null; Element element = null; Element parent = null; boolean bodyOccurred = false; int[] orderedListIndex = new int[elements.size()]; String whitespace = " "; String[] whitespaces = new String[elements.size()]; for (int i = 0; i < elements.size(); i++) { whitespaces[i] = ""; } StringBuilder text = new StringBuilder(); List<JRStyledText.Run> styleRuns = new ArrayList<>(); for (int i = 0; i < elements.size(); i++) { if (bodyOccurred && chunk != null) { text.append(chunk); Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes()); if (hyperlink != null) { styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink); hyperlink = null; } if (!styleAttributes.isEmpty()) { styleRuns.add( new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset)); } } chunk = null; element = elements.get(i); parent = element.getParentElement(); startOffset = element.getStartOffset(); endOffset = element.getEndOffset(); AttributeSet attrs = element.getAttributes(); Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute); Object object = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute); if (object instanceof HTML.Tag) { HTML.Tag htmlTag = (HTML.Tag) object; if (htmlTag == Tag.BODY) { bodyOccurred = true; crtOffset = -startOffset; } else if (htmlTag == Tag.BR) { chunk = "\n"; } else if (htmlTag == Tag.OL) { orderedListIndex[i] = 0; String parentName = parent.getName().toLowerCase(); whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace; if (parentName.equals("li")) { chunk = ""; } else { chunk = "\n"; ++crtOffset; } } else if (htmlTag == Tag.UL) { whitespaces[i] = whitespaces[elements.indexOf(parent)] + whitespace; String parentName = parent.getName().toLowerCase(); if (parentName.equals("li")) { chunk = ""; } else { chunk = "\n"; ++crtOffset; } } else if (htmlTag == Tag.LI) { whitespaces[i] = whitespaces[elements.indexOf(parent)]; if (element.getElement(0) != null && (element.getElement(0).getName().toLowerCase().equals("ol") || element.getElement(0).getName().toLowerCase().equals("ul"))) { chunk = ""; } else if (parent.getName().equals("ol")) { int index = elements.indexOf(parent); Object type = parent.getAttributes().getAttribute(HTML.Attribute.TYPE); Object startObject = parent.getAttributes().getAttribute(HTML.Attribute.START); int start = startObject == null ? 0 : Math.max(0, Integer.valueOf(startObject.toString()) - 1); String suffix = ""; ++orderedListIndex[index]; if (type != null) { switch (((String) type).charAt(0)) { case 'A': suffix = getOLBulletChars(orderedListIndex[index] + start, true); break; case 'a': suffix = getOLBulletChars(orderedListIndex[index] + start, false); break; case 'I': suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, true); break; case 'i': suffix = JRStringUtil.getRomanNumeral(orderedListIndex[index] + start, false); break; case '1': default: suffix = String.valueOf(orderedListIndex[index] + start); break; } } else { suffix += orderedListIndex[index] + start; } chunk = whitespaces[index] + suffix + DEFAULT_BULLET_SEPARATOR + " "; } else { chunk = whitespaces[elements.indexOf(parent)] + DEFAULT_BULLET_CHARACTER + " "; } crtOffset += chunk.length(); } else if (element instanceof LeafElement) { if (element instanceof RunElement) { RunElement runElement = (RunElement) element; AttributeSet attrSet = (AttributeSet) runElement.getAttribute(Tag.A); if (attrSet != null) { hyperlink = new JRBasePrintHyperlink(); hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE); hyperlink.setHyperlinkReference((String) attrSet.getAttribute(HTML.Attribute.HREF)); hyperlink.setLinkTarget((String) attrSet.getAttribute(HTML.Attribute.TARGET)); } } try { chunk = document.getText(startOffset, endOffset - startOffset); } catch (BadLocationException e) { if (log.isDebugEnabled()) { log.debug("Error converting markup.", e); } } } } } if (chunk != null) { if (!"\n".equals(chunk)) { text.append(chunk); Map<Attribute, Object> styleAttributes = getAttributes(element.getAttributes()); if (hyperlink != null) { styleAttributes.put(JRTextAttribute.HYPERLINK, hyperlink); hyperlink = null; } if (!styleAttributes.isEmpty()) { styleRuns.add( new JRStyledText.Run(styleAttributes, startOffset + crtOffset, endOffset + crtOffset)); } } else { //final newline, not appending //check if there's any style run that would have covered it, that can happen if there's a <li> tag with style int length = text.length(); for (ListIterator<JRStyledText.Run> it = styleRuns.listIterator(); it.hasNext();) { JRStyledText.Run run = it.next(); //only looking at runs that end at the position where the newline should have been //we don't want to hide bugs in which runs that span after the text length are created if (run.endIndex == length + 1) { if (run.startIndex < run.endIndex - 1) { it.set(new JRStyledText.Run(run.attributes, run.startIndex, run.endIndex - 1)); } else { it.remove(); } } } } } JRStyledText styledText = new JRStyledText(null, text.toString()); for (JRStyledText.Run run : styleRuns) { styledText.addRun(run); } styledText.setGlobalAttributes(new HashMap<Attribute, Object>()); return JRStyledTextParser.getInstance().write(styledText); }
From source file:com.hexidec.ekit.component.RelativeImageView.java
private void initialize(Element elem) { synchronized (this) { bLoading = true;//from w w w. j av a 2 s .c o m fWidth = 0; fHeight = 0; } int width = 0; int height = 0; boolean customWidth = false; boolean customHeight = false; try { fElement = elem; // request image from document's cache AttributeSet attr = elem.getAttributes(); if (isURL()) { URL src = getSourceURL(); if (src != null) { Dictionary cache = (Dictionary) getDocument().getProperty(IMAGE_CACHE_PROPERTY); if (cache != null) { fImage = (Image) cache.get(src); } else { fImage = Toolkit.getDefaultToolkit().getImage(src); } } } else { // load image from relative path String src = (String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC); src = processSrcPath(src); fImage = Toolkit.getDefaultToolkit().createImage(src); try { waitForImage(); } catch (InterruptedException ie) { fImage = null; // possibly replace with the ImageBroken icon, if that's what is happening } catch (Exception ex) { fImage = null; // trap a null exception or other exception that puts the image pointer into an empty or ambiguous state } } // get height & width from params or image or defaults height = getIntAttr(HTML.Attribute.HEIGHT, -1); customHeight = (height > 0); if (!customHeight && fImage != null) { height = fImage.getHeight(this); } if (height <= 0) { height = DEFAULT_HEIGHT; } width = getIntAttr(HTML.Attribute.WIDTH, -1); customWidth = (width > 0); if (!customWidth && fImage != null) { width = fImage.getWidth(this); } if (width <= 0) { width = DEFAULT_WIDTH; } if (fImage != null) { if (customHeight && customWidth) { Toolkit.getDefaultToolkit().prepareImage(fImage, height, width, this); } else { Toolkit.getDefaultToolkit().prepareImage(fImage, -1, -1, this); } } } finally { synchronized (this) { bLoading = false; if (customHeight || fHeight == 0) { fHeight = height; } if (customWidth || fWidth == 0) { fWidth = width; } } } }
From source file:com.hexidec.ekit.component.HTMLUtilities.java
/** Diese Methode lscht durch Stringmanipulation in jtpSource das bergebene Element, * Alternative fr removeElement in ExtendedHTMLDocument, mit closingTag wird angegeben * ob es ein schlieenden Tag gibt/*from w w w .j a v a 2s . c om*/ */ public void removeTag(Element element, boolean closingTag) { if (element == null) { return; } int pos = parent.getCaretPosition(); HTML.Tag tag = getHTMLTag(element); // Versieht den Tag mit einer einmaligen ID String source = parent.getSourcePane().getText(); boolean hit = false; String idString; int counter = 0; do { hit = false; idString = "diesisteineidzumsuchenimsource" + counter; if (source.indexOf(idString) > -1) { counter++; hit = true; if (counter > 10000) { return; } } } while (hit); SimpleAttributeSet sa = new SimpleAttributeSet(element.getAttributes()); sa.addAttribute("id", idString); parent.getExtendedHtmlDoc().replaceAttributes(element, sa, tag); parent.refreshOnUpdate(); source = parent.getSourcePane().getText(); StringBuffer newHtmlString = new StringBuffer(); int[] position = getPositions(element, source, closingTag, idString); if (position == null) { return; } for (int i = 0; i < position.length; i++) { if (position[i] < 0) { return; } } int beginStartTag = position[0]; int endStartTag = position[1]; if (closingTag) { int beginEndTag = position[2]; int endEndTag = position[3]; newHtmlString.append(source.substring(0, beginStartTag)); newHtmlString.append(source.substring(endStartTag, beginEndTag)); newHtmlString.append(source.substring(endEndTag, source.length())); } else { newHtmlString.append(source.substring(0, beginStartTag)); newHtmlString.append(source.substring(endStartTag, source.length())); } parent.getTextPane().setText(newHtmlString.toString()); parent.refreshOnUpdate(); }
From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java
/** * * @param element// w w w . j av a 2 s .co m * @param attrName * @param matchStrings * @return */ private Element findFirstElement(Element element, HTML.Attribute attrName, String[] matchStrings) { String attr = (String) element.getAttributes().getAttribute(attrName); if (attr != null) for (String matchString : matchStrings) if (attr.startsWith(matchString)) return element; Element resultElement = null; // Count how many messages we have in the document. for (int i = 0; i < element.getElementCount(); i++) { resultElement = findFirstElement(element.getElement(i), attrName, matchStrings); if (resultElement != null) return resultElement; } return null; }
From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java
/** * Appends a consecutive message to the document. * * @param chatMessage the message to append * @param keyword the keywords to highlight *//*from w w w. jav a 2 s . c o m*/ public void appendConsecutiveMessage(final ChatMessage chatMessage, final String keyword) { String previousMessageUID = lastMessageUID; lastMessageUID = chatMessage.getMessageUID(); if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { appendConsecutiveMessage(chatMessage, keyword); } }); return; } Element lastMsgElement = document.getElement(ChatHtmlUtils.MESSAGE_TEXT_ID + previousMessageUID); String contactAddress = (String) lastMsgElement.getAttributes().getAttribute(Attribute.NAME); boolean isHistory = (chatMessage.getMessageType().equals(Chat.HISTORY_INCOMING_MESSAGE) || chatMessage.getMessageType().equals(Chat.HISTORY_OUTGOING_MESSAGE)) ? true : false; String newMessage = ChatHtmlUtils.createMessageTag(chatMessage.getMessageUID(), contactAddress, formatMessageAsHTML(chatMessage.getMessage(), chatMessage.getContentType(), keyword), ChatHtmlUtils.HTML_CONTENT_TYPE, chatMessage.getDate(), false, isHistory, isSimpleTheme); synchronized (scrollToBottomRunnable) { try { Element parentElement = lastMsgElement.getParentElement(); document.insertBeforeEnd(parentElement, newMessage); // Need to call explicitly scrollToBottom, because for some // reason the componentResized event isn't fired every time // we add text. SwingUtilities.invokeLater(scrollToBottomRunnable); } catch (BadLocationException ex) { logger.error("Could not replace chat message", ex); } catch (IOException ex) { logger.error("Could not replace chat message", ex); } } finishMessageAdd(newMessage); }
From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java
/** * Returns the date of the last message in the current page. * * @return the date of the last message in the current page *///from ww w .j av a 2 s . co m public Date getPageLastMsgTimestamp() { Date timestamp = new Date(0); if (lastMessageUID != null) { Element lastMsgElement = document.getElement(ChatHtmlUtils.MESSAGE_TEXT_ID + lastMessageUID); if (lastMsgElement != null) { Object date = lastMsgElement.getAttributes().getAttribute(ChatHtmlUtils.DATE_ATTRIBUTE); SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT); if (date != null) { try { timestamp = sdf.parse(date.toString()); } catch (ParseException e) { } } } } return timestamp; }