Search in sources :

Example 26 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class JavaDebuggerUtils method findFqnByPosition.

/**
     * Return nested class fqn if line with number {@code lineNumber} contains such element, otherwise return outer class fqn.
     *
     * @param projectPath
     *         project path which contains class with {@code outerClassFqn}
     * @param outerClassFqn
     *         fqn outer class
     * @param lineNumber
     *         line position to search
     * @throws DebuggerException
     */
public String findFqnByPosition(String projectPath, String outerClassFqn, int lineNumber) throws DebuggerException {
    if (projectPath == null) {
        return outerClassFqn;
    }
    IJavaProject project = MODEL.getJavaProject(projectPath);
    IType outerClass;
    IMember iMember;
    try {
        outerClass = project.findType(outerClassFqn);
        if (outerClass == null) {
            return outerClassFqn;
        }
        String source;
        if (outerClass.isBinary()) {
            IClassFile classFile = outerClass.getClassFile();
            source = classFile.getSource();
        } else {
            ICompilationUnit unit = outerClass.getCompilationUnit();
            source = unit.getSource();
        }
        Document document = new Document(source);
        IRegion region = document.getLineInformation(lineNumber);
        int start = region.getOffset();
        int end = start + region.getLength();
        iMember = binSearch(outerClass, start, end);
    } catch (JavaModelException e) {
        throw new DebuggerException(format("Unable to find source for class with fqn '%s' in the project '%s'", outerClassFqn, project), e);
    } catch (BadLocationException e) {
        throw new DebuggerException("Unable to calculate breakpoint location", e);
    }
    if (iMember instanceof IType) {
        return ((IType) iMember).getFullyQualifiedName();
    }
    if (iMember != null) {
        return iMember.getDeclaringType().getFullyQualifiedName();
    }
    return outerClassFqn;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaProject(org.eclipse.jdt.core.IJavaProject) IClassFile(org.eclipse.jdt.core.IClassFile) DebuggerException(org.eclipse.che.api.debugger.server.exceptions.DebuggerException) Document(org.eclipse.jface.text.Document) IMember(org.eclipse.jdt.core.IMember) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException) IType(org.eclipse.jdt.core.IType)

Example 27 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class DocumentChange method performEdits.

/*
	 * @see org.eclipse.ltk.core.refactoring.TextChange#performEdits(org.eclipse.jface.text.IDocument)
	 * @since 3.6
	 */
protected UndoEdit performEdits(final IDocument document) throws BadLocationException, MalformedTreeException {
    ITextFileBufferManager fileBufferManager = FileBuffers.getTextFileBufferManager();
    ITextFileBuffer fileBuffer = fileBufferManager.getTextFileBuffer(document);
    if (fileBuffer == null || !fileBuffer.isSynchronizationContextRequested()) {
        return super.performEdits(document);
    }
    /** The lock for waiting for computation in the UI thread to complete. */
    final Lock completionLock = new Lock();
    final UndoEdit[] result = new UndoEdit[1];
    final BadLocationException[] exception = new BadLocationException[1];
    Runnable runnable = new Runnable() {

        public void run() {
            synchronized (completionLock) {
                try {
                    result[0] = DocumentChange.super.performEdits(document);
                } catch (BadLocationException e) {
                    exception[0] = e;
                } finally {
                    completionLock.fDone = true;
                    completionLock.notifyAll();
                }
            }
        }
    };
    synchronized (completionLock) {
        fileBufferManager.execute(runnable);
        while (!completionLock.fDone) {
            try {
                completionLock.wait(500);
            } catch (InterruptedException x) {
            }
        }
    }
    if (exception[0] != null) {
        throw exception[0];
    }
    return result[0];
}
Also used : ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) UndoEdit(org.eclipse.text.edits.UndoEdit) BadLocationException(org.eclipse.jface.text.BadLocationException) Lock(org.eclipse.ltk.internal.core.refactoring.Lock)

Example 28 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class MultiStateTextFileChange method performChanges.

/**
	 * Performs the changes on the specified document.
	 *
	 * @param document
	 *            the document to perform the changes on
	 * @param undoList
	 *            the undo list, or <code>null</code> to discard the undos
	 * @param preview
	 *            <code>true</code> if the changes are performed for preview,
	 *            <code>false</code> otherwise
	 * @throws BadLocationException
	 *             if the edit tree could not be applied
	 */
private void performChanges(final IDocument document, final LinkedList undoList, final boolean preview) throws BadLocationException {
    if (!fBuffer.isSynchronizationContextRequested()) {
        performChangesInSynchronizationContext(document, undoList, preview);
        return;
    }
    ITextFileBufferManager fileBufferManager = FileBuffers.getTextFileBufferManager();
    /** The lock for waiting for computation in the UI thread to complete. */
    final Lock completionLock = new Lock();
    final BadLocationException[] exception = new BadLocationException[1];
    Runnable runnable = new Runnable() {

        public void run() {
            synchronized (completionLock) {
                try {
                    performChangesInSynchronizationContext(document, undoList, preview);
                } catch (BadLocationException e) {
                    exception[0] = e;
                } finally {
                    completionLock.fDone = true;
                    completionLock.notifyAll();
                }
            }
        }
    };
    synchronized (completionLock) {
        fileBufferManager.execute(runnable);
        while (!completionLock.fDone) {
            try {
                completionLock.wait(500);
            } catch (InterruptedException x) {
            }
        }
    }
    if (exception[0] != null) {
        throw exception[0];
    }
}
Also used : ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) BadLocationException(org.eclipse.jface.text.BadLocationException) Lock(org.eclipse.ltk.internal.core.refactoring.Lock)

Example 29 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class MultiStateTextFileChange method getPreviewContent.

/*
	 * @see org.eclipse.ltk.core.refactoring.TextEditBasedChange#getPreviewContent(org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup[],org.eclipse.jface.text.IRegion,boolean,int,org.eclipse.core.runtime.IProgressMonitor)
	 */
public final String getPreviewContent(final TextEditBasedChangeGroup[] groups, final IRegion region, final boolean expand, final int surround, final IProgressMonitor monitor) throws CoreException {
    final Set cachedGroups = new HashSet(Arrays.asList(groups));
    final IDocument document = new Document(getCurrentDocument(monitor).get());
    // Marks the region in the document to be previewed
    final Position range = new Position(region.getOffset(), region.getLength());
    try {
        ComposableBufferChange change = null;
        final TextEditBasedChangeGroup[] changedGroups = getChangeGroups();
        LinkedList compositeUndo = new LinkedList();
        for (int index = 0; index < fChanges.size(); index++) {
            change = (ComposableBufferChange) fChanges.get(index);
            TextEdit copy = null;
            try {
                // Have to use a copy
                fCopier = new TextEditCopier(change.getEdit());
                copy = fCopier.perform();
                // Create a mapping from the copied edits to its originals
                final Map originalMap = new HashMap();
                for (final Iterator outer = change.getGroups().iterator(); outer.hasNext(); ) {
                    final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) outer.next();
                    for (final Iterator inner = group.getCachedEdits().iterator(); inner.hasNext(); ) {
                        final TextEdit originalEdit = (TextEdit) inner.next();
                        final TextEdit copiedEdit = fCopier.getCopy(originalEdit);
                        if (copiedEdit != null)
                            originalMap.put(copiedEdit, originalEdit);
                        else
                            //$NON-NLS-1$
                            RefactoringCorePlugin.logErrorMessage("Could not find a copy for the indexed text edit " + originalEdit.toString());
                    }
                }
                final ComposableBufferChangeGroup[] currentGroup = { null };
                final TextEdit[] currentEdit = { null };
                // Text edit processor which sets the change group and
                // current edit when processing
                final TextEditProcessor processor = new TextEditProcessor(document, copy, TextEdit.NONE) {

                    protected final boolean considerEdit(final TextEdit edit) {
                        final TextEdit originalEdit = (TextEdit) originalMap.get(edit);
                        if (originalEdit != null) {
                            currentEdit[0] = originalEdit;
                            boolean found = false;
                            for (int offset = 0; offset < changedGroups.length && !found; offset++) {
                                final ComposableBufferChangeGroup group = (ComposableBufferChangeGroup) changedGroups[offset];
                                if (group.containsEdit(originalEdit)) {
                                    currentGroup[0] = group;
                                    found = true;
                                }
                            }
                            if (!found)
                                currentGroup[0] = null;
                        } else if (!(edit instanceof MultiTextEdit)) {
                            //$NON-NLS-1$
                            RefactoringCorePlugin.logErrorMessage("Could not find the original of the copied text edit " + edit.toString());
                        }
                        return true;
                    }
                };
                final LinkedList eventUndos = new LinkedList();
                // Listener to record the undos on the document (offsets
                // relative to the document event)
                final IDocumentListener listener = new IDocumentListener() {

                    public final void documentAboutToBeChanged(final DocumentEvent event) {
                        final ComposableUndoEdit edit = new ComposableUndoEdit();
                        edit.setGroup(currentGroup[0]);
                        edit.setOriginal(currentEdit[0]);
                        edit.setUndo(createUndoEdit(document, event.getOffset(), event.getLength(), event.getText()));
                        eventUndos.addFirst(edit);
                    }

                    public final void documentChanged(final DocumentEvent event) {
                    // Do nothing
                    }
                };
                try {
                    // Record undos in LIFO order
                    document.addDocumentListener(listener);
                    processor.performEdits();
                } finally {
                    document.removeDocumentListener(listener);
                }
                compositeUndo.addFirst(eventUndos);
            } finally {
                fCopier = null;
            }
        }
        final IPositionUpdater positionUpdater = new IPositionUpdater() {

            public final void update(final DocumentEvent event) {
                final int eventOffset = event.getOffset();
                final int eventLength = event.getLength();
                final int eventOldEndOffset = eventOffset + eventLength;
                final String eventText = event.getText();
                final int eventNewLength = eventText == null ? 0 : eventText.length();
                final int eventNewEndOffset = eventOffset + eventNewLength;
                final int deltaLength = eventNewLength - eventLength;
                try {
                    final Position[] positions = event.getDocument().getPositions(COMPOSABLE_POSITION_CATEGORY);
                    for (int index = 0; index < positions.length; index++) {
                        final Position position = positions[index];
                        if (position.isDeleted())
                            continue;
                        final int offset = position.getOffset();
                        final int length = position.getLength();
                        final int end = offset + length;
                        if (offset > eventOldEndOffset) {
                            // position comes way after change - shift
                            position.setOffset(offset + deltaLength);
                        } else if (end < eventOffset) {
                        // position comes way before change - leave
                        // alone
                        } else if (offset == eventOffset) {
                        // leave alone, since the edits are overlapping
                        } else if (offset <= eventOffset && end >= eventOldEndOffset) {
                            // event completely internal to the position
                            // -
                            // adjust length
                            position.setLength(length + deltaLength);
                        } else if (offset < eventOffset) {
                            // event extends over end of position - include
                            // the
                            // replacement text into the position
                            position.setLength(eventNewEndOffset - offset);
                        } else if (end > eventOldEndOffset) {
                            // event extends from before position into it -
                            // adjust
                            // offset and length, including the replacement
                            // text into
                            // the position
                            position.setOffset(eventOffset);
                            int deleted = eventOldEndOffset - offset;
                            position.setLength(length - deleted + eventNewLength);
                        } else {
                            // event comprises the position - keep it at the
                            // same
                            // position, but always inside the replacement
                            // text
                            int newOffset = Math.min(offset, eventNewEndOffset);
                            int newEndOffset = Math.min(end, eventNewEndOffset);
                            position.setOffset(newOffset);
                            position.setLength(newEndOffset - newOffset);
                        }
                    }
                } catch (BadPositionCategoryException exception) {
                // ignore and return
                }
            }
        };
        try {
            document.addPositionCategory(COMPOSABLE_POSITION_CATEGORY);
            document.addPositionUpdater(positionUpdater);
            // Apply undos in LIFO order to get to the original document
            // Track the undos of edits which are in change groups to be
            // previewed and insert
            // Undo edits for them (corresponding to the linearized net
            // effect on the original document)
            final LinkedList undoQueue = new LinkedList();
            for (final Iterator outer = compositeUndo.iterator(); outer.hasNext(); ) {
                for (final Iterator inner = ((List) outer.next()).iterator(); inner.hasNext(); ) {
                    final ComposableUndoEdit edit = (ComposableUndoEdit) inner.next();
                    final ReplaceEdit undo = edit.getUndo();
                    final int offset = undo.getOffset();
                    final int length = undo.getLength();
                    final String text = undo.getText();
                    ComposableEditPosition position = new ComposableEditPosition();
                    if (cachedGroups.contains(edit.getGroup())) {
                        if (text == null || text.equals("")) {
                            //$NON-NLS-1$
                            position.offset = offset;
                            if (length != 0) {
                                // Undo is a delete, create final insert
                                // edit
                                position.length = 0;
                                position.setText(edit.getOriginalText());
                            } else
                                //$NON-NLS-1$
                                RefactoringCorePlugin.logErrorMessage("Dubious undo edit found: " + undo.toString());
                        } else if (length == 0) {
                            position.offset = offset;
                            // Undo is an insert, create final delete
                            // edit
                            //$NON-NLS-1$
                            position.setText("");
                            position.length = text.length();
                        } else {
                            // Undo is a replace, create final replace edit
                            position.offset = offset;
                            position.length = length;
                            position.setText(edit.getOriginalText());
                        }
                        document.addPosition(COMPOSABLE_POSITION_CATEGORY, position);
                    }
                    position = new ComposableEditPosition();
                    position.offset = undo.getOffset();
                    position.length = undo.getLength();
                    position.setText(undo.getText());
                    undoQueue.add(position);
                }
                for (final Iterator iterator = undoQueue.iterator(); iterator.hasNext(); ) {
                    final ComposableEditPosition position = (ComposableEditPosition) iterator.next();
                    document.replace(position.offset, position.length, position.getText());
                    iterator.remove();
                }
            }
            // Use a simple non deleting position updater for the range
            final IPositionUpdater markerUpdater = new NonDeletingPositionUpdater(MARKER_POSITION_CATEGORY);
            try {
                final Position[] positions = document.getPositions(COMPOSABLE_POSITION_CATEGORY);
                document.addPositionCategory(MARKER_POSITION_CATEGORY);
                document.addPositionUpdater(markerUpdater);
                document.addPosition(MARKER_POSITION_CATEGORY, range);
                for (int index = 0; index < positions.length; index++) {
                    final ComposableEditPosition position = (ComposableEditPosition) positions[index];
                    //$NON-NLS-1$
                    document.replace(position.offset, position.length, position.getText() != null ? position.getText() : "");
                }
            } catch (BadPositionCategoryException exception) {
                RefactoringCorePlugin.log(exception);
            } finally {
                document.removePositionUpdater(markerUpdater);
                try {
                    document.removePosition(MARKER_POSITION_CATEGORY, range);
                    document.removePositionCategory(MARKER_POSITION_CATEGORY);
                } catch (BadPositionCategoryException exception) {
                // Cannot happen
                }
            }
        } catch (BadPositionCategoryException exception) {
            RefactoringCorePlugin.log(exception);
        } finally {
            document.removePositionUpdater(positionUpdater);
            try {
                document.removePositionCategory(COMPOSABLE_POSITION_CATEGORY);
            } catch (BadPositionCategoryException exception) {
                RefactoringCorePlugin.log(exception);
            }
        }
        return getContent(document, new Region(range.offset, range.length), expand, surround);
    } catch (MalformedTreeException exception) {
        RefactoringCorePlugin.log(exception);
    } catch (BadLocationException exception) {
        RefactoringCorePlugin.log(exception);
    }
    return getPreviewDocument(monitor).get();
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) TextEditCopier(org.eclipse.text.edits.TextEditCopier) NonDeletingPositionUpdater(org.eclipse.ltk.internal.core.refactoring.NonDeletingPositionUpdater) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) Position(org.eclipse.jface.text.Position) IDocumentListener(org.eclipse.jface.text.IDocumentListener) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) DocumentEvent(org.eclipse.jface.text.DocumentEvent) LinkedList(java.util.LinkedList) IPositionUpdater(org.eclipse.jface.text.IPositionUpdater) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) BadPositionCategoryException(org.eclipse.jface.text.BadPositionCategoryException) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IRegion(org.eclipse.jface.text.IRegion) Region(org.eclipse.jface.text.Region) Map(java.util.Map) HashMap(java.util.HashMap) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 30 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class FastPartitioner method documentChanged2.

/**
	 * {@inheritDoc}
	 * <p>
	 * May be extended by subclasses.
	 * </p>
	 */
public IRegion documentChanged2(DocumentEvent e) {
    if (!fIsInitialized)
        return null;
    try {
        Assert.isTrue(e.getDocument() == fDocument);
        Position[] category = getPositions();
        IRegion line = fDocument.getLineInformationOfOffset(e.getOffset());
        int reparseStart = line.getOffset();
        int partitionStart = -1;
        String contentType = null;
        int newLength = e.getText() == null ? 0 : e.getText().length();
        int first = fDocument.computeIndexInCategory(fPositionCategory, reparseStart);
        if (first > 0) {
            TypedPosition partition = (TypedPosition) category[first - 1];
            if (partition.includes(reparseStart)) {
                partitionStart = partition.getOffset();
                contentType = partition.getType();
                if (e.getOffset() == partition.getOffset() + partition.getLength())
                    reparseStart = partitionStart;
                --first;
            } else if (reparseStart == e.getOffset() && reparseStart == partition.getOffset() + partition.getLength()) {
                partitionStart = partition.getOffset();
                contentType = partition.getType();
                reparseStart = partitionStart;
                --first;
            } else {
                partitionStart = partition.getOffset() + partition.getLength();
                contentType = IDocument.DEFAULT_CONTENT_TYPE;
            }
        }
        fPositionUpdater.update(e);
        for (int i = first; i < category.length; i++) {
            Position p = category[i];
            if (p.isDeleted) {
                rememberDeletedOffset(e.getOffset());
                break;
            }
        }
        clearPositionCache();
        category = getPositions();
        fScanner.setPartialRange(fDocument, reparseStart, fDocument.getLength() - reparseStart, contentType, partitionStart);
        int behindLastScannedPosition = reparseStart;
        IToken token = fScanner.nextToken();
        while (!token.isEOF()) {
            contentType = getTokenContentType(token);
            if (!isSupportedContentType(contentType)) {
                token = fScanner.nextToken();
                continue;
            }
            int start = fScanner.getTokenOffset();
            int length = fScanner.getTokenLength();
            behindLastScannedPosition = start + length;
            int lastScannedPosition = behindLastScannedPosition - 1;
            // remove all affected positions
            while (first < category.length) {
                TypedPosition p = (TypedPosition) category[first];
                if (lastScannedPosition >= p.offset + p.length || (p.overlapsWith(start, length) && (!fDocument.containsPosition(fPositionCategory, start, length) || !contentType.equals(p.getType())))) {
                    rememberRegion(p.offset, p.length);
                    fDocument.removePosition(fPositionCategory, p);
                    ++first;
                } else
                    break;
            }
            // area covered by the event, we are done
            if (fDocument.containsPosition(fPositionCategory, start, length)) {
                if (lastScannedPosition >= e.getOffset() + newLength)
                    return createRegion();
                ++first;
            } else {
                // insert the new type position
                try {
                    fDocument.addPosition(fPositionCategory, new TypedPosition(start, length, contentType));
                    rememberRegion(start, length);
                } catch (BadPositionCategoryException x) {
                } catch (BadLocationException x) {
                }
            }
            token = fScanner.nextToken();
        }
        first = fDocument.computeIndexInCategory(fPositionCategory, behindLastScannedPosition);
        clearPositionCache();
        category = getPositions();
        TypedPosition p;
        while (first < category.length) {
            p = (TypedPosition) category[first++];
            fDocument.removePosition(fPositionCategory, p);
            rememberRegion(p.offset, p.length);
        }
    } catch (BadPositionCategoryException x) {
    // should never happen on connected documents
    } catch (BadLocationException x) {
    } finally {
        clearPositionCache();
    }
    return createRegion();
}
Also used : TypedPosition(org.eclipse.jface.text.TypedPosition) Position(org.eclipse.jface.text.Position) TypedPosition(org.eclipse.jface.text.TypedPosition) BadPositionCategoryException(org.eclipse.jface.text.BadPositionCategoryException) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

BadLocationException (org.eclipse.jface.text.BadLocationException)133 IDocument (org.eclipse.jface.text.IDocument)58 IRegion (org.eclipse.jface.text.IRegion)43 Document (org.eclipse.jface.text.Document)26 Point (org.eclipse.swt.graphics.Point)17 CoreException (org.eclipse.core.runtime.CoreException)16 Position (org.eclipse.jface.text.Position)13 StyledString (org.eclipse.jface.viewers.StyledString)13 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)13 TemplateBuffer (org.eclipse.jface.text.templates.TemplateBuffer)12 TemplateException (org.eclipse.jface.text.templates.TemplateException)12 TextEdit (org.eclipse.text.edits.TextEdit)12 UndoEdit (org.eclipse.text.edits.UndoEdit)10 Region (org.eclipse.jface.text.Region)9 ASTNode (org.eclipse.jdt.core.dom.ASTNode)8 ArrayList (java.util.ArrayList)7 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)6 BadPositionCategoryException (org.eclipse.jface.text.BadPositionCategoryException)6 DefaultLineTracker (org.eclipse.jface.text.DefaultLineTracker)6