Example usage for javax.swing.text Element getParentElement

List of usage examples for javax.swing.text Element getParentElement

Introduction

In this page you can find the example usage for javax.swing.text Element getParentElement.

Prototype

public Element getParentElement();

Source Link

Document

Fetches the parent element.

Usage

From source file:Main.java

public static boolean containsAttribute(Element element, Object name, Object value) {
    if (element == null) {
        return false;
    }//from  www  .  j av  a  2s . co  m

    Object attribute = element.getAttributes().getAttribute(name);

    if (attribute == null) {
        return containsAttribute(element.getParentElement(), name, value);
    }
    return value.equals(attribute.toString());
}

From source file:com.hexidec.ekit.component.HTMLUtilities.java

public Element getListItemParent() {
    String listItemTag = HTML.Tag.LI.toString();
    Element eleSearch = parent.getExtendedHtmlDoc().getCharacterElement(parent.getCaretPosition());
    do {/*from  w  w w  . ja va2 s  . c om*/
        if (listItemTag.equals(eleSearch.getName())) {
            return eleSearch;
        }
        eleSearch = eleSearch.getParentElement();
    } while (eleSearch.getName() != HTML.Tag.HTML.toString());
    return null;
}

From source file:com.hexidec.ekit.component.HTMLUtilities.java

public boolean checkParentsTag(HTML.Tag tag) {
    Element e = parent.getExtendedHtmlDoc().getParagraphElement(parent.getCaretPosition());
    String tagString = tag.toString();
    if (e.getName().equalsIgnoreCase(tag.toString())) {
        return true;
    }//from www  . j  a  v  a  2s.co m
    do {
        if ((e = e.getParentElement()).getName().equalsIgnoreCase(tagString)) {
            return true;
        }
    } while (!(e.getName().equalsIgnoreCase("html")));
    return false;
}

From source file:com.hexidec.ekit.component.HTMLUtilities.java

public Element getListItemContainer() {
    String listUnorderedTag = HTML.Tag.UL.toString();
    String listOrderedTag = HTML.Tag.OL.toString();
    Element eleSearch = parent.getExtendedHtmlDoc().getCharacterElement(parent.getCaretPosition());
    do {/*from w ww  . ja  v a 2 s  .c  o  m*/
        if (listUnorderedTag.equals(eleSearch.getName()) || listOrderedTag.equals(eleSearch.getName())) {
            return eleSearch;
        }
        eleSearch = eleSearch.getParentElement();
    } while (eleSearch != null && eleSearch.getName() != HTML.Tag.HTML.toString());
    return null;
}

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);// www .ja  v a  2 s. c om

    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: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  ww. ja  v  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:com.hexidec.ekit.EkitCore.java

/**
 * Method for inserting list elements//  w  w  w .j av  a 2s.c o  m
 */
public void insertListStyle(Element element) throws BadLocationException, IOException {
    if (element.getParentElement().getName() == "ol") {
        actionListOrdered.actionPerformed(new ActionEvent(new Object(), 0, "newListPoint"));
    } else {
        actionListUnordered.actionPerformed(new ActionEvent(new Object(), 0, "newListPoint"));
    }
}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Method that handles initial list insertion and deletion
 *//*from www.  j  av  a2 s . com*/
public void removeEmptyListElement(Element element) {
    Element h = htmlUtilities.getListItemParent();
    Element listPar = h.getParentElement();
    if (h != null) {
        htmlUtilities.removeTag(h, true);
        removeEmptyLists();
        refreshOnUpdate();
    }
}

From source file:com.hexidec.ekit.EkitCore.java

private void moveCaretOnTable(Element tdElement, boolean up, boolean selecting) {

    int caretPos = jtpMain.getCaretPosition();

    Element rowElement = tdElement.getParentElement();
    Element tableElement = rowElement.getParentElement();

    int rowIndex = DocumentUtil.getIndexInParent(rowElement);
    if (up) {//from  w w w  .ja v  a 2  s. c o  m
        if (rowIndex == 0) {
            moveCaret(Math.max(tableElement.getStartOffset() - 1, 0), selecting);
        } else {
            rowElement = tableElement.getElement(rowIndex - 1);
            int posInCell = caretPos - tdElement.getStartOffset();
            int colIndex = DocumentUtil.getIndexInParent(tdElement);
            tdElement = rowElement.getElement(colIndex);
            moveCaret(
                    tdElement.getStartOffset()
                            + Math.min(posInCell, tdElement.getEndOffset() - tdElement.getStartOffset() - 1),
                    selecting);
        }
    } else { // down
        if (rowIndex >= tableElement.getElementCount() - 1) {
            moveCaret(Math.min(tableElement.getEndOffset(), htmlDoc.getLength() - 1), selecting);
        } else {
            rowElement = tableElement.getElement(rowIndex + 1);
            int posInCell = caretPos - tdElement.getStartOffset();
            int colIndex = DocumentUtil.getIndexInParent(tdElement);
            tdElement = rowElement.getElement(colIndex);
            moveCaret(
                    tdElement.getStartOffset()
                            + Math.min(posInCell, tdElement.getEndOffset() - tdElement.getStartOffset() - 1),
                    selecting);
        }
    }

}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Handles caret tracking and related events, such as displaying the current
 * style of the text under the caret//  w w w.  ja v a  2 s . c  o  m
 */
private void handleCaretPositionChange(CaretEvent ce) {
    int caretPos = ce.getDot();
    Element element = htmlDoc.getCharacterElement(caretPos);
    /*
     * //---- TAG EXPLICATOR CODE
     * -------------------------------------------
     * javax.swing.text.ElementIterator ei = new
     * javax.swing.text.ElementIterator(htmlDoc); Element ele; while((ele =
     * ei.next()) != null) { log.debug("ELEMENT : " + ele.getName()); }
     * log.debug("ELEMENT:" + element.getName()); Element elementParent =
     * element.getParentElement(); log.debug("ATTRS:"); AttributeSet attribs
     * = elementParent.getAttributes(); for(Enumeration eAttrs =
     * attribs.getAttributeNames(); eAttrs.hasMoreElements();) {
     * log.debug("  " + eAttrs.nextElement().toString()); }
     * while(elementParent != null &&
     * !elementParent.getName().equals("body")) { String parentName =
     * elementParent.getName(); log.debug("PARENT:" + parentName);
     * log.debug("ATTRS:"); attribs = elementParent.getAttributes();
     * for(Enumeration eAttr = attribs.getAttributeNames();
     * eAttr.hasMoreElements();) { log.debug("  " +
     * eAttr.nextElement().toString()); } elementParent =
     * elementParent.getParentElement(); } //---- END
     * -------------------------------------------
     */
    if (jtpMain.hasFocus()) {
        if (element == null) {
            return;
        }
        String style = null;
        Vector<Element> vcStyles = new Vector<Element>();
        while (element != null) {
            if (style == null) {
                style = findStyle(element);
            }
            vcStyles.add(element);
            element = element.getParentElement();
        }
        int stylefound = -1;
        if (style != null) {
            for (int i = 0; i < jcmbStyleSelector.getItemCount(); i++) {
                String in = (String) (jcmbStyleSelector.getItemAt(i));
                if (in.equalsIgnoreCase(style)) {
                    stylefound = i;
                    break;
                }
            }
        }
        if (stylefound > -1) {
            jcmbStyleSelector.getAction().setEnabled(false);
            jcmbStyleSelector.setSelectedIndex(stylefound);
            jcmbStyleSelector.getAction().setEnabled(true);
        } else {
            jcmbStyleSelector.setSelectedIndex(0);
        }
        // see if current font face is set
        if (jcmbFontSelector != null && jcmbFontSelector.isVisible()) {
            AttributeSet mainAttrs = jtpMain.getCharacterAttributes();
            Enumeration e = mainAttrs.getAttributeNames();
            Object activeFontName = (Object) (Translatrix.getTranslationString("SelectorToolFontsDefaultFont"));
            while (e.hasMoreElements()) {
                Object nexte = e.nextElement();
                if (nexte.toString().toLowerCase().equals("face")
                        || nexte.toString().toLowerCase().equals("font-family")) {
                    activeFontName = mainAttrs.getAttribute(nexte);
                    break;
                }
            }
            jcmbFontSelector.getAction().setEnabled(false);
            jcmbFontSelector.getModel().setSelectedItem(activeFontName);
            jcmbFontSelector.getAction().setEnabled(true);
        }
    }
}