Example usage for javax.swing.text Element getEndOffset

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

Introduction

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

Prototype

public int getEndOffset();

Source Link

Document

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

Usage

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.  ja v  a2s  .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 w  w  w  . jav a  2 s .  c o  m
 */
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) {/*from  w  w w  .  j  a va  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

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  . j a  va2 s. c om*/
            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 last character offset of the given line number.
 *
 * @param line Line number.//from   ww  w.j a v a 2  s. c  o m
 * @return Last character offset of that line.
 * @throws BadLocationException
 */
public int getLineEndOffset(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.getEndOffset();
    }
}

From source file:org.alder.fotobuchconvert.scribus.RtfToScribusConverter.java

void output(XmlBuilder xml, DefaultStyledDocument doc, ScribusWriter scribus) {
    log.debug("Starting conversion of RTF data");
    if (log.isTraceEnabled())
        doc.dump(System.err);/*from   w ww  .  ja  va  2s .  com*/

    try {
        Element section = doc.getDefaultRootElement();
        log.trace(section);
        assert section.getName().equals("section");

        final int nj = section.getElementCount();
        for (int j = 0; j < nj; j++) {
            Element paragraph = section.getElement(j);
            log.trace(paragraph);
            assert section.getName().equals("paragraph");

            // boolean firstInPara = true;
            AttributeSet attr = paragraph.getAttributes();
            Integer alignment = (Integer) attr.getAttribute(StyleConstants.Alignment);

            boolean elementsInThisLine = false;
            final int ni = paragraph.getElementCount();
            for (int i = 0; i < ni; i++) {
                Element content = paragraph.getElement(i);
                assert section.getName().equals("content");

                int start = content.getStartOffset();
                int end = content.getEndOffset();

                attr = content.getAttributes();
                Boolean italic = (Boolean) attr.getAttribute(StyleConstants.Italic);
                Boolean bold = (Boolean) attr.getAttribute(StyleConstants.Bold);
                Boolean underline = (Boolean) attr.getAttribute(StyleConstants.Underline);
                String family = (String) attr.getAttribute(StyleConstants.Family);
                Integer fontSize = (Integer) attr.getAttribute(StyleConstants.Size);
                Color color = (Color) attr.getAttribute(StyleConstants.ColorConstants.Foreground);

                String text = doc.getText(start, end - start);

                // if (firstInPara && text.trim().isEmpty() && family ==
                // null
                // && fontSize == null)
                // continue;
                // else
                // firstInPara = false;
                if (i == ni - 1 && text.trim().isEmpty() && text.length() < 3)
                    continue;
                elementsInThisLine = true;

                while (text.endsWith("\n") || text.endsWith("\r"))
                    text = text.substring(0, text.length() - 1);

                log.debug(italic + " " + bold + " " + underline + " " + family + " " + fontSize + " " + color
                        + "\t\"" + text + "\"");

                XmlBuilder el = xml.add(C.EL_ITEXT).set(C.CH, text);

                if (bold == Boolean.TRUE && italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold Italic");
                else if (bold == Boolean.TRUE)
                    el.set(C.FONT, family + " Bold");
                else if (italic == Boolean.TRUE)
                    el.set(C.FONT, family + " Italic");
                else
                    el.set(C.FONT, family + " Regular");

                if (fontSize != null)
                    el.set(C.FONTSIZE, fontSize);

                if (color != null && color.equals(Color.BLACK) && scribus != null) {
                    String colname = scribus.colorManager.getColorName(color);
                    el.set(C.FCOLOR, colname);
                }
            }

            if (!elementsInThisLine && j == nj - 1)
                break; // don't convert last line if empty

            XmlBuilder el = xml.add(C.EL_PARA);
            if (alignment != null)
                switch (alignment) {
                case StyleConstants.ALIGN_LEFT:
                    el.set(C.ALIGN, 0);
                    break;
                case StyleConstants.ALIGN_CENTER:
                    el.set(C.ALIGN, 1);
                    break;
                case StyleConstants.ALIGN_RIGHT:
                    el.set(C.ALIGN, 2);
                    break;
                case StyleConstants.ALIGN_JUSTIFIED:
                    el.set(C.ALIGN, 3);
                    break;
                }
        }
    } catch (BadLocationException e) {
        throw new RuntimeException("This error should not occour", e);
    }

}

From source file:org.debux.webmotion.netbeans.Utils.java

public static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException {
    Element lineElement = doc.getParagraphElement(offset);
    int start = lineElement.getStartOffset();
    while (start + 1 < lineElement.getEndOffset()) {
        try {//from  w ww  .  j a  va2s.  c  o m
            char charAt = doc.getText(start, 1).charAt(0);
            if (charAt != ' ') {
                break;
            }
        } catch (BadLocationException ex) {
            throw (BadLocationException) new BadLocationException(
                    "calling getText(" + start + ", " + (start + 1) + ") on doc of length: " + doc.getLength(),
                    start).initCause(ex);
        }
        start++;
    }
    return start;
}

From source file:org.deegree.tools.metadata.InspireValidator.java

/**
 * parse INSPIRE metadata validator response and print out result onto the console
 * //  w ww .  j av  a 2 s .  c  o m
 * @param response
 * @throws IOException
 * @throws IllegalStateException
 */
private void parseServiceResponse(HttpResponse response) throws Exception {
    String s = FileUtils.readTextFile(((BasicHttpResponse) response).getEntity().getContent()).toString();
    if (response.getStatusLine().getStatusCode() != 200) {
        outputWriter.println(s);
        outputWriter.println();
        return;
    }
    s = "<html><head></head><body>" + s + "</body></html>";
    BufferedReader br = new BufferedReader(new StringReader(s));

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);

    // Parse
    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag) && ((name == HTML.Tag.IMPLIED))) {
            // Build up content text as it may be within multiple elements
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            outputWriter.println(text.toString());
        }
    }
    outputWriter.println("---------------------------------------------------------------------");
    outputWriter.println();
}

From source file:org.domainmath.gui.MainFrame.java

private int getFirstCharacter(Element row) {
    if (row == null) {
        return 0;
    }/* ww w  .  j  a  v a2  s  .  co  m*/
    int lastColumnInRow = row.getEndOffset();
    return lastColumnInRow;
}

From source file:org.domainmath.gui.MainFrame.java

public void gotoLine(String goto_file, int lineRequested) {
    if (fileTab.getSelectedIndex() >= 0) {
        int indexOf = MainFrame.fileNameList.indexOf(goto_file);
        RTextScrollPane t = (RTextScrollPane) fileTab.getComponentAt(indexOf);
        RSyntaxTextArea selectedArea = (RSyntaxTextArea) t.getTextArea();
        try {//  ww w.  j ava2s . c  o m
            Element element = selectedArea.getDocument().getDefaultRootElement();

            int rowCount = element.getElementCount();
            if (lineRequested > rowCount || lineRequested < 0) {

                setVisible(false);
                return;
            }
            Element row = null;
            int firstCharacter = 0;
            int rowNumber = 0;
            for (int i = 0; i < lineRequested; ++i) {
                firstCharacter = getFirstCharacter(row);
                rowNumber = element.getElementIndex(firstCharacter);
                row = element.getElement(rowNumber);
            }
            int lastColumnInRow = row.getEndOffset();
            selectedArea.select(firstCharacter, lastColumnInRow - 1);

        } catch (Exception e) {

        }
    }
}