Java Code Examples for org.netbeans.editor.BaseDocument#readLock()
The following examples show how to use
org.netbeans.editor.BaseDocument#readLock() .
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 File: CompletionContext.java From netbeans with Apache License 2.0 | 6 votes |
private boolean copyDocument(final BaseDocument src, final BaseDocument dest) { final boolean[] retVal = new boolean[]{true}; src.readLock(); try{ dest.runAtomic(new Runnable() { @Override public void run() { try { String docText = src.getText(0, src.getLength()); dest.insertString(0, docText, null); // dest.putProperty(Language.class, src.getProperty(Language.class)); } catch(BadLocationException ble) { Exceptions.printStackTrace(ble); retVal[0] = false; } } }); } finally { src.readUnlock(); } return retVal[0]; }
Example 2
Source File: HyperlinkOperation.java From netbeans with Apache License 2.0 | 6 votes |
private void performHyperlinking(int position, HyperlinkType type) { final BaseDocument doc = (BaseDocument) component.getDocument(); doc.readLock(); try { HyperlinkProviderExt provider = findProvider(position, type); if (provider != null) { int[] offsets = provider.getHyperlinkSpan(doc, position, type); if (offsets != null) { makeHyperlink(type, provider, offsets[0], offsets[1], position); } } else { unHyperlink(true); } } finally { doc.readUnlock(); } }
Example 3
Source File: PHP73UnhandledError.java From netbeans with Apache License 2.0 | 6 votes |
private void checkFunctionCallTrailingCommas() { if (!nodes.isEmpty()) { BaseDocument document = GsfUtilities.getDocument(fileObject, true); if (document == null) { return; } document.readLock(); try { TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, 0); if (ts == null) { return; } checkFunctionCallTrailingCommas(ts); } finally { document.readUnlock(); nodes.clear(); } } }
Example 4
Source File: PHP73UnhandledError.java From netbeans with Apache License 2.0 | 6 votes |
private void checkFlexibleHeredocAndNowdoc() { if (CancelSupport.getDefault().isCancelled()) { return; } BaseDocument document = GsfUtilities.getDocument(fileObject, true); if (document == null) { return; } document.readLock(); try { TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, document.getLength()); if (ts == null) { return; } ts.move(document.getLength()); checkHeredocNowdocIndentationAndNewline(ts); } finally { document.readUnlock(); } }
Example 5
Source File: IntroduceSuggestion.java From netbeans with Apache License 2.0 | 6 votes |
private static int getOffsetAfterNextTokenId(BaseDocument doc, int offset, PHPTokenId tokenId) throws BadLocationException { int retval = offset; doc.readLock(); try { TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, retval); if (ts != null) { ts.move(retval); while (ts.moveNext()) { Token t = ts.token(); if (t.id() == tokenId) { ts.moveNext(); retval = ts.offset(); break; } } } } finally { doc.readUnlock(); } return retval; }
Example 6
Source File: XmlFoldManager.java From netbeans with Apache License 2.0 | 5 votes |
/** * This method parses the XML document using Lexer and creates/recreates * the fold hierarchy. */ private void updateFolds() { FoldHierarchy foldHierarchy = getOperation().getHierarchy(); //lock the document for changes BaseDocument d = getDocument(); d.readLock(); try { //lock the hierarchy foldHierarchy.lock(); try { //open new transaction FoldHierarchyTransaction fht = getOperation().openTransaction(); try { ArrayList<Fold> existingFolds = new ArrayList<Fold>(); collectExistingFolds(foldHierarchy.getRootFold(), existingFolds); for(Fold f : existingFolds) { getOperation().removeFromHierarchy(f, fht); } createFolds(fht); } catch (Exception ex) { // Logger.getLogger(this.getClass().getName()).log(Level.WARNING, // NbBundle.getMessage(XmlFoldManager.class, "MSG_FOLDS_DISABLED")); } finally { fht.commit(); } } finally { //printFoldHierarchy(foldHierarchy.getRootFold(),""); foldHierarchy.unlock(); } } finally { d.readUnlock(); } }
Example 7
Source File: TwigBracesMatcher.java From netbeans with Apache License 2.0 | 5 votes |
@Override public int[] findMatches() throws InterruptedException, BadLocationException { int[] result = null; BaseDocument document = (BaseDocument) context.getDocument(); document.readLock(); try { result = findMatchesUnderLock(); } finally { document.readUnlock(); } return result; }
Example 8
Source File: TwigBracesMatcher.java From netbeans with Apache License 2.0 | 5 votes |
@Override public int[] findOrigin() throws InterruptedException, BadLocationException { int[] result = null; BaseDocument document = (BaseDocument) context.getDocument(); document.readLock(); try { result = findOriginUnderLock(); } finally { document.readUnlock(); } return result; }
Example 9
Source File: LatteBracesMatcher.java From netbeans with Apache License 2.0 | 5 votes |
@Override public int[] findMatches() throws InterruptedException, BadLocationException { int[] result = null; BaseDocument document = (BaseDocument) context.getDocument(); document.readLock(); try { result = findMatchesUnderLock(); } finally { document.readUnlock(); } return result; }
Example 10
Source File: LanguageRegistry.java From netbeans with Apache License 2.0 | 5 votes |
public List<Language> getEmbeddedLanguages(BaseDocument doc, int offset) { List<Language> result = new ArrayList<Language>(); doc.readLock(); // Read-lock due to Token hierarchy use try { // TODO - I should only do this for languages which CAN have it /* at org.netbeans.lib.lexer.inc.IncTokenList.reinit(IncTokenList.java:113) at org.netbeans.lib.lexer.TokenHierarchyOperation.setActiveImpl(TokenHierarchyOperation.java:257) at org.netbeans.lib.lexer.TokenHierarchyOperation.isActiveImpl(TokenHierarchyOperation.java:308) at org.netbeans.lib.lexer.TokenHierarchyOperation.tokenSequence(TokenHierarchyOperation.java:344) at org.netbeans.lib.lexer.TokenHierarchyOperation.tokenSequence(TokenHierarchyOperation.java:338) at org.netbeans.api.lexer.TokenHierarchy.tokenSequence(TokenHierarchy.java:183) at org.netbeans.modules.csl.LanguageRegistry.getEmbeddedLanguages(LanguageRegistry.java:336) at org.netbeans.modules.gsfret.hints.infrastructure.SuggestionsTask.getHintsProviderLanguage(SuggestionsTask.java:70) at org.netbeans.modules.gsfret.hints.infrastructure.SuggestionsTask.run(SuggestionsTask.java:94) at org.netbeans.modules.gsfret.hints.infrastructure.SuggestionsTask.run(SuggestionsTask.java:63) [catch] at org.netbeans.napi.gsfret.source.Source$CompilationJob.run(Source.java:1272) * */ TokenSequence ts = TokenHierarchy.get(doc).tokenSequence(); if (ts != null) { addLanguages(result, ts, offset); } } finally { doc.readUnlock(); } String mimeType = (String) doc.getProperty("mimeType"); // NOI18N if (mimeType != null) { Language language = getLanguageByMimeType(mimeType); if (language != null && (result.size() == 0 || result.get(result.size()-1) != language)) { result.add(language); } } return result; }
Example 11
Source File: IntroduceSuggestion.java From netbeans with Apache License 2.0 | 5 votes |
private static int getOffsetAfterBlockCloseCurly(BaseDocument doc, int offset) throws BadLocationException { int retval = offset; doc.readLock(); try { TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, retval); if (ts != null) { ts.move(retval); int curlyMatch = 0; while (ts.moveNext()) { Token t = ts.token(); if (t.id() == PHPTokenId.PHP_CURLY_OPEN || t.id() == PHPTokenId.PHP_CURLY_CLOSE) { if (t.id() == PHPTokenId.PHP_CURLY_OPEN) { curlyMatch++; } else if (t.id() == PHPTokenId.PHP_CURLY_CLOSE) { curlyMatch--; } if (curlyMatch == 0) { ts.moveNext(); retval = ts.offset(); break; } } } } } finally { doc.readUnlock(); } return retval; }
Example 12
Source File: ModifiersCheckHintError.java From netbeans with Apache License 2.0 | 5 votes |
private static int getStartOffset(final BaseDocument doc, final int elementOffset) { int retval = 0; doc.readLock(); try { TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, elementOffset); if (ts != null) { ts.move(elementOffset); TokenId lastTokenId = null; while (ts.movePrevious()) { Token t = ts.token(); if (t.id() != PHPTokenId.PHP_PUBLIC && t.id() != PHPTokenId.PHP_PROTECTED && t.id() != PHPTokenId.PHP_PRIVATE && t.id() != PHPTokenId.PHP_STATIC && t.id() != PHPTokenId.PHP_FINAL && t.id() != PHPTokenId.PHP_ABSTRACT && t.id() != PHPTokenId.PHP_FUNCTION && t.id() != PHPTokenId.WHITESPACE && t.id() != PHPTokenId.PHP_CLASS && t.id() != PHPTokenId.PHP_CONST) { ts.moveNext(); if (lastTokenId == PHPTokenId.WHITESPACE) { ts.moveNext(); } retval = ts.offset(); break; } lastTokenId = t.id(); } } } finally { doc.readUnlock(); } return retval; }
Example 13
Source File: PHP72UnhandledError.java From netbeans with Apache License 2.0 | 5 votes |
private void checkGroupUseTrailingCommas() { if (!lastUseStatementParts.isEmpty()) { BaseDocument document = GsfUtilities.getDocument(fileObject, true); if (document == null) { return; } document.readLock(); try { TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, 0); if (ts == null) { return; } lastUseStatementParts.forEach((lastUseStatementPart) -> { if (CancelSupport.getDefault().isCancelled()) { return; } ts.move(lastUseStatementPart.getEndOffset()); if (ts.moveNext()) { Token<? extends PHPTokenId> token = LexUtilities.findNext(ts, Arrays.asList(PHPTokenId.WHITESPACE)); if (token == null) { return; } if (token.id() == PHPTokenId.PHP_TOKEN && TokenUtilities.textEquals(token.text(), ",")) { // NOI18N createError(lastUseStatementPart); } } }); } finally { document.readUnlock(); lastUseStatementParts.clear(); } } }
Example 14
Source File: DeclareStrictTypesSuggestion.java From netbeans with Apache License 2.0 | 5 votes |
private FixInfo createFixInfo(BaseDocument doc, OffsetRange lineBounds, int caretOffset) { boolean foundOpenTag = false; int insertOffset = 0; int phpOpenTagCount = 0; doc.readLock(); try { TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(doc, caretOffset); if (ts != null) { ts.move(lineBounds.getStart()); // check the php tag on the caret line while (ts.moveNext() && ts.offset() < lineBounds.getEnd()) { PHPTokenId id = ts.token().id(); if (id == PHPTokenId.PHP_OPENTAG && TokenUtilities.equals(ts.token().text(), "<?php")) { // NOI18N foundOpenTag = true; break; } } // check all php open tags if (foundOpenTag) { ts.move(0); while (ts.moveNext()) { if (ts.token().id() == PHPTokenId.PHP_OPENTAG) { if (insertOffset == 0 && TokenUtilities.equals(ts.token().text(), "<?php")) { // NOI18N insertOffset = ts.offset() + "<?php".length(); // NOI18N } phpOpenTagCount++; } } } } } finally { doc.readUnlock(); } return new FixInfo(foundOpenTag, insertOffset, phpOpenTagCount); }
Example 15
Source File: DocRenderer.java From netbeans with Apache License 2.0 | 5 votes |
@CheckForNull private PHPDocBlock getPhpDocBlock(final PhpElement phpElement) { if (!canBeProcessed(phpElement)) { return null; } FileObject fileObject = phpElement.getFileObject(); BaseDocument document = GsfUtilities.getDocument(fileObject, true); if (document != null) { document.readLock(); try { int offset = phpElement.getOffset(); TokenSequence<PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, offset); if (ts != null) { ts.move(offset); if (ts.movePrevious()) { List<PHPTokenId> lookfor = Arrays.asList( PHPTokenId.PHPDOC_COMMENT, PHPTokenId.PHP_CURLY_OPEN, PHPTokenId.PHP_CURLY_CLOSE, PHPTokenId.PHP_SEMICOLON ); Token<? extends PHPTokenId> token = LexUtilities.findPreviousToken(ts, lookfor); if (token != null && token.id() == PHPTokenId.PHPDOC_COMMENT) { PHPDocCommentParser phpDocCommentParser = new PHPDocCommentParser(); return phpDocCommentParser.parse( ts.offset() - 3, // - /** ts.offset() + token.length(), token.text().toString() ); } } } } finally { document.readUnlock(); } } return null; }
Example 16
Source File: LexUtilities.java From netbeans with Apache License 2.0 | 5 votes |
/** Find the Groovy token sequence (in case it's embedded in something else at the top level. */ @SuppressWarnings("unchecked") public static TokenSequence<GroovyTokenId> getGroovyTokenSequence(Document doc, int offset) { final BaseDocument baseDocument = (BaseDocument) doc; try { baseDocument.readLock(); return getGroovyTokenSequence(TokenHierarchy.get(doc), offset); } finally { baseDocument.readUnlock(); } }
Example 17
Source File: IntroduceSuggestion.java From netbeans with Apache License 2.0 | 4 votes |
/** * Get an offset after a use trait statement. * <b>NOTE:</b>This method should be used when a type doesn't have * constants. If the use trait statement is after fields or methods, the * offset after the open curry for type is returned. * * @param document the document * @param typeScope the type scope * @return The offset after the last use trait statement if traits are used, * otherwise the offset after the open curly for the type */ private static int getOffsetAfterUseTrait(BaseDocument document, TypeScope typeScope) { OffsetRange blockRange = typeScope.getBlockRange(); int offset = blockRange.getEnd() - 1; // before close curly "}" Collection<ModelElement> elements = new HashSet<>(); elements.addAll(typeScope.getDeclaredMethods()); if (typeScope instanceof ClassScope) { elements.addAll(((ClassScope) typeScope).getDeclaredFields()); } else if (typeScope instanceof TraitScope) { elements.addAll(((TraitScope) typeScope).getDeclaredFields()); } for (ModelElement element : elements) { int newOffset = element.getOffset(); if (newOffset < offset) { offset = newOffset; } } document.readLock(); try { TokenSequence<? extends PHPTokenId> ts = LexUtilities.getPHPTokenSequence(document, offset); if (ts != null) { ts.move(offset); if (ts.movePrevious()) { // find the following cases : "use TraitA;", "use TraitA{}" and "TypeName {" List<PHPTokenId> lookfor = Arrays.asList( PHPTokenId.PHP_SEMICOLON, PHPTokenId.PHP_CURLY_CLOSE, PHPTokenId.PHP_CURLY_OPEN ); Token<? extends PHPTokenId> previousToken = LexUtilities.findPreviousToken(ts, lookfor); if (previousToken != null) { return ts.offset() + previousToken.length(); } } } } finally { document.readUnlock(); } return offset; }
Example 18
Source File: CodeFoldingSideBar.java From netbeans with Apache License 2.0 | 4 votes |
private void performActionAt(Mark mark, int mouseY) throws BadLocationException { if (mark != null) { return; } BaseDocument bdoc = Utilities.getDocument(component); BaseTextUI textUI = (BaseTextUI)component.getUI(); View rootView = Utilities.getDocumentView(component); if (rootView == null) return; bdoc.readLock(); try { int yOffset = textUI.getPosFromY(mouseY); FoldHierarchy hierarchy = FoldHierarchy.get(component); hierarchy.lock(); try { Fold f = FoldUtilities.findOffsetFold(hierarchy, yOffset); if (f == null) { return; } if (f.isCollapsed()) { LOG.log(Level.WARNING, "Clicked on a collapsed fold {0} at {1}", new Object[] { f, mouseY }); return; } int startOffset = f.getStartOffset(); int endOffset = f.getEndOffset(); int startY = textUI.getYFromPos(startOffset); int nextLineOffset = Utilities.getRowStart(bdoc, startOffset, 1); int nextY = textUI.getYFromPos(nextLineOffset); if (mouseY >= startY && mouseY <= nextY) { LOG.log(Level.FINEST, "Starting line clicked, ignoring. MouseY={0}, startY={1}, nextY={2}", new Object[] { mouseY, startY, nextY }); return; } startY = textUI.getYFromPos(endOffset); nextLineOffset = Utilities.getRowStart(bdoc, endOffset, 1); nextY = textUI.getYFromPos(nextLineOffset); if (mouseY >= startY && mouseY <= nextY) { // the mouse can be positioned above the marker (the fold found above), or // below it; in that case, the immediate enclosing fold should be used - should be the fold // that corresponds to the nextLineOffset, if any int h2 = (startY + nextY) / 2; if (mouseY >= h2) { Fold f2 = f; f = FoldUtilities.findOffsetFold(hierarchy, nextLineOffset); if (f == null) { // fold does not exist for the position below end-of-fold indicator return; } } } LOG.log(Level.FINEST, "Collapsing fold: {0}", f); hierarchy.collapse(f); } finally { hierarchy.unlock(); } } finally { bdoc.readUnlock(); } }
Example 19
Source File: WhereUsedElement.java From netbeans with Apache License 2.0 | 4 votes |
public static WhereUsedElement create(FileObject fileObject, Entry entry, ElementKind kind, boolean related) { Icon icon = UiUtils.getElementIcon(kind, Collections.<Modifier>emptyList()); String name = entry.getName(); OffsetRange range = entry.getDocumentRange(); int start = range.getStart(); int end = range.getEnd(); int sta = start; int en = start; // ! Same line as start String content = null; BaseDocument bdoc = GsfUtilities.getDocument(fileObject, true); try { bdoc.readLock(); // I should be able to just call tree.getInfo().getText() to get cached // copy - but since I'm playing fast and loose with compilationinfos // for for example find subclasses (using a singly dummy FileInfo) I need // to read it here instead content = bdoc.getText(0, bdoc.getLength()); sta = Utilities.getRowFirstNonWhite(bdoc, start); if (sta == -1) { sta = Utilities.getRowStart(bdoc, start); } en = Utilities.getRowLastNonWhite(bdoc, start); if (en == -1) { en = Utilities.getRowEnd(bdoc, start); } else { // Last nonwhite - left side of the last char, not inclusive en++; } // Sometimes the node we get from the AST is for the whole block // (e.g. such as the whole class), not the argument node. This happens // for example in Find Subclasses out of the index. In this case if (end > en) { end = start + name.length(); if (end > bdoc.getLength()) { end = bdoc.getLength(); } } } catch (Exception ex) { Exceptions.printStackTrace(ex); } finally { bdoc.readUnlock(); } StringBuilder sb = new StringBuilder(); if (end < sta) { // XXX Shouldn't happen, but I still have AST offset errors sta = end; } if (start < sta) { // XXX Shouldn't happen, but I still have AST offset errors start = sta; } if (en < end) { // XXX Shouldn't happen, but I still have AST offset errors en = end; } sb.append(encodeCharRefs(content.subSequence(sta, start).toString())); sb.append("<b>"); // NOI18N sb.append(content.subSequence(start, end)); sb.append("</b>"); // NOI18N sb.append(encodeCharRefs(content.subSequence(end, en).toString())); if(!related) { sb.append(NbBundle.getMessage(WhereUsedElement.class, "MSG_Unrelated_Where_Used_Occurance")); //NOI18N } CloneableEditorSupport ces = GsfUtilities.findCloneableEditorSupport(fileObject); PositionRef ref1 = ces.createPositionRef(start, Bias.Forward); PositionRef ref2 = ces.createPositionRef(end, Bias.Forward); PositionBounds bounds = new PositionBounds(ref1, ref2); return new WhereUsedElement(bounds, sb.toString().trim(), fileObject, name, new OffsetRange(start, end), icon); }
Example 20
Source File: CompletionHandler.java From netbeans with Apache License 2.0 | 4 votes |
@Override public CodeCompletionResult complete(CodeCompletionContext completionContext) { ParserResult parserResult = completionContext.getParserResult(); String prefix = completionContext.getPrefix(); // Documentation says that @NonNull is return from getPrefix() but it's not true // Invoking "this.^" makes the return value null if (prefix == null) { prefix = ""; } int lexOffset = completionContext.getCaretOffset(); int astOffset = ASTUtils.getAstOffset(parserResult, lexOffset); int anchor = lexOffset - prefix.length(); LOG.log(Level.FINEST, "complete(...), prefix : {0}", prefix); // NOI18N LOG.log(Level.FINEST, "complete(...), lexOffset : {0}", lexOffset); // NOI18N LOG.log(Level.FINEST, "complete(...), astOffset : {0}", astOffset); // NOI18N final Document document = parserResult.getSnapshot().getSource().getDocument(false); if (document == null) { return CodeCompletionResult.NONE; } final BaseDocument doc = (BaseDocument) document; doc.readLock(); // Read-lock due to Token hierarchy use try { CompletionContext context = new CompletionContext(parserResult, prefix, anchor, lexOffset, astOffset, doc); context.init(); // if we are above a package statement or inside a comment there's no completion at all. if (context.location == CaretLocation.ABOVE_PACKAGE || context.location == CaretLocation.INSIDE_COMMENT) { return new DefaultCompletionResult(Collections.<CompletionProposal>emptyList(), false); } ProposalsCollector proposalsCollector = new ProposalsCollector(context); if (ContextHelper.isVariableNameDefinition(context) || ContextHelper.isFieldNameDefinition(context)) { proposalsCollector.completeNewVars(context); } else { if (!(context.location == CaretLocation.OUTSIDE_CLASSES || context.location == CaretLocation.INSIDE_STRING)) { proposalsCollector.completePackages(context); proposalsCollector.completeTypes(context); } if (!context.isBehindImportStatement()) { if (context.location != CaretLocation.INSIDE_STRING) { proposalsCollector.completeKeywords(context); proposalsCollector.completeMethods(context); } proposalsCollector.completeFields(context); proposalsCollector.completeLocalVars(context); } if (context.location == CaretLocation.INSIDE_CONSTRUCTOR_CALL) { if (ContextHelper.isAfterComma(context) || ContextHelper.isAfterLeftParenthesis(context)) { proposalsCollector.completeNamedParams(context); } } } proposalsCollector.completeCamelCase(context); return new GroovyCompletionResult(proposalsCollector.getCollectedProposals(), context); } finally { doc.readUnlock(); } }