Java Code Examples for javax.swing.text.Document#render()

The following examples show how to use javax.swing.text.Document#render() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   File: HighlightingManager.java    License: Apache License 2.0 6 votes vote down vote up
public @Override void propertyChange(PropertyChangeEvent evt) {
    if (evt.getPropertyName() == null || PROP_DOCUMENT.equals(evt.getPropertyName())) {
        updatePaneFilter();
        Document doc = pane.getDocument();
        if (doc != null) {
            doc.render(new Runnable() {
                @Override
                public void run() {
                    rebuildAll();
                }
            });
        }
    }

    if (PROP_HL_INCLUDES.equals(evt.getPropertyName()) || PROP_HL_EXCLUDES.equals(evt.getPropertyName())) {
        updatePaneFilter();
        rebuildAllLayers();
    }
}
 
Example 2
Source Project: netbeans   File: DocPositionRegion.java    License: Apache License 2.0 6 votes vote down vote up
public String getText () {
    final String[] result = new String[1];
    final Document doc = this.doc.get();
    if (doc != null) {
        doc.render(new Runnable() {
            public void run () {
                try {
                    result[0] = doc.getText(getStartOffset(), getLength());
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    }
    return result[0];
}
 
Example 3
Source Project: netbeans   File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
public static int[] findIdentifierSpan( final TreePath decl, final CompilationInfo info, final Document doc) {
    final int[] result = new int[] {-1, -1};
    Runnable r = new Runnable() {
        public void run() {
            Token<JavaTokenId> t = findIdentifierSpan(info, doc, decl);
            if (t != null) {
                result[0] = t.offset(null);
                result[1] = t.offset(null) + t.length();
            }
        }
    };
    if (doc != null) {
        doc.render(r);
    } else {
        r.run();
    }
    return result;
}
 
Example 4
@Override
public OffsetRange getReferenceSpan(final Document doc, final int caretOffset) {
    final OffsetRange[] value = new OffsetRange[1];
    value[0] = OffsetRange.NONE;

    doc.render(new Runnable() {

        @Override
        public void run() {
            TokenSequence<? extends JsTokenId> ts = LexUtilities.getJsTokenSequence(doc, caretOffset);
            Token<? extends JsTokenId> path = getModeluPath(ts, caretOffset);
            if (path != null) {
                value[0] = new OffsetRange(ts.offset(), ts.offset() + ts.token().length());
            }
        }
    });
    return value[0];
}
 
Example 5
Source Project: netbeans   File: PHPSQLStatement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given a caret offset into a PHP document, compute the SQL statement for that
 * location, if any.
 *
 * @param document the PHP source document
 * @param caretOffset the caret location in the document
 * @return the resulting PHPSQLStatement, or null if none could be determined
 */
public static PHPSQLStatement computeSQLStatement(final Document document, final int caretOffset) {
    final PHPSQLStatement[] result = {null};
    document.render(new Runnable() {

        @Override
        public void run() {
            TokenSequence<PHPTokenId> seq = LexUtilities.getPHPTokenSequence(document, caretOffset);
            if (seq == null) {
                return;
            }

            PHPSQLStatement stmt = new PHPSQLStatement(seq, caretOffset);
            if (stmt.getStatement() != null) {
                result[0] = stmt;
            }
        }
    });

    return result[0];
}
 
Example 6
Source Project: netbeans   File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copied from org.netbeans.api.xml.parsers.DocumentInputSource to save whole module dependency.
 *
 * @param doc a Document to read
 * @return Reader a reader that reads document's text
 */
public static Reader getDocumentReader(final Document doc) {
    final String[] str = new String[1];
    Runnable run = new Runnable() {
        @Override
        public void run () {
            try {
                str[0] = doc.getText(0, doc.getLength());
            } catch (javax.swing.text.BadLocationException e) {
                // impossible
                LOG.log(Level.INFO, null, e);
            }
        }
    };
    doc.render(run);
    return new StringReader(str[0]);
}
 
Example 7
Source Project: netbeans   File: CssModuleSupport.java    License: Apache License 2.0 6 votes vote down vote up
public static Pair<OffsetRange, FutureParamTask<DeclarationLocation, EditorFeatureContext>> getDeclarationLocation(final Document document, final int caretOffset, final FeatureCancel cancel) {
    final AtomicReference<Pair<OffsetRange, FutureParamTask<DeclarationLocation, EditorFeatureContext>>> result =
            new AtomicReference<>();
    document.render(new Runnable() {

        @Override
        public void run() {
            for (CssEditorModule module : getModules()) {
                if (cancel.isCancelled()) {
                    return ;
                }
                Pair<OffsetRange, FutureParamTask<DeclarationLocation, EditorFeatureContext>> declarationLocation = module.getDeclaration(document, caretOffset);
                if (declarationLocation != null) {
                    result.set(declarationLocation);
                    return ;
                }
            }
        }
        
    });
    return result.get();
}
 
Example 8
Source Project: netbeans   File: Convertors.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return current state of Document as string
 */
public static String documentToString (final Document doc) {
    
    final String[] str = new String[1];
    
    // safely take the text from the document
    Runnable run = new Runnable () {
        public void run () {
            try {
                str[0] = doc.getText (0, doc.getLength ());
            } catch (javax.swing.text.BadLocationException e) {
                // impossible
                e.printStackTrace ();
            }
        }
    };
    
    doc.render (run);
    return str[0];
    
}
 
Example 9
Source Project: netbeans   File: SQLCompletionProvider.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isDotAtOffset(JTextComponent component, final int offset) {
    final Document doc = component.getDocument();
    final boolean[] result = { false };
    doc.render(new Runnable() {
        public void run() {
            TokenSequence<SQLTokenId> seq = getSQLTokenSequence(doc);
            if (seq == null) {
                return;
            }
            seq.move(offset);
            if (!seq.moveNext() && !seq.movePrevious()) {
                return;
            }
            if (seq.offset() != offset) {
                return;
            }
            result[0] = (seq.token().id() == SQLTokenId.DOT);
        }
    });
    return result[0];
}
 
Example 10
Source Project: netbeans   File: LexerEmbeddingAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private void process(ConsoleModel model, List<ConsoleSection> sections) {
    Document d = model.getDocument();
    AtomicLockDocument ald = LineDocumentUtils.as(d, AtomicLockDocument.class);
    Runnable r = () -> {
    TokenHierarchy h = TokenHierarchy.get(d);
    
    if (h == null) {
        return;
    }
    TokenSequence seq = h.tokenSequence();
    for (ConsoleSection s : sections) {
        if (s.getType().java) {
            defineEmbeddings(seq, model, s);
        }
        
    }};
    if (ald != null) {
        ald.runAtomicAsUser(r);
    } else {
        d.render(r);
    }
}
 
Example 11
Source Project: netbeans   File: TplCompletionProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doQuery(CompletionResultSet resultSet, final Document doc, final int caretOffset) {
    try {
        final TplCompletionQuery.CompletionResult result = new TplCompletionQuery(doc).query();
        if (result != null) {
            doc.render(new Runnable() {
                @Override
                public void run() {
                    items = getItems(result, doc, caretOffset);
                }
            });
        } else {
            items = Collections.<TplCompletionItem>emptySet();
        }
        resultSet.addAllItems(items);

    } catch (ParseException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 12
Source Project: netbeans   File: ConsoleEditor.java    License: Apache License 2.0 5 votes vote down vote up
private void resetEditableArea(boolean caret) {
    if (pane == null || pane.getDocument() == null) {
        // probably closed
        return;
    }
    
    Document document = pane.getDocument();
    // may block/delay, check detached inside.
    document.render(() -> {
        if (detached) {
            return;
        }
        final LineDocument ld = LineDocumentUtils.as(document, LineDocument.class);
        if (ld == null) {
            return;
        }
        ConsoleModel model = session.getModel();
        ConsoleSection input = model.getInputSection();
        if (input != null) {
            int commandStart = input.getPartBegin();
//            pane.setCaretPosition(commandStart);
            if (commandStart > 0 && commandStart < document.getLength()) {
                return;
            }
            if (caret) {
                pane.setCaretPosition(commandStart);
            }
        }
    });
}
 
Example 13
private static boolean verifyDocument(final Document doc) {
    if (doc == null) {
        Logger.getLogger(SemanticHighlighterBase.class.getName()).log(Level.FINE, "SemanticHighlighter: Cannot get document!");
        return false;
    }

    final boolean[] tokenSequenceNull =  new boolean[1];
    doc.render(new Runnable() {
        @Override
        public void run() {
            tokenSequenceNull[0] = (TokenHierarchy.get(doc).tokenSequence() == null);
        }
    });
    return !tokenSequenceNull[0];
}
 
Example 14
Source Project: netbeans   File: ELHyperlinkProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int[] getHyperlinkSpan(final Document doc, final int offset, HyperlinkType type) {
    final AtomicReference<int[]> ret = new AtomicReference<>();
    doc.render(new Runnable() {

        @Override
        public void run() {
            ret.set(getELIdentifierSpan(doc, offset));
        }
    });
    return ret.get();
}
 
Example 15
@Override
protected boolean canFilter(final JTextComponent component) {
    final Collection<PaletteCompletionItem> currentItems = items;
    if(currentItems == null) {
        return false;
    }
    final Document doc = component.getDocument();
    final AtomicBoolean retval = new AtomicBoolean();
    doc.render(new Runnable() {

        @Override
        public void run() {
            try {
                int offset = component.getCaretPosition();
                if (completionExpressionStartOffset < 0  || offset < completionExpressionStartOffset) {
                    retval.set(false);
                    return;
                }
                String prefix = doc.getText(completionExpressionStartOffset, offset - completionExpressionStartOffset);
                //check the items
                for (PaletteCompletionItem item : currentItems) {
                    if (startsWithIgnoreCase(item.getItemName(), prefix)) {
                        retval.set(true); //at least one item will remain
                        return;
                    }
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });


    return retval.get();

}
 
Example 16
Source Project: netbeans   File: ActionFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    Document doc = target.getDocument();
    doc.render(new Runnable() {
        @Override
        public void run() {
            FoldHierarchy hierarchy = FoldHierarchy.get(target);
            int dot = target.getCaret().getDot();
            hierarchy.lock();
            try {
                try {
                    int rowStart = javax.swing.text.Utilities.getRowStart(target, dot);
                    int rowEnd = javax.swing.text.Utilities.getRowEnd(target, dot);
                    Fold fold = getLineFold(hierarchy, dot, rowStart, rowEnd);
                    if (fold == null) {
                        return;
                    }
                    List<Fold> allFolds = new ArrayList<>(FoldUtilities.findRecursive(fold));
                    Collections.reverse(allFolds);
                    allFolds.add(0, fold);
                    hierarchy.collapse(allFolds);
                } catch (BadLocationException ble) {
                    Exceptions.printStackTrace(ble);
                }
            } finally {
                hierarchy.unlock();
            }
        }
    });
}
 
Example 17
Source Project: netbeans   File: ActionFactory.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    Document doc = target.getDocument();
    doc.render(new Runnable() {
        @Override
        public void run() {
            FoldHierarchy hierarchy = FoldHierarchy.get(target);
            int dot = target.getCaret().getDot();
            hierarchy.lock();
            try{
                try{
                    int rowStart = javax.swing.text.Utilities.getRowStart(target, dot);
                    int rowEnd = javax.swing.text.Utilities.getRowEnd(target, dot);
                    Fold fold = FoldUtilities.findNearestFold(hierarchy, rowStart);
                    fold = getLineFold(hierarchy, dot, rowStart, rowEnd);
                    if (fold==null){
                        return; // no success
                    }
                    // ensure we' got the right fold
                    if (dotInFoldArea(target, fold, dot)){
                        hierarchy.collapse(fold);
                    }
                }catch(BadLocationException ble){
                    Exceptions.printStackTrace(ble);
                }
            }finally {
                hierarchy.unlock();
            }
        }
    });
}
 
Example 18
Source Project: netbeans   File: PropertiesParser.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates new input stream from the file object.
 * Finds the properties data object, checks if the document is loaded,
 * if not is loaded and created a stream from the document.
 * @exception IOException if any i/o problem occured during reading
 */
private PropertiesReader createReader() throws IOException {
    // Get loaded document, or load it if necessary.
    Document loadDoc = null;
    
    if(editor.isDocumentLoaded()) {
        loadDoc = editor.getDocument();
    } 

    if(loadDoc == null) {
        loadDoc = editor.openDocument(); 
    }
        
    final Document document = loadDoc;
    final String[] str = new String[1];

    // safely take the text from the document
    document.render(new Runnable() {
        public void run() {
            try {
                str[0] = document.getText(0, document.getLength());
            } catch(BadLocationException ble) {
                // Should be not possible.
                ble.printStackTrace();
            }
        }
    });

    return new PropertiesReader(str[0]);
}
 
Example 19
@Override
    public OffsetRange getReferenceSpan(final Document doc, final int caretOffset) {
//        int embeddedOffset = info.getSnapshot().getEmbeddedOffset(caretOffset);
        final OffsetRange[] value = new OffsetRange[1];
        doc.render(new Runnable() {

            @Override
            public void run() {
                TokenSequence<? extends JsTokenId> ts = LexUtilities.getJsTokenSequence(doc, caretOffset);

                if (ts == null) {
                    return;
                }

                ts.move(caretOffset);
                if (ts.moveNext()) {
                    JsTokenId id = ts.token().id();
                    if (id == JsTokenId.IDENTIFIER) {
                        value[0] = new OffsetRange(ts.offset(), ts.offset() + ts.token().length());
                        return;
                    }
                    value[0] = isValueOfProperty(AngularWhenInterceptor.CONTROLLER_PROP, ts, caretOffset);
                    if (value[0] != null) {
                        return;
                    }
                    value[0] = isValueOfProperty(AngularWhenInterceptor.TEMPLATE_URL_PROP, ts, caretOffset);
                    if (value[0] != null) {
                        return;
                    }
                    value[0] = isValueOfProperty(AngularConfigInterceptor.COMPONENT_PROP, ts, caretOffset);
                    if (value[0] != null) {
                        return;
                    }
                    value[0] = isValueOfProperty(AngularConfigInterceptor.COMPONENTS_PROP, ts, caretOffset);
                    if (value[0] != null) {
                        return;
                    }
                    value[0] = isInObjectValueOfProperty(AngularConfigInterceptor.COMPONENTS_PROP, ts, caretOffset);
                }
            }
        });
        if (value[0] != null) {
            return value[0];
        }
        return OffsetRange.NONE;
    }
 
Example 20
Source Project: netbeans   File: ContextAnalyzer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
        public void run(final CompilationController cc) throws Exception {
            cc.toPhase(JavaSource.Phase.RESOLVED);
            final int c = selection?start:this.caret;
            final TreePath[] selectedElement = new TreePath[] {null};
//            final boolean[] insideJavadoc = {false};
            final Document doc = cc.getDocument();
            doc.render(new Runnable() {
                @Override
                public void run() {
                    selectedElement[0] = validateSelection(cc, start, end);

                    if (selectedElement[0] == null) {
                        TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(cc.getTokenHierarchy(), c);
                        int adjustedCaret = c;
                        ts.move(c);
                        if (ts.moveNext() && ts.token() != null) {
                            if (ts.token().id() == JavaTokenId.IDENTIFIER) {
                                adjustedCaret = ts.offset() + ts.token().length() / 2 + 1;
                            } /*else if (ts.token().id() == JavaTokenId.JAVADOC_COMMENT) {
                             TokenSequence<JavadocTokenId> jdts = ts.embedded(JavadocTokenId.language());
                             if (jdts != null && JavadocImports.isInsideReference(jdts, caret)) {
                             jdts.move(caret);
                             if (jdts.moveNext() && jdts.token().id() == JavadocTokenId.IDENT) {
                             adjustedCaret[0] = jdts.offset();
                             insideJavadoc[0] = true;
                             }
                             } else if (jdts != null && JavadocImports.isInsideParamName(jdts, caret)) {
                             jdts.move(caret);
                             if (jdts.moveNext()) {
                             adjustedCaret[0] = jdts.offset();
                             insideJavadoc[0] = true;
                             }
                             }
                             }*/
                        }
                        selectedElement[0] = cc.getTreeUtilities().pathFor(adjustedCaret);
                    }
                }
            });
            //workaround for issue 89064
            if (selectedElement[0].getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
                List<? extends Tree> decls = cc.getCompilationUnit().getTypeDecls();
                if (!decls.isEmpty()) {
                    TreePath path = TreePath.getPath(cc.getCompilationUnit(), decls.get(0));
                    if (path!=null && cc.getTrees().getElement(path)!=null) {
                        selectedElement[0] = path;
                    }
                } else {
                    selectedElement[0] = null;
                }
            }
            ui = createRefactoringUI(selectedElement[0] != null ? TreePathHandle.create(selectedElement[0], cc) : null, start, end, cc);
        }