Java Code Examples for org.eclipse.ui.texteditor.IDocumentProvider#disconnect()

The following examples show how to use org.eclipse.ui.texteditor.IDocumentProvider#disconnect() . 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: TestEditor.java    From ermasterr with Apache License 2.0 6 votes vote down vote up
/**
 * Disposes of the connection with the document provider. Subclasses may
 * extend.
 * 
 * @since 3.0
 */
protected void disposeDocumentProvider() {
    final IDocumentProvider provider = getDocumentProvider();
    if (provider != null) {

        final IEditorInput input = getEditorInput();
        if (input != null)
            provider.disconnect(input);

        if (fElementStateListener != null) {
            provider.removeElementStateListener(fElementStateListener);
            fElementStateListener = null;
        }

    }
    fImplicitDocumentProvider = null;
}
 
Example 2
Source File: TLAHyperlinkDetector.java    From tlaplus with MIT License 6 votes vote down vote up
private int[] getDocumentAndRegion(SyntaxTreeNode csNode, IDocumentProvider documentProvider, IEditorInput editorInput)
		throws CoreException {
	IDocument document;
	// connect to the resource
	try {
		documentProvider.connect(editorInput);
		document = documentProvider.getDocument(editorInput);
	} finally {
		/*
		 * Once the document has been retrieved, the document provider is not needed.
		 * Always disconnect it to avoid a memory leak.
		 * 
		 * Keeping it connected only seems to provide synchronization of the document
		 * with file changes. That is not necessary in this context.
		 */
		documentProvider.disconnect(editorInput);
	}

	return getRegion(csNode, document);
}
 
Example 3
Source File: EditorUtils.java    From typescript.java with MIT License 6 votes vote down vote up
public static Position getPosition(IFile file, TextSpan textSpan) throws BadLocationException {
	ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
	ITextFileBuffer buffer = bufferManager.getTextFileBuffer(file.getLocation(), LocationKind.IFILE);
	if (buffer != null) {
		return getPosition(buffer.getDocument(), textSpan);
	}
	IDocumentProvider provider = new TextFileDocumentProvider();
	try {
		provider.connect(file);
		IDocument document = provider.getDocument(file);
		if (document != null) {
			return getPosition(document, textSpan);
		}
	} catch (CoreException e) {
	} finally {
		provider.disconnect(file);
	}
	return null;
}
 
Example 4
Source File: EditorManager.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
private String doGetContent(saros.filesystem.IFile wrappedFile) {
  IFile file = ((EclipseFileImpl) wrappedFile).getDelegate();
  FileEditorInput input = new FileEditorInput(file);

  IDocumentProvider provider = EditorAPI.connect(input);

  if (provider == null) {
    log.warn("Failed to retrieve the content of " + wrappedFile);
    return null;
  }

  IDocument doc = provider.getDocument(input);
  String content = (doc != null) ? doc.get() : null;

  provider.disconnect(input);

  return content;
}
 
Example 5
Source File: TestEditor.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
/**
 * Disposes of the connection with the document provider. Subclasses may
 * extend.
 * 
 * @since 3.0
 */
protected void disposeDocumentProvider() {
	IDocumentProvider provider = getDocumentProvider();
	if (provider != null) {

		IEditorInput input = getEditorInput();
		if (input != null)
			provider.disconnect(input);

		if (fElementStateListener != null) {
			provider.removeElementStateListener(fElementStateListener);
			fElementStateListener = null;
		}

	}
	fImplicitDocumentProvider = null;
}
 
Example 6
Source File: N4JSStackTraceHyperlink.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void revealLocationInFile(String typeName, int line, int column, IEditorPart editorPart)
		throws CoreException {
	if (editorPart instanceof ITextEditor && line >= 0) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocumentProvider provider = textEditor.getDocumentProvider();
		IEditorInput editorInput = editorPart.getEditorInput();
		provider.connect(editorInput);
		IDocument document = provider.getDocument(editorInput);
		try {
			IRegion regionOfLine = document.getLineInformation(line);
			// only used to reveal the location
			textEditor.selectAndReveal(regionOfLine.getOffset(), regionOfLine.getLength());
			int startOffset = regionOfLine.getOffset() + column;
			int length = regionOfLine.getLength() - column;
			if (startOffset >= document.getLength()) {
				startOffset = document.getLength() - 1;
			}
			if (length + startOffset >= document.getLength()) {
				length = document.getLength() - startOffset - 1;
			}
			textEditor.setHighlightRange(startOffset, length, true);
		} catch (BadLocationException e) {
			MessageDialog.openInformation(N4JSGracefulActivator.getActiveWorkbenchShell(),
					ConsoleMessages.msgInvalidLineNumberTitle(),
					ConsoleMessages.msgInvalidLineNumberIn(
							(line + 1) + "",
							typeName));
		}
		provider.disconnect(editorInput);
	}
}
 
Example 7
Source File: TestResultHyperlink.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void revealLocationInFile(IEditorPart editorPart)
		throws CoreException {
	if (editorPart instanceof ITextEditor && locationText.line > 0) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocumentProvider provider = textEditor.getDocumentProvider();
		IEditorInput editorInput = editorPart.getEditorInput();
		provider.connect(editorInput);
		IDocument document = provider.getDocument(editorInput);
		try {
			IRegion regionOfLine = document.getLineInformation(locationText.line - 1);
			// only used to reveal the location
			textEditor.selectAndReveal(regionOfLine.getOffset(), regionOfLine.getLength());
			int startOffset = regionOfLine.getOffset() + locationText.column - 1;
			int length = regionOfLine.getLength() - locationText.column;
			if (startOffset >= document.getLength()) {
				startOffset = document.getLength() - 1;
			}
			if (length + startOffset >= document.getLength()) {
				length = document.getLength() - startOffset - 1;
			}
			textEditor.setHighlightRange(startOffset, length, true);
		} catch (BadLocationException e) {
			MessageDialog.openInformation(N4JSGracefulActivator.getActiveWorkbenchShell(),
					ConsoleMessages.msgInvalidLineNumberTitle(),
					ConsoleMessages.msgInvalidLineNumberIn(
							(locationText.line) + "",
							locationText.fileName));
		}
		provider.disconnect(editorInput);
	}
}
 
Example 8
Source File: JavaStatusContextViewer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument getDocument(IDocumentProvider provider, IEditorInput input) {
	if (input == null)
		return null;
	IDocument result= null;
	try {
		provider.connect(input);
		result= provider.getDocument(input);
	} catch (CoreException e) {
	} finally {
		provider.disconnect(input);
	}
	return result;
}
 
Example 9
Source File: UndoManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
protected void fireActivity(TextEditActivity activity) {

    expectedActivities.add(activity);

    List<ITextOperation> textOps = activity.toOperation().getTextOperations();

    org.eclipse.core.resources.IFile file = ((EclipseFileImpl) currentActiveEditor).getDelegate();

    FileEditorInput input = new FileEditorInput(file);
    IDocumentProvider provider = EditorAPI.connect(input);

    if (provider == null) return;

    try {

      IDocument doc = provider.getDocument(input);
      if (doc == null) {
        log.error(
            "Could not connect to a document provider on file '" + file.toString() + "':",
            new StackTrace());
        return;
      }

      for (ITextOperation textOp : textOps) {
        int offset = EditorAPI.calculateOffset(doc, textOp.getStartPosition());

        try {
          if (textOp instanceof DeleteOperation) doc.replace(offset, textOp.getText().length(), "");
          if (textOp instanceof InsertOperation) doc.replace(offset, 0, textOp.getText());
        } catch (BadLocationException e) {
          log.error("Invalid location for " + textOp);
        }
      }
    } finally {
      provider.disconnect(input);
    }
  }
 
Example 10
Source File: EditorManager.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
private void execTextEdit(TextEditActivity textEdit) {

    log.trace(".execTextEdit invoked");

    saros.filesystem.IFile fileWrapper = textEdit.getResource();
    IFile file = ((EclipseFileImpl) fileWrapper).getDelegate();

    if (!file.exists()) {
      log.error("TextEditActivity refers to file which" + " is not available locally: " + textEdit);
      // TODO A consistency check can be started here
      return;
    }

    User user = textEdit.getSource();

    FileEditorInput input = new FileEditorInput(file);
    IDocumentProvider provider = EditorAPI.connect(input);

    if (provider == null) {
      // TODO Trigger a consistency recovery
      return;
    }

    try {
      IDocument doc = provider.getDocument(input);
      if (doc == null) {
        log.error(
            "Could not connect document provider for file: " + file.toString(), new StackTrace());
        // TODO Trigger a consistency recovery
        return;
      }

      int offset = EditorAPI.calculateOffset(doc, textEdit.getStartPosition());

      String replacedText = textEdit.getReplacedText();
      String text = textEdit.getNewText();

      String lineSeparator = FileUtil.getLineSeparator(file);

      String denormalizedReplacedText =
          LineSeparatorNormalizationUtil.revertNormalization(replacedText, lineSeparator);
      String denormalizedNewText =
          LineSeparatorNormalizationUtil.revertNormalization(text, lineSeparator);

      /*
       * Disable documentListener temporarily to avoid being notified of the
       * change, otherwise this would lead to an infinite activity sending,
       * crashing the application
       */
      editorPool.setDocumentListenerEnabled(false);

      replaceText(fileWrapper, offset, denormalizedReplacedText, denormalizedNewText, user, doc);

      editorPool.setDocumentListenerEnabled(true);

    } finally {
      provider.disconnect(input);
    }

    /*
     * TODO Find out whether this is actually necessary. If we receive a
     * TextSelectionActivity for each cursor movement, then we don't need to
     * listen for edits as well.
     */
    /*
     * If the text edit ends in the visible region of a local editor, set
     * the cursor annotation.
     *
     * TODO Performance optimization in case of batch operation might make
     * sense. Problem: How to recognize batch operations?
     */
    for (IEditorPart editorPart : editorPool.getEditors(fileWrapper)) {
      ITextViewer viewer = EditorAPI.getViewer(editorPart);
      if (viewer == null) {
        // No text viewer for the editorPart found.
        continue;
      }

      TextPosition cursorPosition = textEdit.getNewEndPosition();
      int cursorLine = cursorPosition.getLineNumber();

      if (viewer.getTopIndex() <= cursorLine && cursorLine <= viewer.getBottomIndex()) {

        TextSelection cursorSelection = new TextSelection(cursorPosition, cursorPosition);

        locationAnnotationManager.setSelection(editorPart, cursorSelection, user);
      }
    }

    // inform all registered ISharedEditorListeners about this text edit
    editorListenerDispatch.textEdited(textEdit);
  }
 
Example 11
Source File: EditorManager.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Programmatically saves the given editor IF and only if the file is registered as a connected
 * file.
 *
 * <p>Calling this method will trigger a call to all registered SharedEditorListeners (independent
 * of the success of this method) BEFORE the file is actually saved.
 *
 * <p>Calling this method will NOT trigger a {@link EditorActivity} of type Save to be sent to the
 * other clients.
 *
 * @param wrappedFile the file that is supposed to be saved to disk.
 * @swt This method must be called from the SWT thread
 * @nonReentrant This method cannot be called twice at the same time.
 */
public void saveEditor(saros.filesystem.IFile wrappedFile) {
  checkThreadAccess();

  IFile file = ((EclipseFileImpl) wrappedFile).getDelegate();

  log.trace(".saveEditor (" + file.getName() + ") invoked");

  if (!file.exists()) {
    log.warn("File not found for saving: " + wrappedFile.toString(), new StackTrace());
    return;
  }

  FileEditorInput input = new FileEditorInput(file);
  IDocumentProvider provider = EditorAPI.connect(input);

  if (provider == null) return;

  if (!provider.canSaveDocument(input)) {
    /*
     * This happens when a file which is already saved is saved again by
     * a user.
     */
    log.debug(".saveEditor File " + file.getName() + " does not need to be saved");
    provider.disconnect(input);
    return;
  }

  log.trace(".saveEditor File " + file.getName() + " will be saved");

  final boolean isConnected = isManaged(file);

  /*
   * connect to the file so the SharedResourceManager /
   * ProjectDeltaVisitor will ignore the file change because it is
   * possible that no editor is open for this file
   */
  if (!isConnected) connect(file);

  IDocument doc = provider.getDocument(input);

  // TODO Why do we need to connect to the annotation model here?
  IAnnotationModel model = provider.getAnnotationModel(input);
  if (model != null) model.connect(doc);

  log.trace(".saveEditor Annotations on the IDocument are set");

  editorPool.setElementStateListenerEnabled(false);

  try {
    provider.saveDocument(new NullProgressMonitor(), input, doc, true);
    log.debug("Saved document: " + wrappedFile);
  } catch (CoreException e) {
    log.error("Failed to save document: " + wrappedFile, e);
  }

  editorPool.setElementStateListenerEnabled(true);

  if (model != null) model.disconnect(doc);

  provider.disconnect(input);

  if (!isConnected) disconnect(file);
}
 
Example 12
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Can be called instead of {@link #getDocumentProvider(IEditorInput)} and {@link
 * IDocumentProvider#disconnect(Object) provider.disconnect()}, in case there is no {@link
 * IDocumentProvider} instance at hand (e.g. if <code>connect()</code> and <code>disconnect()
 * </code> are called in different contexts).
 */
public static void disconnect(IEditorInput input) {
  IDocumentProvider documentProvider = EditorAPI.getDocumentProvider(input);

  documentProvider.disconnect(input);
}