Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,24 @@ public static Builder create(ITextEditor editor, String source, UnifiedDiffMode
return new Builder(editor, source, mode);
}

/**
* Removes the unified diff display from the given editor without changing its
* document or computing another diff. Clears diff annotations and code minings,
* disposes diff toolbars and listeners, removes diff folds, restores the editor's
* navigation actions, and prevents a pending diff computation from restoring the display.
* Annotations unrelated to the diff are preserved.
* <p>
* Must be called on the editor's UI thread. Has no effect when the editor has no
* unified diff or no live text viewer. A new diff can be opened afterwards.
*
* @param editor the text editor whose unified diff display is removed
* @throws NullPointerException if the editor is <code>null</code>
* @since 3.13
*/
public static void dispose(ITextEditor editor) {
UnifiedDiffManager.dispose(Objects.requireNonNull(editor, "Editor cannot be null")); //$NON-NLS-1$
}

/**
* Identifies a built-in action of a unified diff toolbar, so that its text or
* image can be replaced. Which actions are shown depends on the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,8 @@ private static ToolbarActionPresentations toolbarActionPresentations(ITextViewer
* model, so the one installed on the viewer is used.
*/
public static IAnnotationModel annotationModelOf(ITextEditor editor) {
IAnnotationModel model = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
var provider = editor.getDocumentProvider();
IAnnotationModel model = provider != null ? provider.getAnnotationModel(editor.getEditorInput()) : null;
if (model != null) {
return model;
}
Expand All @@ -218,6 +219,28 @@ public static IAnnotationModel annotationModelOf(ITextEditor editor) {
: null;
}

public static void dispose(ITextEditor editor) {
ITextViewer viewer = editor.getAdapter(ITextViewer.class);
if (viewer == null) {
return;
}
StyledText textWidget = viewer.getTextWidget();
if (textWidget == null || textWidget.isDisposed()) {
return;
}
// Invalidate computations that yield to the UI event loop before installing
// their result, even when no diff has been displayed yet.
textWidget.setData(OPEN_REQUEST_KEY, null);
IAnnotationModel model = annotationModelOf(editor);
if (model != null) {
clearAll(viewer, model);
}
disposeUnifiedDiff(viewer, model, textWidget);
textWidget.setData(TOOLBAR_ACTION_PRESENTATIONS_KEY, null);
viewer.invalidateTextPresentation();
textWidget.redraw();
}

/**
* Installs an annotation model on the viewer of an editor whose document
* provider has none, so that the diffs have somewhere to be shown.
Expand Down Expand Up @@ -266,7 +289,7 @@ public static IStatus open(ITextEditor editor, String source, UnifiedDiffMode mo
IStatus status = open(viewer, leftDocument, model, file, source, mode, additionalActions, tokenComparatorFactory,
ignoreWhitespaceContributorFactory, compareFilters, leftContributor, rightContributor, ignoreWhiteSpace,
foldContextLines, toolbarActionPresentations, eventListener);
if (status.isOK()) {
if (status.isOK() && get(viewer) != null) {
registerCommandHandlers(editor, viewer, model);
}
return status;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,112 @@ private static void await(CountDownLatch latch, String message) {
}
}

@Test
public void testDisposeClearsDisplayAndAllowsReopening() throws Exception {
IAnnotationModel model = annotationModel();
Annotation unrelated = new Annotation("test.annotation", false, "Keep this annotation"); //$NON-NLS-1$ //$NON-NLS-2$
model.addAnnotation(unrelated, new Position(0, 4));
var actionBars = editor.getEditorSite().getActionBars();
var previousNext = actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId());
var previousPrevious = actionBars.getGlobalActionHandler(ActionFactory.PREVIOUS.getId());
StyledText tw = viewer().getTextWidget();
for (UnifiedDiffMode mode : List.of(UnifiedDiffMode.OVERLAY_MODE, UnifiedDiffMode.OVERLAY_READ_ONLY_MODE,
UnifiedDiffMode.REVERT_MODE, UnifiedDiffMode.REPLACE_MODE)) {
setEditorContent(LEFT);
assertTrue(UnifiedDiff.create(editor, RIGHT, mode).open().isOK());
assertNotSame(previousNext, actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId()));
assertNotNull(waitForLineHeaderAnnotation());
firePaint(tw);
var diff = UnifiedDiffManager.get(viewer()).get(0);
int miningLine = tw.getLineAtOffset(lineHeaderMiningFor(diff).getPosition().offset);
assertTrue(tw.getLineVerticalIndent(miningLine) > 0, "the diff mining must reserve height before disposal");
int diffLine = tw.getLineAtOffset(diff.leftStart);
fireMouseMove(tw, tw.getLinePixel(diffLine) + 2);
processEvents();
Composite allToolbar = (Composite) tw.getData(TOOLBAR_COMPOSITE_FOR_ALL_DIFFS_KEY);
Composite oneToolbar = (Composite) tw.getData(TOOLBAR_COMPOSITE_FOR_ONE_DIFF_KEY);
assertNotNull(allToolbar);
assertNotNull(oneToolbar);
String contentBeforeDispose = document().get();
boolean dirtyBeforeDispose = editor.isDirty();

UnifiedDiff.dispose(editor);
processEvents();
firePaint(tw);

assertNull(UnifiedDiffManager.get(viewer()), "disposal must release the manager state");
assertTrue(allToolbar.isDisposed());
assertTrue(oneToolbar.isDisposed());
assertEquals(0, tw.getLineVerticalIndent(miningLine), "disposal must clear the mining's reserved height");
assertEquals(contentBeforeDispose, document().get(), "disposal must preserve the current document");
assertEquals(dirtyBeforeDispose, editor.isDirty(), "disposal must preserve the editor's dirty state");
assertNotNull(model.getPosition(unrelated));
assertEquals(List.of(unrelated), annotations(model, "test.annotation")); //$NON-NLS-1$
assertEquals(0, countUnifiedDiffAnnotations(model));
assertSame(previousNext, actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId()));
assertSame(previousPrevious, actionBars.getGlobalActionHandler(ActionFactory.PREVIOUS.getId()));
assertEquals(0, tw.getTypedListeners(SWT.Paint, PaintListener.class)
.filter(listener -> listener.getClass().getName()
.equals(UnifiedDiffManager.class.getName() + "$UnifiedDiffPaintListener")).count()); //$NON-NLS-1$
assertEquals(0, tw.getTypedListeners(SWT.MouseMove, MouseMoveListener.class)
.filter(listener -> listener.getClass().getName()
.equals(UnifiedDiffManager.class.getName() + "$UnifiedDiffMouseMoveListener")).count()); //$NON-NLS-1$
UnifiedDiff.dispose(editor);
}
}

private static int countUnifiedDiffAnnotations(IAnnotationModel model) {
int count = 0;
for (Iterator<Annotation> it = model.getAnnotationIterator(); it.hasNext();) {
String type = it.next().getType();
if (type != null && type.startsWith("org.eclipse.compare.unifieddiff.")) { //$NON-NLS-1$
count++;
}
}
return count;
}

@Test
public void testDisposePreventsPendingComputationFromRestoringDisplay() {
CountDownLatch disposed = new CountDownLatch(1);
AtomicBoolean firstComparison = new AtomicBoolean(true);
var actionBars = editor.getEditorSite().getActionBars();
var previousNext = actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId());
IStatus status = UnifiedDiff.create(editor, RIGHT, UnifiedDiffMode.REPLACE_MODE)
.tokenComparatorFactory(text -> {
if (firstComparison.compareAndSet(true, false)) {
Display.getDefault().asyncExec(() -> {
UnifiedDiff.dispose(editor);
disposed.countDown();
});
await(disposed, "disposal must run while the diff computation is blocked");
}
return new CaseInsensitiveTokenComparator(text);
}).open();

assertTrue(status.isOK(), "the superseded open must return normally");
assertEquals(0, disposed.getCount());
processEvents();
assertNull(UnifiedDiffManager.get(viewer()));
assertEquals(0, countUnifiedDiffAnnotations(annotationModel()));
assertNull(viewer().getTextWidget().getData(TOOLBAR_COMPOSITE_FOR_ALL_DIFFS_KEY));
assertSame(previousNext, actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId()),
"the superseded open must not reinstall navigation handlers");
assertEquals(LEFT, document().get(), "the superseded replace-mode open must not change the document");
}

@Test
public void testDisposeWithoutDiffAndAfterClosingEditor() {
assertThrows(NullPointerException.class, () -> UnifiedDiff.dispose(null));
UnifiedDiff.dispose(editor);
UnifiedDiff.dispose(editor);
assertEquals(LEFT, document().get());
assertNull(UnifiedDiffManager.get(viewer()));
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(editor, false);
UnifiedDiff.dispose(editor);
editor = null;
}

/**
* Opening a second diff on the same editor must replace the first one instead
* of stacking annotations and diffs on top of each other.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
*******************************************************************************/
package org.eclipse.team.tests.ui;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
Expand All @@ -28,6 +30,7 @@
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModel;
Expand All @@ -37,6 +40,7 @@
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.texteditor.ITextEditor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -105,6 +109,34 @@ public void testAFoldComesBackWhenTheRegionIsExpanded() throws Exception {
"the fold of the editor must be usable again once nothing hides its first line");
}

@Test
public void testDisposeRemovesDiffFoldsAndRestoresEditorFoldsWithoutProviderModel() throws Exception {
IDocument document = numberedLines(100);
ProjectionAnnotationModel projectionModel = openViewer(document);
ProjectionAnnotation foldOfTheEditor = addFoldOfTheEditor(projectionModel, document, 10, 70);
UnifiedDiffManager.foldUnchangedRegions(viewer, document, List.of(changeOnLine(document, 60)), MODE, 3);
assertFalse(isInModel(projectionModel, foldOfTheEditor));
assertTrue(projectionModel.getAnnotationIterator().hasNext());
// An editor with no provider model uses the model installed on its viewer.
ITextEditor editor = (ITextEditor) Proxy.newProxyInstance(ITextEditor.class.getClassLoader(),
new Class<?>[] { ITextEditor.class }, (_, method, args) -> {
if (method.getName().equals("getAdapter") && args[0] == ITextViewer.class) { //$NON-NLS-1$
return viewer;
}
return null;
});
String originalText = document.get();

org.eclipse.compare.unifieddiff.UnifiedDiff.dispose(editor);
waitForPendingWork();

assertTrue(isInModel(projectionModel, foldOfTheEditor), "disposal must restore the editor's own folds");
var remaining = projectionModel.getAnnotationIterator();
assertEquals(foldOfTheEditor, remaining.next());
assertFalse(remaining.hasNext(), "only the editor's own fold must remain");
assertEquals(originalText, document.get());
}

/**
* A fold whose first line stays visible works as it always did and must be left
* alone.
Expand Down
Loading