Example usage for javax.swing.text Document getDefaultRootElement

List of usage examples for javax.swing.text Document getDefaultRootElement

Introduction

In this page you can find the example usage for javax.swing.text Document getDefaultRootElement.

Prototype

public Element getDefaultRootElement();

Source Link

Document

Returns the root element that views should be based upon, unless some other mechanism for assigning views to element structures is provided.

Usage

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   w w w  . java2  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:EditorPaneExample16.java

public TreeNode buildHeadingTree(Document doc) {
    String title = (String) doc.getProperty(Document.TitleProperty);
    if (title == null) {
        title = "[No title]";
    }/*from   w w w .  j a  va2 s.c  o  m*/
    Heading rootHeading = new Heading(title, 0, 0);
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(rootHeading);

    DefaultMutableTreeNode lastNode[] = new DefaultMutableTreeNode[7];
    int lastLevel = 0;
    lastNode[lastLevel] = rootNode;

    if (doc instanceof HTMLDocument) {
        Element elem = doc.getDefaultRootElement();
        ElementIterator iterator = new ElementIterator(elem);
        Heading heading;

        while ((heading = getNextHeading(doc, iterator)) != null) {
            // Add the node to the tree
            DefaultMutableTreeNode hNode = new DefaultMutableTreeNode(heading);
            int level = heading.getLevel();

            if (level > lastLevel) {
                for (int i = lastLevel + 1; i < level; i++) {
                    lastNode[i] = null;
                }
                lastNode[lastLevel].add(hNode);
            } else {
                int prevLevel = level - 1;
                while (prevLevel >= 0) {
                    if (lastNode[prevLevel] != null) {
                        break;
                    }
                    lastNode[prevLevel] = null;
                    prevLevel--;
                }
                lastNode[prevLevel].add(hNode);
            }
            lastNode[level] = hNode;
            lastLevel = level;
        }
    }
    return rootNode;
}

From source file:org.apache.cayenne.swing.components.textpane.JCayenneTextPane.java

public void paint(Graphics g) {

    super.paint(g);

    int start = getStartPositionInDocument();
    int end = getEndPositionInDocument();
    // end pos in doc

    // translate offsets to lines
    Document doc = pane.getDocument();
    int startline = doc.getDefaultRootElement().getElementIndex(start) + 1;
    int endline = doc.getDefaultRootElement().getElementIndex(end) + 1;

    int fontHeight = g.getFontMetrics(pane.getFont()).getHeight();
    int fontDesc = g.getFontMetrics(pane.getFont()).getDescent();
    int starting_y = -1;

    try {/*from ww  w .  j av  a 2  s  .c o  m*/
        if (pane.modelToView(start) == null) {
            starting_y = -1;
        } else {
            starting_y = pane.modelToView(start).y - scrollPane.getViewport().getViewPosition().y + fontHeight
                    - fontDesc;
        }
    } catch (Exception e1) {
        logObj.warn("Error: ", e1);
    }

    for (int line = startline, y = starting_y; line <= endline; y += fontHeight, line++) {
        Color color = g.getColor();

        if (line - 1 == doc.getDefaultRootElement().getElementIndex(pane.getCaretPosition())) {
            g.setColor(new Color(224, 224, 255));
            g.fillRect(0, y - fontHeight + 3, 30, fontHeight + 1);
        }

        if (imageError) {
            Image img = ModelerUtil.buildIcon("error.gif").getImage();
            g.drawImage(img, 0, endYPositionToolTip, this);
        }

        g.setColor(color);
    }

}

From source file:org.docx4all.ui.menu.FileMenu.java

@Action
public void printPreview() {
    WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
    JEditorPane editor = wmlEditor.getCurrentEditor();

    WordMLEditorKit kit = (WordMLEditorKit) editor.getEditorKit();
    kit.saveCaretText();//from   w  w  w . j a  v  a  2s. co m

    Document doc = editor.getDocument();
    String filePath = (String) doc.getProperty(WordMLDocument.FILE_PATH_PROPERTY);
    DocumentElement elem = (DocumentElement) doc.getDefaultRootElement();
    DocumentML rootML = (DocumentML) elem.getElementML();

    //Do not include the last paragraph when saving or printing.
    //we'll put it back when the job is done.
    elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
    ElementML paraML = elem.getElementML();
    ElementML bodyML = paraML.getParent();
    paraML.delete();

    try {
        WordprocessingMLPackage wordMLPackage = rootML.getWordprocessingMLPackage();

        //         XmlPackage worker = new XmlPackage(wordMLPackage);         
        //         org.docx4j.xmlPackage.Package result = worker.get();         
        //         boolean suppressDeclaration = true;
        //         boolean prettyprint = true;         
        //         System.out.println( 
        //               org.docx4j.XmlUtils.
        //                  marshaltoString(result, suppressDeclaration, prettyprint, 
        //                        org.docx4j.jaxb.Context.jcXmlPackage) );

        //Create temporary .pdf file.
        //Remember that filePath is in Commons-VFS format which
        //uses '/' as separator char.
        String tmpName = filePath.substring(filePath.lastIndexOf("/"), filePath.lastIndexOf(Constants.DOT));
        File tmpFile = File.createTempFile(tmpName + ".tmp", ".pdf");
        // Delete the temporary file when program exits.
        tmpFile.deleteOnExit();

        OutputStream os = new java.io.FileOutputStream(tmpFile);

        // Could write to a ByteBuffer and avoid the temp file if:
        // 1. com.sun.pdfview.PDFViewer had an appropriate open method
        // 2. We knew how big to make the buffer
        // java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(15000);
        // //15kb
        // OutputStream os = newOutputStream(buf);

        PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
        // can change from viaHTML to viaIText or viaXSLFO
        PdfSettings settings = new PdfSettings();
        c.output(os, settings);

        os.close();

        PDFViewer pv = new PDFViewer(true);
        // pv.openFile(buf, "some name"); // requires modified
        // com.sun.pdfview.PDFViewer
        pv.openFile(tmpFile);

    } catch (Exception exc) {
        exc.printStackTrace();
        ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());
        String title = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.text");
        String message = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.errorMessage") + "\n"
                + VFSUtils.getFriendlyName(filePath);
        wmlEditor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);

    } finally {
        //Remember to put 'paraML' as last paragraph
        bodyML.addChild(paraML);
    }

}

From source file:org.docx4all.ui.menu.FileMenu.java

/**
 * Saves editor documents to a file./* ww  w.j  ava2  s  .co  m*/
 * 
 * Internal frame may have two editors for presenting two different views
 * to user namely editor view and source view. WordMLTextPane is used for 
 * editor view and JEditorPane for source view.
 * The contents of these two editors are synchronized when user switches
 * from one view to the other. Therefore, there will be ONLY ONE editor 
 * that is dirty and has to be saved by this method.
 * 
 * @param iframe
 * @param saveAsFilePath
 * @param callerActionName
 * @return
 */
public boolean save(JInternalFrame iframe, String saveAsFilePath, String callerActionName) {
    boolean success = true;

    if (saveAsFilePath == null) {
        saveAsFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);
    }

    if (log.isDebugEnabled()) {
        log.debug("save(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));
    }

    WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe);
    JEditorPane sourceView = SwingUtil.getSourceEditor(iframe);

    if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG))
            .booleanValue()) {
        //signifies that Source View is not synchronised with Editor View yet.
        //Therefore, it is dirty and has to be saved.
        if (editorView != null && editorView.getWordMLEditorKit().getPlutextClient() != null) {
            //Document has to be saved from editor view 
            //by committing local edits
            success = false;
        } else {
            EditorKit kit = sourceView.getEditorKit();
            Document doc = sourceView.getDocument();
            WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) doc
                    .getProperty(WordMLDocument.WML_PACKAGE_PROPERTY);

            DocUtil.write(kit, doc, wmlPackage);
            success = save(wmlPackage, saveAsFilePath, callerActionName);

            if (success) {
                if (saveAsFilePath.endsWith(Constants.DOCX_STRING)
                        || saveAsFilePath.endsWith(Constants.FLAT_OPC_STRING)) {
                    doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                    iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                }
            }
        }
        return success;
    }
    sourceView = null;

    if (editorView == null) {
        ;//pass

    } else if (editorView.getWordMLEditorKit().getPlutextClient() != null) {
        if (saveAsFilePath.equals(editorView.getDocument().getProperty(WordMLDocument.FILE_PATH_PROPERTY))) {
            success = commitLocalChanges(editorView, callerActionName);

        } else {
            //TODO: Enable saving Plutext document as a new file.
            WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
            ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());
            String title = rm.getString(callerActionName + ".Action.text");
            StringBuilder message = new StringBuilder();
            message.append("File ");
            message.append(saveAsFilePath);
            message.append(Constants.NEWLINE);
            message.append(rm.getString(callerActionName + ".Action.wrong.fileName.infoMessage"));
            wmlEditor.showMessageDialog(title, message.toString(), JOptionPane.INFORMATION_MESSAGE);

            success = false;
        }
    } else {
        WordMLEditorKit kit = (WordMLEditorKit) editorView.getEditorKit();
        kit.saveCaretText();

        Document doc = editorView.getDocument();
        DocumentElement elem = (DocumentElement) doc.getDefaultRootElement();
        DocumentML rootML = (DocumentML) elem.getElementML();

        //Do not include the last paragraph when saving.
        //After saving we put it back.
        elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
        ElementML paraML = elem.getElementML();
        ElementML bodyML = paraML.getParent();
        paraML.delete();

        success = save(rootML.getWordprocessingMLPackage(), saveAsFilePath, callerActionName);

        //Remember to put 'paraML' as last paragraph
        bodyML.addChild(paraML);

        if (success) {
            if (saveAsFilePath.endsWith(Constants.DOCX_STRING)) {
                doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
            }
        }
    }

    return success;
}

From source file:org.docx4all.ui.menu.FileMenu.java

public boolean export(JInternalFrame iframe, String saveAsFilePath, String callerActionName) {
    log.debug("export(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));

    WordprocessingMLPackage srcPackage = null;

    WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe);
    JEditorPane sourceView = SwingUtil.getSourceEditor(iframe);

    if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG))
            .booleanValue()) {//  w  ww.java2 s  . co  m
        //signifies that Source View is not synchronised with Editor View yet.
        //Therefore, export from Source View.
        EditorKit kit = sourceView.getEditorKit();
        Document doc = sourceView.getDocument();
        srcPackage = DocUtil.write(kit, doc, null);
        editorView = null;
    }
    sourceView = null;

    if (editorView == null) {
        ;//pass
    } else {
        WordMLDocument doc = (WordMLDocument) editorView.getDocument();
        DocumentElement root = (DocumentElement) doc.getDefaultRootElement();
        DocumentML docML = (DocumentML) root.getElementML();
        srcPackage = docML.getWordprocessingMLPackage();
    }

    boolean success = save(XmlUtil.export(srcPackage), saveAsFilePath, callerActionName);

    log.debug("export(): success=" + success + " filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));

    return success;
}

From source file:ro.nextreports.designer.querybuilder.SQLViewPanel.java

private void highlightErrorLine(Exception e) {
    removeHighlightErrorLine();/* w w w  . j  av a 2s . com*/
    // determine error line number, if any
    String er = e.getMessage();
    // error may contain line number info like " line 12" or " line 12, column 3 " ...
    String regex = ".*\\sline\\s(\\d+)([^\\d].*)*";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(er);
    // first found is line number
    if (m.find()) {
        String lineNo = m.group(1);
        LOG.info("Error on line number : " + lineNo);
        Document ed = sqlEditor.getEditorPanel().getEditorPane().getDocument();
        Element elem = ed.getDefaultRootElement().getElement(Integer.parseInt(lineNo) - 1);
        sqlEditor.getEditorPanel().getEditorPane().setCaretPosition(elem.getStartOffset());
        try {
            errorTag = sqlEditor.getEditorPanel().getEditorPane().getHighlighter()
                    .addHighlight(elem.getStartOffset(), elem.getEndOffset(), errorPainter);
        } catch (BadLocationException e1) {
            LOG.error("Could not highlight sql error line number", e1);
        }
    }
}

From source file:tk.tomby.tedit.core.snr.FindReplaceWorker.java

/**
 * DOCUMENT ME!/* ww  w.ja  v  a2  s  .c o m*/
 *
 * @param lineNumber DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
private Element init(int lineNumber) {
    Document doc = buffer.getDocument();
    Element line = doc.getDefaultRootElement().getElement(lineNumber);

    try {
        int options = Pattern.DOTALL;

        String find = PreferenceManager.getString("snr.find", "");

        if ((find != null) && !find.equals("")) {
            if (PreferenceManager.getBoolean("snr.case", false)) {
                find = find.toLowerCase();

                options |= Pattern.CASE_INSENSITIVE;
            }

            if (PreferenceManager.getBoolean("snr.whole", false)) {
                find = "\\b" + find + "\\b";
            }

            int offset = line.getStartOffset();
            int length = line.getEndOffset() - offset;

            if (PreferenceManager.getInt("snr.direction", FORWARD) == FORWARD) {
                if ((buffer.getSelectionEnd() > line.getStartOffset())
                        && (buffer.getSelectionEnd() <= line.getEndOffset())) {
                    offset = buffer.getSelectionEnd();
                    length = line.getEndOffset() - offset;
                }
            } else {
                if ((buffer.getSelectionStart() > line.getStartOffset())
                        && (buffer.getSelectionStart() <= line.getEndOffset())) {
                    length = buffer.getSelectionStart() - offset;
                }
            }

            String text = doc.getText(offset, length);

            Pattern pattern = Pattern.compile(find, options);

            this.matcher = pattern.matcher(text);
        }
    } catch (BadLocationException e) {
        log.error(e.getMessage(), e);
    }

    return line;
}