Example usage for javax.swing.text Element getStartOffset

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

Introduction

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

Prototype

public int getStartOffset();

Source Link

Document

Fetches the offset from the beginning of the document that this element begins at.

Usage

From source file:net.sf.jasperreports.engine.util.JEditorPaneRtfMarkupProcessor.java

@Override
public String convert(String srcText) {
    JEditorPane editorPane = new JEditorPane("text/rtf", srcText);
    editorPane.setEditable(false);/*from w  ww  . j ava  2  s.com*/

    List<Element> elements = new ArrayList<Element>();

    Document document = editorPane.getDocument();

    Element root = document.getDefaultRootElement();
    if (root != null) {
        addElements(elements, root);
    }

    String chunk = null;
    Element element = null;
    int startOffset = 0;
    int endOffset = 0;

    JRStyledText styledText = new JRStyledText();
    styledText.setGlobalAttributes(new HashMap<Attribute, Object>());
    for (int i = 0; i < elements.size(); i++) {
        if (chunk != null) {
            styledText.append(chunk);
            styledText.addRun(
                    new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
        }

        chunk = null;
        element = elements.get(i);
        startOffset = element.getStartOffset();
        endOffset = element.getEndOffset();

        try {
            chunk = document.getText(startOffset, endOffset - startOffset);
        } catch (BadLocationException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error converting markup.", e);
            }
        }

    }

    if (chunk != null && !"\n".equals(chunk)) {
        styledText.append(chunk);
        styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
    }

    return JRStyledTextParser.getInstance().write(styledText);
}

From source file:forge.screens.deckeditor.DeckImport.java

private void readInput() {
    this.tokens.clear();
    final ElementIterator it = new ElementIterator(this.txtInput.getDocument().getDefaultRootElement());
    Element e;

    DeckRecognizer recognizer = new DeckRecognizer(newEditionCheck.isSelected(), onlyCoreExpCheck.isSelected(),
            FModel.getMagicDb().getCommonCards());
    if (dateTimeCheck.isSelected()) {
        recognizer.setDateConstraint(monthDropdown.getSelectedIndex(),
                (Integer) yearDropdown.getSelectedItem());
    }// w ww  .j  a v a2 s  .  c  o  m
    while ((e = it.next()) != null) {
        if (!e.isLeaf()) {
            continue;
        }
        final int rangeStart = e.getStartOffset();
        final int rangeEnd = e.getEndOffset();
        try {
            final String line = this.txtInput.getText(rangeStart, rangeEnd - rangeStart);
            this.tokens.add(recognizer.recognizeLine(line));
        } catch (final BadLocationException ex) {
        }
    }
}

From source file:EditorPaneExample16.java

public Heading getNextHeading(Document doc, ElementIterator iter) {
    Element elem;/* ww  w  . j  a  v a  2  s  . co  m*/

    while ((elem = iter.next()) != null) {
        AttributeSet attrs = elem.getAttributes();
        Object type = attrs.getAttribute(StyleConstants.NameAttribute);
        int level = getHeadingLevel(type);
        if (level > 0) {
            // It is a heading - get the text
            String headingText = "";
            int count = elem.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = elem.getElement(i);
                AttributeSet cattrs = child.getAttributes();
                if (cattrs.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    try {
                        int offset = child.getStartOffset();
                        headingText += doc.getText(offset, child.getEndOffset() - offset);
                    } catch (BadLocationException e) {
                    }
                }
            }
            headingText = headingText.trim();
            return new Heading(headingText, level, elem.getStartOffset());
        }
    }
    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);/*from  w  w w.  j  a va 2  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:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java

/**
 * Ensures that the document won't become too big. When the document reaches
 * a certain size the first message in the page is removed.
 *//* www  .j  av  a 2s.  c o  m*/
private void ensureDocumentSize() {
    if (document.getLength() > Chat.CHAT_BUFFER_SIZE) {
        String[] ids = new String[] { ChatHtmlUtils.MESSAGE_TEXT_ID, "statusMessage", "systemMessage",
                "actionMessage" };

        Element firstMsgElement = findElement(Attribute.ID, ids);

        int startIndex = firstMsgElement.getStartOffset();
        int endIndex = firstMsgElement.getEndOffset();

        try {
            // Remove the message.
            this.document.remove(startIndex, endIndex - startIndex);
        } catch (BadLocationException e) {
            logger.error("Error removing messages from chat: ", e);
        }

        if (firstMsgElement.getName().equals("table")) {
            // as we have removed a header for maybe several messages,
            // delete all messages without header
            deleteAllMessagesWithoutHeader();
        }
    }
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java

/**
 * Deletes all messages "div"s that are missing their header the table tag.
 * The method calls itself recursively.//from   ww  w.  ja  v a  2s  . c  om
 */
private void deleteAllMessagesWithoutHeader() {
    String[] ids = new String[] { ChatHtmlUtils.MESSAGE_TEXT_ID, "statusMessage", "systemMessage",
            "actionMessage" };

    Element firstMsgElement = findElement(Attribute.ID, ids);

    if (firstMsgElement == null || !firstMsgElement.getName().equals("div")) {
        return;
    }

    int startIndex = firstMsgElement.getStartOffset();
    int endIndex = firstMsgElement.getEndOffset();

    try {
        // Remove the message.
        if (endIndex - startIndex < document.getLength())
            this.document.remove(startIndex, endIndex - startIndex);
        else {
            // currently there is a problem of deleting the last message
            // if it is the last message on the view
            return;
        }
    } catch (BadLocationException e) {
        logger.error("Error removing messages from chat: ", e);

        return;
    }

    deleteAllMessagesWithoutHeader();
}

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) {//w  ww.  j  a  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

/**
 * Method for inserting a break (BR) element inside a table cell.
 *///from w  w  w  . jav  a  2s.  c  o  m
private void insertBreakInsideTD(Element tdElement) throws IOException, BadLocationException, RuntimeException {
    int caretPos = jtpMain.getCaretPosition();

    //      log.debug("--------------- caretPos: " + caretPos);
    //      DocumentUtil.debug(tdElement);

    if (caretPos == tdElement.getStartOffset()) {
        // Avoid inserting the break in the previous cell.
        Element parent = htmlDoc.getParagraphElement(caretPos);
        htmlDoc.insertAfterStart(parent, "<BR>");
        if (parent == tdElement) {
            jtpMain.setCaretPosition(caretPos + 2);
        } else {
            jtpMain.setCaretPosition(caretPos + 1);
        }
        return;
    }

    htmlKit.insertHTML(htmlDoc, caretPos, "<BR>", 0, 0, HTML.Tag.BR);
    jtpMain.setCaretPosition(caretPos + 1);

    //      caretPos = jtpMain.getCaretPosition();
    //      log.debug("--------------- depois: " + caretPos);
    //      DocumentUtil.debug(tdElement);

}

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

public void keyTyped(KeyEvent ke) {

    // log.debug("> keyTyped(" + ke.getKeyChar() + ")");

    Element elem;
    int pos = this.getCaretPosition();
    int repos = -1;
    if (ke.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
        try {//from   w w w  . java  2  s .  co m
            if (pos > 0) {
                // if (jtpMain.getSelectedText() != null) {
                // htmlUtilities.delete();
                // refreshOnUpdate();
                // return;
                // } else {
                int sOffset = htmlDoc.getParagraphElement(pos).getStartOffset();
                if (sOffset == jtpMain.getSelectionStart()) {
                    boolean content = true;
                    if (htmlUtilities.checkParentsTag(HTML.Tag.LI)) {
                        elem = htmlUtilities.getListItemParent();
                        content = false;
                        int so = elem.getStartOffset();
                        int eo = elem.getEndOffset();
                        if (so + 1 < eo) {
                            char[] temp = jtpMain.getText(so, eo - so).toCharArray();
                            for (char c : temp) {
                                if (!(new Character(c)).isWhitespace(c)) {
                                    content = true;
                                }
                            }
                        }
                        if (!content) {
                            htmlUtilities.removeTag(elem, true);
                            this.setCaretPosition(sOffset - 1);
                            refreshOnUpdate();
                            return;
                        } else {
                            jtpMain.replaceSelection("");
                            refreshOnUpdate();
                            return;
                        }
                    } else if (htmlUtilities.checkParentsTag(HTML.Tag.TABLE)) {
                        jtpMain.setCaretPosition(jtpMain.getCaretPosition() - 1);
                        ke.consume();
                        refreshOnUpdate();
                        return;
                    }
                }
                jtpMain.replaceSelection("");
                refreshOnUpdate();
                return;
                // }
            }
        } catch (BadLocationException ble) {
            logException("BadLocationException in keyTyped method", ble);
            new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                    Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
        } // catch (IOException ioe) {
          // logException("IOException in keyTyped method", ioe);
          // new SimpleInfoDialog(this.getWindow(),
          // Translatrix.getTranslationString("Error"), true,
          // Translatrix.getTranslationString("ErrorIOException"),
          // SimpleInfoDialog.ERROR);
          // }
          // finally {
          // log.debug("< keyTyped");
          // }
    } else if (ke.getKeyChar() == KeyEvent.VK_ENTER && !inlineEdit) {
        try {
            if (htmlUtilities.checkParentsTag(HTML.Tag.UL) == true
                    | htmlUtilities.checkParentsTag(HTML.Tag.OL) == true) {
                elem = htmlUtilities.getListItemParent();
                int so = elem.getStartOffset();
                int eo = elem.getEndOffset();
                char[] temp = this.getTextPane().getText(so, eo - so).toCharArray();
                boolean content = false;
                for (char c : temp) {
                    if (!(new Character(c)).isWhitespace(c)) {
                        content = true;
                    }
                }
                if (content) {
                    int end = -1;
                    int j = temp.length;
                    do {
                        j--;
                        if (new Character(temp[j]).isLetterOrDigit(temp[j])) {
                            end = j;
                        }
                    } while (end == -1 && j >= 0);
                    j = end;
                    do {
                        j++;
                        if (!new Character(temp[j]).isSpaceChar(temp[j])) {
                            repos = j - end - 1;
                        }
                    } while (repos == -1 && j < temp.length);
                    if (repos == -1) {
                        repos = 0;
                    }
                }
                if (!content) {
                    removeEmptyListElement(elem);
                } else {
                    if (this.getCaretPosition() + 1 == elem.getEndOffset()) {
                        insertListStyle(elem);
                        this.setCaretPosition(pos - repos);
                    } else {
                        int caret = this.getCaretPosition();
                        String tempString = this.getTextPane().getText(caret, eo - caret);
                        if (tempString != null && tempString.length() > 0) {
                            this.getTextPane().select(caret, eo - 1);
                            this.getTextPane().replaceSelection("");
                            htmlUtilities.insertListElement(tempString);
                            Element newLi = htmlUtilities.getListItemParent();
                            this.setCaretPosition(newLi.getEndOffset() - 1);
                        }
                    }
                }
            } else if (enterIsBreak) {
                insertBreak();
                ke.consume();
            }
        } catch (BadLocationException ble) {
            logException("BadLocationException in keyTyped method", ble);
            new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                    Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
        } catch (IOException ioe) {
            logException("IOException in keyTyped method", ioe);
            new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                    Translatrix.getTranslationString("ErrorIOException"), SimpleInfoDialog.ERROR);
        }
        // finally {
        // log.debug("< keyTyped");
        // }
    }
}

From source file:net.team2xh.crt.gui.editor.EditorTextPane.java

/**
 * Returns the first character offset of the given line number.
 *
 * @param line Line number./*from w  w  w  .j av a2  s  . c  o m*/
 * @return First character offset of that line.
 * @throws BadLocationException
 */
public int getLineStartOffset(int line) throws BadLocationException {
    Element map = doc.getDefaultRootElement();
    if (line < 0) {
        throw new BadLocationException("Negative line", -1);
    } else if (line >= map.getElementCount()) {
        throw new BadLocationException("No such line", doc.getLength() + 1);
    } else {
        Element lineElem = map.getElement(line);
        return lineElem.getStartOffset();
    }
}