From 31c83fdcd78504b0280f0f4030a4390bf7127ee0 Mon Sep 17 00:00:00 2001 From: Mehmet Emin Karaman Date: Mon, 13 Oct 2025 09:38:11 +0200 Subject: [PATCH 01/52] Fix for multi-threading issues in AnnotationMap - added synchronize block to methods in AnnotationModel, wherever reads / writes could happen in multiple threads. - changed execution order, to be able to synchronize only necessary code blocks. Co-authored-by: Andrey Loskutov --- .../jface/text/source/AnnotationModel.java | 119 ++++++++++-------- 1 file changed, 69 insertions(+), 50 deletions(-) diff --git a/bundles/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java b/bundles/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java index bb6fe764265..f62ceaf3edb 100644 --- a/bundles/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java +++ b/bundles/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java @@ -451,18 +451,17 @@ protected void replaceAnnotations(Annotation[] annotationsToRemove, Map deleted= new ArrayList<>(); IAnnotationMap annotations= getAnnotationMap(); - Object mapLock = annotations.getLockObject(); - synchronized (mapLock) { + synchronized (getLockObject()) { annotations.forEach((a, p) -> { if (p == null || p.isDeleted()) { deleted.add(a); @@ -693,10 +691,12 @@ private void cleanup(boolean fireModelChanged, boolean forkNotification) { removeAnnotations(deleted, false, false); synchronized (getLockObject()) { if (fModelEvent != null) { + final AnnotationModelEvent event = fModelEvent; + fModelEvent = null; new Thread() { @Override public void run() { - fireModelChanged(); + fireModelChanged(event); } }.start(); } @@ -760,7 +760,11 @@ private Iterator getRegionAnnotationIterator(int offset, int length, try { Position[] positions= document.getPositions(IDocument.DEFAULT_CATEGORY, offset, length, canStartBefore, canEndAfter); - return new AnnotationsInterator(positions, fPositions); + IdentityHashMap positionsMap; + synchronized (getLockObject()) { + positionsMap= new IdentityHashMap<>(fPositions); + } + return new AnnotationsInterator(positions, positionsMap); } catch (BadPositionCategoryException e) { // can happen if e.g. the document doesn't contain such a category, or when removed in a different thread return Collections.emptyList().iterator(); @@ -784,11 +788,14 @@ private Iterator getAnnotationIterator(boolean cleanup, boolean recu return iter; } - List> iterators= new ArrayList<>(fAttachments.size() + 1); - iterators.add(iter); - Iterator it= fAttachments.keySet().iterator(); - while (it.hasNext()) { - iterators.add(fAttachments.get(it.next()).getAnnotationIterator()); + List> iterators; + synchronized (getLockObject()) { + iterators= new ArrayList<>(fAttachments.size() + 1); + iterators.add(iter); + Iterator it= fAttachments.keySet().iterator(); + while (it.hasNext()) { + iterators.add(fAttachments.get(it.next()).getAnnotationIterator()); + } } return new MetaIterator<>(iterators.iterator()); @@ -837,22 +844,21 @@ public void removeAllAnnotations() { */ protected void removeAllAnnotations(boolean fireModelChanged) { IAnnotationMap annotations= getAnnotationMap(); - if (fDocument != null) { + List positionsToRemove = new ArrayList<>(); + synchronized (getLockObject()) { Iterator e= getAnnotationMap().keySetIterator(); while (e.hasNext()) { Annotation a= e.next(); Position p= annotations.get(a); - removePosition(fDocument, p); -// p.delete(); - synchronized (getLockObject()) { - getAnnotationModelEvent().annotationRemoved(a, p); - } + positionsToRemove.add(p); + getAnnotationModelEvent().annotationRemoved(a, p); } + annotations.clear(); + fPositions.clear(); + } + for (Position position : positionsToRemove) { + removePosition(fDocument, position); } - - annotations.clear(); - fPositions.clear(); - if (fireModelChanged) { fireModelChanged(); } @@ -872,24 +878,22 @@ public void removeAnnotation(Annotation annotation) { */ protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) { IAnnotationMap annotations= getAnnotationMap(); - if (annotations.containsKey(annotation)) { - - Position p= null; + Position p; + synchronized (getLockObject()) { p= annotations.get(annotation); - if (fDocument != null) { - removePosition(fDocument, p); -// p.delete(); + if (p == null) { + return; } - annotations.remove(annotation); fPositions.remove(p); - synchronized (getLockObject()) { - getAnnotationModelEvent().annotationRemoved(annotation, p); - } + getAnnotationModelEvent().annotationRemoved(annotation, p); + } + if (fDocument != null) { + removePosition(fDocument, p); + } - if (fireModelChanged) { - fireModelChanged(); - } + if (fireModelChanged) { + fireModelChanged(); } } @@ -982,13 +986,20 @@ public void removeAnnotationModelListener(IAnnotationModelListener listener) { @Override public void addAnnotationModel(Object key, IAnnotationModel attachment) { Assert.isNotNull(attachment); - if (!fAttachments.containsValue(attachment)) { + Assert.isNotNull(key); + synchronized (getLockObject()) { + if (fAttachments.containsValue(attachment)) { + return; + } fAttachments.put(key, attachment); + } + IDocument document= fDocument; + if (document != null) { for (int i= 0; i < fOpenConnections; i++) { - attachment.connect(fDocument); + attachment.connect(document); } - attachment.addAnnotationModelListener(fModelListener); } + attachment.addAnnotationModelListener(fModelListener); } /* @@ -1006,13 +1017,21 @@ public IAnnotationModel getAnnotationModel(Object key) { */ @Override public IAnnotationModel removeAnnotationModel(Object key) { - IAnnotationModel ret= fAttachments.remove(key); - if (ret != null) { + Assert.isNotNull(key); + IAnnotationModel ret; + synchronized (getLockObject()) { + ret= fAttachments.remove(key); + if (ret == null) { + return null; + } + } + IDocument document= fDocument; + if (document != null) { for (int i= 0; i < fOpenConnections; i++) { - ret.disconnect(fDocument); + ret.disconnect(document); } - ret.removeAnnotationModelListener(fModelListener); } + ret.removeAnnotationModelListener(fModelListener); return ret; } From ec70c281555d88c914ebdbdf9e4fc2d79c23520f Mon Sep 17 00:00:00 2001 From: andrew-tram <106191140+andrew-tram@users.noreply.github.com> Date: Wed, 13 Aug 2025 10:43:46 -0400 Subject: [PATCH 02/52] Allowing smaller images to show in the workbench window --- .../renderers/swt/StackRenderer.java | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java index bc20b90c816..91013eeb04a 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java @@ -201,6 +201,8 @@ public class StackRenderer extends LazyStackRenderer { * this threshold, the image is hidden. */ public static final int ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD = 450; + public static final int ONBOARDING_SMALL_IMAGE_MAX_HEIGHT = 250; // "small" cutoff + public static final int ONBOARDING_SMALL_IMAGE_REQUIRED_TOTAL = 314; // 256 + 32(top/bot) + 32(extra) private MPerspective currentPerspectiveForOnboarding; @@ -790,6 +792,7 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding || onBoardingImage == null || onBoardingImage.isDisposed()) { return; } + int imgH = getImageHeight(onBoardingImage); boolean showComposite = tabFolder.getItemCount() == 0; boolean compositeVisible = onBoarding.isVisible(); boolean imageVisible = onBoardingImage.isVisible(); @@ -803,7 +806,15 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding if (!new Point(width, height).equals(onBoarding.getSize())) { onBoarding.setSize(width, height); - boolean showImage = height > ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD; + boolean showImage; + if (imgH > 0 && imgH <= ONBOARDING_SMALL_IMAGE_MAX_HEIGHT) { + // For small images, require a smaller total height (314 overall) + showImage = height >= ONBOARDING_SMALL_IMAGE_REQUIRED_TOTAL + - (ONBOARDING_TOP_SPACING + ONBOARDING_SPACING); // 314 - 32 = 282 + } else { + // For larger images, fall back to the original (higher) threshold + showImage = height >= ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD; // e.g., 450 content height + } if (imageVisible != showImage || showComposite != compositeVisible) { onBoardingImage.setVisible(showImage); ((GridData) onBoardingImage.getLayoutData()).exclude = !showImage; @@ -819,6 +830,23 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding } } + /** + * Returns the height of the image assigned to the given label. + * + * @param label the Label widget holding the image + * @return the height in pixels, or 0 if the label has no valid image + */ + private static int getImageHeight(Label label) { + if (label == null || label.isDisposed()) { + return 0; + } + Image img = label.getImage(); + if (img == null || img.isDisposed()) { + return 0; + } + return img.getBounds().height; + } + private boolean getMRUValue() { return getMRUValueFromPreferences(); } From d63891facb4ccc5de0e6bd8d868c6a890bf89ad9 Mon Sep 17 00:00:00 2001 From: andrew-tram <106191140+andrew-tram@users.noreply.github.com> Date: Mon, 8 Sep 2025 16:45:42 -0400 Subject: [PATCH 03/52] Apply suggestion from @marcushoepfner Co-authored-by: marcushoepfner --- .../eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java index 91013eeb04a..b16302c5902 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java @@ -792,7 +792,7 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding || onBoardingImage == null || onBoardingImage.isDisposed()) { return; } - int imgH = getImageHeight(onBoardingImage); + int imgHeight = getImageHeight(onBoardingImage); boolean showComposite = tabFolder.getItemCount() == 0; boolean compositeVisible = onBoarding.isVisible(); boolean imageVisible = onBoardingImage.isVisible(); From 53e463e752abe0fed9a094ca730b5b039d356c88 Mon Sep 17 00:00:00 2001 From: andrew-tram <106191140+andrew-tram@users.noreply.github.com> Date: Mon, 8 Sep 2025 16:57:24 -0400 Subject: [PATCH 04/52] Update StackRenderer.java > did you consider putting this in a method and provide some java doc for the method. With that: > https://github.com/eclipse-platform/eclipse.platform.ui/pull/3169/files/6841a0ef260ff65316607a1d4d2b6617b8dc637b#r2329939384 > * very detailed math code is hidden from the method flow (increased readability of the setOnboardingControlSize method) > * comments can be removed and put into java doc of the new method > > WDYT? --- .../renderers/swt/StackRenderer.java | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java index b16302c5902..395c688b48d 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java @@ -805,22 +805,12 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding int height = folderBounds.height - ONBOARDING_TOP_SPACING - ONBOARDING_SPACING; if (!new Point(width, height).equals(onBoarding.getSize())) { onBoarding.setSize(width, height); - - boolean showImage; - if (imgH > 0 && imgH <= ONBOARDING_SMALL_IMAGE_MAX_HEIGHT) { - // For small images, require a smaller total height (314 overall) - showImage = height >= ONBOARDING_SMALL_IMAGE_REQUIRED_TOTAL - - (ONBOARDING_TOP_SPACING + ONBOARDING_SPACING); // 314 - 32 = 282 - } else { - // For larger images, fall back to the original (higher) threshold - showImage = height >= ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD; // e.g., 450 content height - } + boolean showImage = shouldShowOnboardingImage(height, imgHeight); if (imageVisible != showImage || showComposite != compositeVisible) { onBoardingImage.setVisible(showImage); ((GridData) onBoardingImage.getLayoutData()).exclude = !showImage; onboardingComposite.getParent().layout(true); } - } } else { if (compositeVisible) { @@ -830,6 +820,29 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding } } + /** + * Checks if the onboarding image should be shown, based on how much vertical + * space is available and the image size. + *

+ *

    + *
  • Small images: allowed with a lower minimum height.
  • + *
  • Large images: require the standard higher threshold.
  • + *
+ * + * @param contentHeight available space in pixels + * @param imageHeight image height in pixels (0 if none) + * @return true if the image should be shown; false otherwise + */ + private static boolean shouldShowOnboardingImage(int contentHeight, int imageHeight) { + if (imageHeight > 0 && imageHeight <= ONBOARDING_SMALL_IMAGE_MAX_HEIGHT) { + // 314 total minus (top + bottom) = 314 - (30 + 2) = 282 + int required = ONBOARDING_SMALL_IMAGE_REQUIRED_TOTAL - (ONBOARDING_TOP_SPACING + ONBOARDING_SPACING); + return contentHeight >= required; + } + // Larger images fall back to the original (higher) threshold + return contentHeight >= ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD; + } + /** * Returns the height of the image assigned to the given label. * From 3c7103dfd091856c5ce1d93a7ab94f9d5039f50c Mon Sep 17 00:00:00 2001 From: andrew-tram <106191140+andrew-tram@users.noreply.github.com> Date: Mon, 1 Dec 2025 11:40:12 -0500 Subject: [PATCH 05/52] Update MANIFEST.MF update version --- .../META-INF/MANIFEST.MF | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/META-INF/MANIFEST.MF b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/META-INF/MANIFEST.MF index 249542c521d..ca4f9ad426c 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/META-INF/MANIFEST.MF @@ -1,7 +1,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-SymbolicName: org.eclipse.e4.ui.workbench.renderers.swt;singleton:=true -Bundle-Version: 0.16.1000.qualifier +Bundle-Version: 0.16.1100.qualifier Bundle-Name: %pluginName Bundle-Vendor: %providerName Bundle-Localization: plugin From 8c58914c58a185837de87463e9b051152021f047 Mon Sep 17 00:00:00 2001 From: Vasili Gulevich Date: Sun, 8 Mar 2026 01:24:49 +0400 Subject: [PATCH 06/52] Test MultiPageEditorPart contracts in FormEditor #3764 --- .../META-INF/MANIFEST.MF | 4 +- .../build.properties | 3 +- .../ui/forms/editor/FormEditorMock.java | 98 ++++++++++ .../ui/forms/editor/FormEditorTest.java | 180 ++++++++++++++++++ .../eclipse/ui/tests/forms/AllFormsTests.java | 4 +- tests/org.eclipse.ui.tests.forms/plugin.xml | 14 ++ 6 files changed, 300 insertions(+), 3 deletions(-) create mode 100644 tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorMock.java create mode 100644 tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorTest.java create mode 100644 tests/org.eclipse.ui.tests.forms/plugin.xml diff --git a/tests/org.eclipse.ui.tests.forms/META-INF/MANIFEST.MF b/tests/org.eclipse.ui.tests.forms/META-INF/MANIFEST.MF index c46a6f01793..d9e88853a9a 100755 --- a/tests/org.eclipse.ui.tests.forms/META-INF/MANIFEST.MF +++ b/tests/org.eclipse.ui.tests.forms/META-INF/MANIFEST.MF @@ -6,7 +6,9 @@ Bundle-Version: 3.11.100.qualifier Require-Bundle: org.eclipse.ui;bundle-version="3.208.0", org.eclipse.core.runtime, org.eclipse.test.performance, - org.eclipse.ui.forms + org.eclipse.ui.forms, + org.mockito.mockito-core;bundle-version="[5.21.0,6.0.0)", + junit-jupiter-api;bundle-version="[5.14.3,6.0.0)" Bundle-Vendor: Eclipse.org Import-Package: org.junit.jupiter.api;version="[5.14.0,6.0.0)", org.junit.jupiter.api.function;version="[5.14.0,6.0.0)", diff --git a/tests/org.eclipse.ui.tests.forms/build.properties b/tests/org.eclipse.ui.tests.forms/build.properties index e0fa9d81fe3..4fc66a2a165 100755 --- a/tests/org.eclipse.ui.tests.forms/build.properties +++ b/tests/org.eclipse.ui.tests.forms/build.properties @@ -14,7 +14,8 @@ bin.includes = .,\ META-INF/,\ about.html,\ - test.xml + test.xml,\ + plugin.xml output.. = bin/ source.. = forms/ diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorMock.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorMock.java new file mode 100644 index 00000000000..26a7de7e16d --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorMock.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2026 Vasili Gulevich and others + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Vasili Gulevich - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.forms.editor; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabItem; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.PartInitException; + +public class FormEditorMock extends FormEditor { + public static final String ID = "org.eclipse.ui.tests.forms.FormEditorMock"; + + public interface Hook { + + default boolean isSaveAsAllowed(FormEditorMock subject) { + return false; + } + + default void addPages(FormEditorMock subject) { + FormPage page1 = new FormPage(subject, "defaultpage", "defaultpage"); + try { + subject.addPage(page1); + } catch (PartInitException e) { + throw new AssertionError(e); + } + } + + default void doSave(FormEditorMock subject) { + } + + default void createContainer(FormEditorMock subject, CTabFolder container) { + } + + default void createItem(FormEditorMock subject, CTabItem item) { + + } + } + + public static final Hook DEFAULT_HOOK = new Hook() { + }; + + public static Hook hook = DEFAULT_HOOK; + + @Override + protected CTabFolder createContainer(Composite parent) { + CTabFolder result = super.createContainer(parent); + hook.createContainer(this, result); + return result; + } + + @Override + protected CTabItem createItem(int index, Control control) { + CTabItem result = super.createItem(index, control); + hook.createItem(this, result); + return result; + } + @Override + protected void addPages() { + hook.addPages(this); + } + + @Override + public void doSave(IProgressMonitor monitor) { + hook.doSave(this); + } + + @Override + public void doSaveAs() { + hook.doSave(this); + } + + @Override + public boolean isSaveAsAllowed() { + return hook.isSaveAsAllowed(this); + } + + public CTabFolder leakContainer() { + return (CTabFolder) getContainer(); + } + + public IEditorPart[] leakPages() { + return pages.stream().toArray(IEditorPart[]::new); + } +} diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorTest.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorTest.java new file mode 100644 index 00000000000..8273127113c --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/forms/editor/FormEditorTest.java @@ -0,0 +1,180 @@ +/******************************************************************************* + * Copyright (c) 2026 Vasili Gulevich and others + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Vasili Gulevich - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.forms.editor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabItem; +import org.eclipse.swt.widgets.Event; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.forms.editor.FormEditorMock.Hook; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +public class FormEditorTest { + + private static final IWorkbench WORKBENCH = PlatformUI.getWorkbench(); + + public IEditorInput input = mock(); + + @BeforeEach + public void closeEditors() { + WORKBENCH.getActiveWorkbenchWindow().getActivePage().closeAllEditors(false); + } + + @Test + public void activatePage() throws PartInitException { + FormEditorMock.hook = FormEditorMock.DEFAULT_HOOK; + FormEditorMock subject = (FormEditorMock) WORKBENCH.getActiveWorkbenchWindow().getActivePage().openEditor(input, + FormEditorMock.ID); + assertEquals("defaultpage", subject.getActivePageInstance().getTitle()); + FormPage page1 = addPage(subject, "page1"); + subject.setActivePage("page1"); + dispatch(subject); + assertSame(page1, subject.getActivePageInstance()); + } + + @Test + public void removePage() throws PartInitException { + FormEditorMock.hook = FormEditorMock.DEFAULT_HOOK; + FormEditorMock subject = (FormEditorMock) WORKBENCH.getActiveWorkbenchWindow().getActivePage().openEditor(input, + FormEditorMock.ID); + dispatch(subject); + CTabItem[] tabs = subject.leakContainer().getItems(); + assertEquals(1, tabs.length); + FormPage page1 = addPage(subject, "page1"); + assertSame(page1, subject.findPage("page1")); + tabs = subject.leakContainer().getItems(); + assertEquals(2, tabs.length); + subject.removePage(page1.getIndex()); + dispatch(subject); + assertNull(subject.findPage("page1")); + tabs = subject.leakContainer().getItems(); + assertEquals(1, tabs.length); + } + + @Test + public void disposeTab() throws PartInitException { + FormEditorMock.hook = FormEditorMock.DEFAULT_HOOK; + FormEditorMock subject = (FormEditorMock) WORKBENCH.getActiveWorkbenchWindow().getActivePage().openEditor(input, + FormEditorMock.ID); + dispatch(subject); + CTabItem[] tabs = subject.leakContainer().getItems(); + assertEquals(1, tabs.length); + FormPage page1 = addPage(subject, "page1"); + assertSame(page1, subject.findPage("page1")); + tabs = subject.leakContainer().getItems(); + assertEquals(2, tabs.length); + tabs[tabs.length - 1].dispose(); + dispatch(subject); + tabs = subject.leakContainer().getItems(); + assertEquals(1, tabs.length); + // BUG https://github.com/eclipse-platform/eclipse.platform.ui/issues/3766 + // assertNull(subject.findPage("page1")); + } + + @Test + public void maintainIntegrityOnPageClose() throws PartInitException { + FormEditorMock.hook = new Hook() { + @Override + public void createContainer(FormEditorMock subject, CTabFolder container) { + Hook.super.createContainer(subject, container); + container.setUnselectedCloseVisible(true); + } + + @Override + public void createItem(FormEditorMock subject, CTabItem item) { + Hook.super.createItem(subject, item); + item.setShowClose(true); + } + }; + FormEditorMock subject = (FormEditorMock) WORKBENCH.getActiveWorkbenchWindow().getActivePage().openEditor(input, + FormEditorMock.ID); + FormPage page1 = addPage(subject, "page1"); + CTabFolder tabFolder = subject.leakContainer(); + CTabItem tab = tabFolder.getItem(1); + assertTrue(tab.getShowClose()); + assertSame(page1, subject.findPage("page1")); + Event event = new Event(); + event.type = SWT.MouseDown; + event.button = 1; + event.x = tab.getBounds().x + tab.getBounds().width - 9; + event.y = tab.getBounds().y + tab.getBounds().height/2; + tabFolder.notifyListeners(event.type, event); + dispatch(subject); + event.type = SWT.MouseUp; + tabFolder.notifyListeners(event.type, event); + dispatch(subject); + assertEquals(1, tabFolder.getItems().length); + // BUG https://github.com/eclipse-platform/eclipse.platform.ui/issues/3766 + // assertNull(subject.findPage("page1")); + } + + @Test + @Disabled("https://github.com/eclipse-platform/eclipse.platform.ui/issues/3764") + public void anEditorIsActiveOnStart() throws PartInitException { + FormEditorMock.hook = FormEditorMock.DEFAULT_HOOK; + FormEditorMock subject = (FormEditorMock) WORKBENCH.getActiveWorkbenchWindow().getActivePage().openEditor(input, + FormEditorMock.ID); + dispatch(subject); + // BUG https://github.com/eclipse-platform/eclipse.platform.ui/issues/3764 + assertNotNull(subject.getActiveEditor()); + } + + @Test + @Disabled("https://github.com/eclipse-platform/eclipse.platform.ui/issues/3764") + public void activateEditors() throws PartInitException { + FormEditorMock.hook = FormEditorMock.DEFAULT_HOOK; + FormEditorMock subject = (FormEditorMock) WORKBENCH.getActiveWorkbenchWindow().getActivePage().openEditor(input, + FormEditorMock.ID); + FormPage page1 = addPage(subject, "page1"); + assertNotNull(page1); +// BUG https://github.com/eclipse-platform/eclipse.platform.ui/issues/3764 + assertEveryTabCanBeActive(subject); + } + + private void assertEveryTabCanBeActive(FormEditorMock subject) { + dispatch(subject); + for (IEditorPart part : subject.leakPages()) { + subject.setActiveEditor(part); + dispatch(subject); + assertSame(part, subject.getActiveEditor()); + } + } + + private void dispatch(FormEditorMock subject) { + while (subject.leakContainer().getDisplay().readAndDispatch()) { + } + } + + private FormPage addPage(FormEditorMock subject, String id) throws PartInitException { + FormPage page1 = new FormPage(subject, id, id); + subject.addPage(page1); + dispatch(subject); + return page1; + } + +} diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java index 1fbd271b2d8..2df3ad4df99 100755 --- a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java @@ -16,6 +16,7 @@ package org.eclipse.ui.tests.forms; +import org.eclipse.ui.forms.editor.FormEditorTest; import org.eclipse.ui.tests.forms.events.AllEventsTests; import org.eclipse.ui.tests.forms.layout.AllLayoutTests; import org.eclipse.ui.tests.forms.util.AllUtilityTests; @@ -32,7 +33,8 @@ AllEventsTests.class, // AllLayoutTests.class, // AllUtilityTests.class, // - AllWidgetsTests.class // + AllWidgetsTests.class, // + FormEditorTest.class // }) public class AllFormsTests { diff --git a/tests/org.eclipse.ui.tests.forms/plugin.xml b/tests/org.eclipse.ui.tests.forms/plugin.xml new file mode 100644 index 00000000000..2a1c9fb1c0c --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/plugin.xml @@ -0,0 +1,14 @@ + + + + + + + + + From 8007e93d290d3c2e0fe13d4179f5dffaaca37369 Mon Sep 17 00:00:00 2001 From: Elsa Zacharia Date: Tue, 2 Jun 2026 11:02:55 +0530 Subject: [PATCH 07/52] Add result count to Find/Replace overlay Display the total number of search results in the Find/Replace overlay if any else hide the bar --- .../overlay/FindReplaceOverlay.java | 135 +++++++++++++++++- 1 file changed, 134 insertions(+), 1 deletion(-) diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlay.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlay.java index ac389fd96a6..364f12267ed 100644 --- a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlay.java +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlay.java @@ -38,6 +38,7 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Scrollable; @@ -127,6 +128,7 @@ private static final class KeyboardShortcuts { private Composite searchContainer; private Composite searchBarContainer; private HistoryTextWrapper searchBar; + private Label countLabel; private AccessibleToolBar searchTools; private ToolItem searchInSelectionButton; private ToolItem wholeWordSearchButton; @@ -723,6 +725,7 @@ public void focusLost(FocusEvent e) { private void updateIncrementalSearch() { findReplaceLogic.setFindString(searchBar.getText()); + updateCount(); evaluateStatusAfterFind(); } @@ -747,14 +750,142 @@ private void createReplaceBar() { private void createSearchContainer() { searchContainer = new FixedColorComposite(contentGroup, SWT.NONE, widgetBackgroundColor); GridDataFactory.fillDefaults().grab(true, true).align(GridData.FILL, GridData.FILL).applyTo(searchContainer); - GridLayoutFactory.fillDefaults().numColumns(3).extendedMargins(7, 4, 3, 5).equalWidth(false) + GridLayoutFactory.fillDefaults().numColumns(4).extendedMargins(7, 4, 3, 5).equalWidth(false) .applyTo(searchContainer); createSearchBar(); + createCountLabel(); createSearchTools(); createCloseTools(); } + private void createCountLabel() { + countLabel = new Label(searchContainer, SWT.NONE); + countLabel.setForeground(normalTextForegroundColor); + countLabel.setBackground(widgetBackgroundColor); + GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).hint(SWT.DEFAULT, SWT.DEFAULT).exclude(true) + .applyTo(countLabel); + countLabel.setVisible(false); + } + + private void updateCount() { + if (!okayToUse(countLabel)) { + return; + } + String inputString = searchBar.getText(); + if (inputString.isEmpty()) { + hideCountLabel(); + return; + } + + try { + int totalCount = inputTextCount(inputString); + if (totalCount == 0) { + hideCountLabel(); + } else { + int currentIndex = getCurrentIndex(inputString, totalCount); + countLabel.setText(currentIndex + " of " + totalCount); //$NON-NLS-1$ + showCountLabel(); + } + } catch (Exception e) { + hideCountLabel(); + } + } + + private void showCountLabel() { + if (!countLabel.isVisible()) { + countLabel.setVisible(true); + ((GridData) countLabel.getLayoutData()).exclude = false; + } + countLabel.pack(); + countLabel.getParent().layout(); + } + + private void hideCountLabel() { + if (countLabel.isVisible()) { + countLabel.setVisible(false); + ((GridData) countLabel.getLayoutData()).exclude = true; + countLabel.getParent().layout(); + } + } + + private int inputTextCount(String inputString) { + if (inputString.isEmpty() || findReplaceLogic.getTarget() == null) { + return 0; + } + if (!(targetPart instanceof StatusTextEditor)) { + return 0; + } + StatusTextEditor textEditor = (StatusTextEditor) targetPart; + ITextViewer viewer = textEditor.getAdapter(ITextViewer.class); + if (viewer == null || viewer.getDocument() == null) { + return 0; + } + + FindReplaceDocumentAdapter docAdapter = new FindReplaceDocumentAdapter(viewer.getDocument()); + return findMatches(docAdapter, inputString, -1); + } + + private int getCurrentIndex(String inputString, int totalCount) { + if (totalCount == 0 || findReplaceLogic.getTarget() == null) { + return 0; + } + + IFindReplaceTarget target = findReplaceLogic.getTarget(); + Point selection = target.getSelection(); + int currentOffset = selection.x; + + if (!(targetPart instanceof StatusTextEditor)) { + return 0; + } + + StatusTextEditor textEditor = (StatusTextEditor) targetPart; + ITextViewer viewer = textEditor.getAdapter(ITextViewer.class); + if (viewer == null || viewer.getDocument() == null) { + return 0; + } + + FindReplaceDocumentAdapter docAdapter = new FindReplaceDocumentAdapter(viewer.getDocument()); + int index = findMatches(docAdapter, inputString, currentOffset); + return index > 0 ? index : 1; + } + + /** + * Iterates through all matches of the search string in the document. + * + * @param docAdapter the document adapter to search in + * @param searchString the string to search for + * @param stopOffset if stopOffset>= 0, stops and returns the index when a + * match at or after this offset is found; if stopOffset< 0, + * counts all matches + * @return the count of all matches (if stopOffset < 0) or the index of the + * first match at or after stopOffset. + */ + private int findMatches(FindReplaceDocumentAdapter docAdapter, String searchString, int stopOffset) { + boolean isCaseSensitive = findReplaceLogic.isActive(SearchOptions.CASE_SENSITIVE); + boolean isWholeWord = findReplaceLogic.isActive(SearchOptions.WHOLE_WORD); + boolean isRegEx = findReplaceLogic.isActive(SearchOptions.REGEX); + + int index = 0; + int startOffset = 0; + try { + while (true) { + org.eclipse.jface.text.IRegion match = docAdapter.find(startOffset, searchString, true, + isCaseSensitive, isWholeWord, isRegEx); + if (match == null) { + break; + } + index++; + if (stopOffset >= 0 && match.getOffset() >= stopOffset) { + return index; + } + startOffset = match.getOffset() + Math.max(1, match.getLength()); + } + } catch (Exception e) { + } + return index; + } + private void createReplaceContainer() { replaceContainer = new FixedColorComposite(contentGroup, SWT.NONE, widgetBackgroundColor); GridDataFactory.fillDefaults().grab(true, true).align(GridData.FILL, GridData.FILL).applyTo(replaceContainer); @@ -973,6 +1104,7 @@ private String getFindString() { private void performSingleReplace() { if (findReplaceLogic.performSelectAndReplace()) { findReplaceLogic.performSearch(); + updateCount(); evaluateStatusAfterFind(); } else { evaluateStatusAfterReplace(); @@ -987,6 +1119,7 @@ private void performSearch(boolean forward) { activateInFindReplacerIf(SearchOptions.FORWARD, forward); findReplaceLogic.performSearch(); activateInFindReplacerIf(SearchOptions.FORWARD, oldForwardSearchSetting); + updateCount(); evaluateStatusAfterFind(); searchBar.storeHistory(); } From 998dac9f81ea35bf0bc8b1c08f9a0d7c2c689c52 Mon Sep 17 00:00:00 2001 From: Simeon Andreev Date: Sat, 30 May 2026 13:09:51 +0300 Subject: [PATCH 08/52] Use OSGI tracing and debug options handling in org.eclipse.ui.workbench Moved debug option handling from Policy to WorkbenchPlugin, adjusted it to use OSGI debug option handling. Replaced standard out and log tracing in org.eclipse.ui.workbench with OSGI tracing. Fixes: https://github.com/eclipse-platform/eclipse.platform.ui/issues/4033 --- .../ui/internal/ObjectActionContributor.java | 4 +- .../eclipse/ui/internal/WorkbenchImages.java | 2 +- .../eclipse/ui/internal/WorkbenchPlugin.java | 112 +++++++++++++++++- .../org/eclipse/ui/internal/WorkingSet.java | 3 +- .../org/eclipse/ui/internal/misc/Policy.java | 75 +++++------- .../eclipse/ui/part/MultiPageEditorPart.java | 8 +- 6 files changed, 143 insertions(+), 61 deletions(-) diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/ObjectActionContributor.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/ObjectActionContributor.java index e9b38e0531e..a0b0175f8f9 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/ObjectActionContributor.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/ObjectActionContributor.java @@ -118,7 +118,7 @@ public boolean contributeObjectActions(final IWorkbenchPart part, IMenuManager m IStructuredSelection newSelection = LegacyResourceSupport.adaptSelection(ssel, getObjectClass()); if (newSelection.size() != ssel.size()) { if (Policy.DEBUG_CONTRIBUTIONS) { - WorkbenchPlugin.log("Error adapting selection to " + getObjectClass() + //$NON-NLS-1$ + WorkbenchPlugin.getDefault().getTrace().trace(Policy.DEBUG_CONTRIBUTIONS_FLAG, "Error adapting selection to " + getObjectClass() + //$NON-NLS-1$ ". Contribution " + getID(config) + " is being ignored"); //$NON-NLS-1$ //$NON-NLS-2$ } return false; @@ -208,7 +208,7 @@ public boolean isApplicableTo(Object object) { Object adapted = LegacyResourceSupport.getAdapter(object, getObjectClass()); if (adapted == null) { if (Policy.DEBUG_CONTRIBUTIONS) { - WorkbenchPlugin.log("Error adapting " + object.getClass().getName() + //$NON-NLS-1$ + WorkbenchPlugin.getDefault().getTrace().trace(Policy.DEBUG_CONTRIBUTIONS_FLAG, "Error adapting " + object.getClass().getName() + //$NON-NLS-1$ " to " //$NON-NLS-1$ + getObjectClass() + ". Contribution " + getID(config) + " is being ignored"); //$NON-NLS-1$ //$NON-NLS-2$ } diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchImages.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchImages.java index 8c64c27f996..d25664455b2 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchImages.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchImages.java @@ -309,7 +309,7 @@ public static void declareImage(String symbolicName, ImageDescriptor descriptor, if (Policy.DEBUG_DECLARED_IMAGES) { Image image = descriptor.createImage(false); if (image == null) { - WorkbenchPlugin.log("Image not found in WorkbenchImages.declaredImage(). symbolicName=" + symbolicName //$NON-NLS-1$ + WorkbenchPlugin.getDefault().getTrace().trace(Policy.DEBUG_DECLARED_IMAGES_FLAG, "Image not found in WorkbenchImages.declaredImage(). symbolicName=" + symbolicName //$NON-NLS-1$ + " descriptor=" + descriptor, new Exception("stack dump")); //$NON-NLS-1$//$NON-NLS-2$ } else { image.dispose(); diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPlugin.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPlugin.java index 1d4037a9d08..6e146cbe81b 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPlugin.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPlugin.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2025 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -16,11 +16,63 @@ package org.eclipse.ui.internal; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_COMMANDS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_COMMANDS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTEXTS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTEXTS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTEXTS_PERFORMANCE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTEXTS_PERFORMANCE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTEXTS_VERBOSE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTEXTS_VERBOSE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTRIBUTIONS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_CONTRIBUTIONS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_DECLARED_IMAGES; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_DECLARED_IMAGES_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_DRAG_DROP; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_DRAG_DROP_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_PERFORMANCE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_PERFORMANCE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_VERBOSE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_VERBOSE_COMMAND_ID; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_VERBOSE_COMMAND_ID_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_HANDLERS_VERBOSE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_KEY_BINDINGS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_KEY_BINDINGS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_KEY_BINDINGS_VERBOSE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_KEY_BINDINGS_VERBOSE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_MPE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_MPE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_OPERATIONS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_OPERATIONS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_OPERATIONS_VERBOSE; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_OPERATIONS_VERBOSE_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SHOW_ALL_JOBS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SHOW_ALL_JOBS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SOURCES; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SOURCES_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_STALE_JOBS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_STALE_JOBS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SWT_DEBUG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SWT_DEBUG_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SWT_DEBUG_GLOBAL; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SWT_DEBUG_GLOBAL_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SWT_GRAPHICS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_SWT_GRAPHICS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_TOOLBAR_DISPOSAL; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_TOOLBAR_DISPOSAL_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_WORKING_SETS; +import static org.eclipse.ui.internal.misc.Policy.DEBUG_WORKING_SETS_FLAG; +import static org.eclipse.ui.internal.misc.Policy.DEFAULT; +import static org.eclipse.ui.internal.misc.Policy.EXPERIMENTAL_MENU; + import java.text.Bidi; import java.text.MessageFormat; import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import java.util.Hashtable; import java.util.Locale; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; @@ -41,8 +93,11 @@ import org.eclipse.jface.util.BidiUtils; import org.eclipse.jface.window.Window; import org.eclipse.osgi.service.debug.DebugOptions; +import org.eclipse.osgi.service.debug.DebugOptionsListener; +import org.eclipse.osgi.service.debug.DebugTrace; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.graphics.Device; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IDecoratorManager; @@ -58,6 +113,7 @@ import org.eclipse.ui.internal.help.HelpServiceImpl; import org.eclipse.ui.internal.intro.IIntroRegistry; import org.eclipse.ui.internal.intro.IntroRegistry; +import org.eclipse.ui.internal.misc.Policy; import org.eclipse.ui.internal.misc.StatusUtil; import org.eclipse.ui.internal.operations.WorkbenchOperationSupport; import org.eclipse.ui.internal.progress.ProgressManager; @@ -85,6 +141,7 @@ import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleException; import org.osgi.framework.BundleListener; +import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; /** @@ -103,7 +160,7 @@ * createExecutableExtension to create an executable instance of our workbench * class. */ -public class WorkbenchPlugin extends AbstractUIPlugin { +public class WorkbenchPlugin extends AbstractUIPlugin implements DebugOptionsListener { /** * Splash shell constant. @@ -163,6 +220,8 @@ public class WorkbenchPlugin extends AbstractUIPlugin { // TODO we should just drop this constant and use PlatformUI.PLUGIN_ID instead public static String PI_WORKBENCH = PlatformUI.PLUGIN_ID; + private static final String JFACE = "org.eclipse.jface"; //$NON-NLS-1$ + /** * The character used to separate preference page category ids */ @@ -202,6 +261,10 @@ public class WorkbenchPlugin extends AbstractUIPlugin { private ICommandHelpService commandHelpService; + private ServiceRegistration debugRegistration; + + private DebugTrace trace; + /** * Create an instance of the WorkbenchPlugin. The workbench plugin is * effectively the "application" for the workbench UI. The entire UI operates as @@ -762,6 +825,10 @@ public void start(BundleContext context) throws Exception { parseBidiArguments(); Window.setDefaultOrientation(getDefaultOrientation()); + Hashtable properties = new Hashtable<>(2); + properties.put(DebugOptions.LISTENER_SYMBOLICNAME, PlatformUI.PLUGIN_ID); + debugRegistration = context.registerService(DebugOptionsListener.class, this, properties); + // The UI plugin needs to be initialized so that it can install the callback in // PrefUtil, // which needs to be done as early as possible, before the workbench @@ -1061,6 +1128,10 @@ public void stop(BundleContext context) throws Exception { testableTracker.close(); testableTracker = null; } + if (debugRegistration != null) { + debugRegistration.unregister(); + debugRegistration = null; + } super.stop(context); } @@ -1436,4 +1507,41 @@ public TestableObject getTestableObject() { } return (TestableObject) testableTracker.getService(); } + + @Override + public void optionsChanged(DebugOptions options) { + trace = options.newDebugTrace(PlatformUI.PLUGIN_ID); + DEBUG_SWT_GRAPHICS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_SWT_GRAPHICS_FLAG, DEFAULT); + DEBUG_SWT_DEBUG = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_SWT_DEBUG_FLAG, DEFAULT); + DEBUG_SWT_DEBUG_GLOBAL = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_SWT_DEBUG_GLOBAL_FLAG, DEFAULT); + DEBUG_DRAG_DROP = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_DRAG_DROP_FLAG, DEFAULT); + DEBUG_SOURCES = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_SOURCES_FLAG, DEFAULT); + DEBUG_KEY_BINDINGS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_KEY_BINDINGS_FLAG, DEFAULT); + DEBUG_KEY_BINDINGS_VERBOSE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_KEY_BINDINGS_VERBOSE_FLAG, DEFAULT); + DEBUG_TOOLBAR_DISPOSAL = options.getBooleanOption(JFACE + DEBUG_TOOLBAR_DISPOSAL_FLAG, DEFAULT); + DEBUG_COMMANDS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_COMMANDS_FLAG, DEFAULT); + DEBUG_CONTEXTS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_CONTEXTS_FLAG, DEFAULT); + DEBUG_CONTEXTS_PERFORMANCE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_CONTEXTS_PERFORMANCE_FLAG, DEFAULT); + DEBUG_CONTEXTS_VERBOSE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_CONTEXTS_VERBOSE_FLAG, DEFAULT); + DEBUG_HANDLERS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_HANDLERS_FLAG, DEFAULT); + DEBUG_HANDLERS_PERFORMANCE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_HANDLERS_PERFORMANCE_FLAG, DEFAULT); + DEBUG_HANDLERS_VERBOSE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_HANDLERS_VERBOSE_FLAG, DEFAULT); + DEBUG_OPERATIONS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_OPERATIONS_FLAG, DEFAULT); + DEBUG_OPERATIONS_VERBOSE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_OPERATIONS_VERBOSE_FLAG, DEFAULT); + DEBUG_SHOW_ALL_JOBS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_SHOW_ALL_JOBS_FLAG, DEFAULT); + DEBUG_STALE_JOBS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_STALE_JOBS_FLAG, DEFAULT); + DEBUG_DECLARED_IMAGES = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_DECLARED_IMAGES_FLAG, DEFAULT); + DEBUG_CONTRIBUTIONS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_CONTRIBUTIONS_FLAG, DEFAULT); + DEBUG_HANDLERS_VERBOSE_COMMAND_ID = options.getOption(PlatformUI.PLUGIN_ID + DEBUG_HANDLERS_VERBOSE_COMMAND_ID_FLAG, ""); //$NON-NLS-1$ + EXPERIMENTAL_MENU = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_CONTRIBUTIONS_FLAG, DEFAULT); + DEBUG_MPE = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_MPE_FLAG, DEFAULT); + DEBUG_WORKING_SETS = options.getBooleanOption(PlatformUI.PLUGIN_ID + DEBUG_WORKING_SETS_FLAG, DEFAULT); + if (Policy.DEBUG_SWT_DEBUG_GLOBAL) { + Device.DEBUG = true; + } + } + + public DebugTrace getTrace() { + return trace; + } } diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkingSet.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkingSet.java index e3fb1684fd4..fe02d3b8f83 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkingSet.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkingSet.java @@ -180,8 +180,7 @@ public void run() throws Exception { IAdaptable item = factory.createElement(itemMemento); if (item == null) { if (Policy.DEBUG_WORKING_SETS) { - WorkbenchPlugin - .log("Unable to restore working set item - cannot instantiate item: " + factoryID); //$NON-NLS-1$ + WorkbenchPlugin.getDefault().getTrace().trace(Policy.DEBUG_WORKING_SETS_FLAG, "Unable to restore working set item - cannot instantiate item: " + factoryID); //$NON-NLS-1$ } } else { items.add(item); diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/misc/Policy.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/misc/Policy.java index 4d67b61e5e8..afdfde8a467 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/misc/Policy.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/misc/Policy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,10 +13,7 @@ *******************************************************************************/ package org.eclipse.ui.internal.misc; -import org.eclipse.core.runtime.Platform; -import org.eclipse.swt.graphics.Device; import org.eclipse.ui.ISourceProvider; -import org.eclipse.ui.PlatformUI; /** * A common facility for parsing the org.eclipse.ui/.options file. @@ -24,6 +21,33 @@ * @since 2.1 */ public class Policy { + + public static final String DEBUG_SWT_GRAPHICS_FLAG = "/trace/graphics"; //$NON-NLS-1$ + public static final String DEBUG_SWT_DEBUG_FLAG = "/debug/swtdebug"; //$NON-NLS-1$ + public static final String DEBUG_SWT_DEBUG_GLOBAL_FLAG = "/debug/swtdebugglobal"; //$NON-NLS-1$ + public static final String DEBUG_DRAG_DROP_FLAG = "/trace/dragDrop"; //$NON-NLS-1$ + public static final String DEBUG_SOURCES_FLAG = "/trace/sources"; //$NON-NLS-1$ + public static final String DEBUG_KEY_BINDINGS_FLAG = "/trace/keyBindings"; //$NON-NLS-1$ + public static final String DEBUG_KEY_BINDINGS_VERBOSE_FLAG = "/trace/keyBindings.verbose"; //$NON-NLS-1$ + public static final String DEBUG_TOOLBAR_DISPOSAL_FLAG = "/trace/toolbarDisposal"; //$NON-NLS-1$ + public static final String DEBUG_COMMANDS_FLAG = "/trace/commands"; //$NON-NLS-1$ + public static final String DEBUG_CONTEXTS_FLAG = "/trace/contexts"; //$NON-NLS-1$ + public static final String DEBUG_CONTEXTS_PERFORMANCE_FLAG = "/trace/contexts.performance"; //$NON-NLS-1$ + public static final String DEBUG_CONTEXTS_VERBOSE_FLAG = "/trace/contexts.verbose"; //$NON-NLS-1$ + public static final String DEBUG_HANDLERS_FLAG = "/trace/handlers"; //$NON-NLS-1$ + public static final String DEBUG_HANDLERS_PERFORMANCE_FLAG = "/trace/handlers.performance"; //$NON-NLS-1$ + public static final String DEBUG_HANDLERS_VERBOSE_FLAG = "/trace/handlers.verbose"; //$NON-NLS-1$ + public static final String DEBUG_OPERATIONS_FLAG = "/trace/operations"; //$NON-NLS-1$ + public static final String DEBUG_OPERATIONS_VERBOSE_FLAG = "/trace/operations.verbose"; //$NON-NLS-1$ + public static final String DEBUG_SHOW_ALL_JOBS_FLAG = "/debug/showAllJobs"; //$NON-NLS-1$ + public static final String DEBUG_STALE_JOBS_FLAG = "/debug/job.stale"; //$NON-NLS-1$ + public static final String DEBUG_DECLARED_IMAGES_FLAG = "/debug/declaredImages"; //$NON-NLS-1$ + public static final String DEBUG_CONTRIBUTIONS_FLAG = "/debug/contributions"; //$NON-NLS-1$ + public static final String DEBUG_HANDLERS_VERBOSE_COMMAND_ID_FLAG = ""; //$NON-NLS-1$ + public static final String EXPERIMENTAL_MENU_FLAG = "/experimental/menus"; //$NON-NLS-1$ + public static final String DEBUG_MPE_FLAG = "/trace/multipageeditor"; //$NON-NLS-1$ + public static final String DEBUG_WORKING_SETS_FLAG = "/debug/workingSets"; //$NON-NLS-1$ + public static boolean DEFAULT = false; public static boolean DEBUG_SWT_GRAPHICS = DEFAULT; @@ -158,47 +182,4 @@ public class Policy { * @since 3.4 */ public static boolean DEBUG_WORKING_SETS = DEFAULT; - - static { - if (getDebugOption("/debug")) { //$NON-NLS-1$ - DEBUG_SWT_GRAPHICS = getDebugOption("/trace/graphics"); //$NON-NLS-1$ - DEBUG_SWT_DEBUG = getDebugOption("/debug/swtdebug"); //$NON-NLS-1$ - DEBUG_SWT_DEBUG_GLOBAL = getDebugOption("/debug/swtdebugglobal"); //$NON-NLS-1$ - DEBUG_DRAG_DROP = getDebugOption("/trace/dragDrop"); //$NON-NLS-1$ - DEBUG_SOURCES = getDebugOption("/trace/sources"); //$NON-NLS-1$ - DEBUG_KEY_BINDINGS = getDebugOption("/trace/keyBindings"); //$NON-NLS-1$ - DEBUG_KEY_BINDINGS_VERBOSE = getDebugOption("/trace/keyBindings.verbose"); //$NON-NLS-1$ - DEBUG_TOOLBAR_DISPOSAL = "true" //$NON-NLS-1$ - .equalsIgnoreCase(Platform.getDebugOption("org.eclipse.jface/trace/toolbarDisposal")); //$NON-NLS-1$ - DEBUG_COMMANDS = getDebugOption("/trace/commands"); //$NON-NLS-1$ - DEBUG_CONTEXTS = getDebugOption("/trace/contexts"); //$NON-NLS-1$ - DEBUG_CONTEXTS_PERFORMANCE = getDebugOption("/trace/contexts.performance"); //$NON-NLS-1$ - DEBUG_CONTEXTS_VERBOSE = getDebugOption("/trace/contexts.verbose"); //$NON-NLS-1$ - DEBUG_HANDLERS = getDebugOption("/trace/handlers"); //$NON-NLS-1$ - DEBUG_HANDLERS_PERFORMANCE = getDebugOption("/trace/handlers.performance"); //$NON-NLS-1$ - DEBUG_HANDLERS_VERBOSE = getDebugOption("/trace/handlers.verbose"); //$NON-NLS-1$ - DEBUG_OPERATIONS = getDebugOption("/trace/operations"); //$NON-NLS-1$ - DEBUG_OPERATIONS_VERBOSE = getDebugOption("/trace/operations.verbose"); //$NON-NLS-1$ - DEBUG_SHOW_ALL_JOBS = getDebugOption("/debug/showAllJobs"); //$NON-NLS-1$ - DEBUG_STALE_JOBS = getDebugOption("/debug/job.stale"); //$NON-NLS-1$ - DEBUG_HANDLERS_VERBOSE_COMMAND_ID = Platform - .getDebugOption(PlatformUI.PLUGIN_ID + "/trace/handlers.verbose.commandId"); //$NON-NLS-1$ - if ("".equals(DEBUG_HANDLERS_VERBOSE_COMMAND_ID)) { //$NON-NLS-1$ - DEBUG_HANDLERS_VERBOSE_COMMAND_ID = null; - } - DEBUG_DECLARED_IMAGES = getDebugOption("/debug/declaredImages"); //$NON-NLS-1$ - DEBUG_CONTRIBUTIONS = getDebugOption("/debug/contributions"); //$NON-NLS-1$ - EXPERIMENTAL_MENU = getDebugOption("/experimental/menus"); //$NON-NLS-1$ - DEBUG_MPE = getDebugOption("/trace/multipageeditor"); //$NON-NLS-1$ - DEBUG_WORKING_SETS = getDebugOption("/debug/workingSets"); //$NON-NLS-1$ - - if (DEBUG_SWT_DEBUG_GLOBAL) { - Device.DEBUG = true; - } - } - } - - private static boolean getDebugOption(String option) { - return "true".equalsIgnoreCase(Platform.getDebugOption(PlatformUI.PLUGIN_ID + option)); //$NON-NLS-1$ - } } diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/part/MultiPageEditorPart.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/part/MultiPageEditorPart.java index 6097c863995..ccb6c0689ea 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/part/MultiPageEditorPart.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/part/MultiPageEditorPart.java @@ -23,7 +23,6 @@ import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.commands.internal.util.Tracing; import org.eclipse.core.runtime.Adapters; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.ISafeRunnable; @@ -124,11 +123,6 @@ public abstract class MultiPageEditorPart extends EditorPart implements IPageCha */ protected static final int PAGE_CONTAINER_SITE = 65535; - /** - * Private tracing output. - */ - private static final String TRACING_COMPONENT = "MPE"; //$NON-NLS-1$ - /** * The active service locator. This value may be null if there is * no selected page, or if the selected page is a control with no site. @@ -879,7 +873,7 @@ protected void pageChange(int newPageIndex) { provider.fireSelectionChanged(event); provider.firePostSelectionChanged(event); } else if (Policy.DEBUG_MPE) { - Tracing.printTrace(TRACING_COMPONENT, "MultiPageEditorPart " + getTitle() //$NON-NLS-1$ + WorkbenchPlugin.getDefault().getTrace().trace(Policy.DEBUG_MPE_FLAG, "MultiPageEditorPart " + getTitle() //$NON-NLS-1$ + " did not propogate selection for " //$NON-NLS-1$ + activeEditor.getTitle()); } From 8e8602f94ea8e0bb8a87ada9dea78376601754a9 Mon Sep 17 00:00:00 2001 From: tuanvtdeptre199 Date: Thu, 11 Jun 2026 09:24:04 +0000 Subject: [PATCH 09/52] Fix selection not updating when checking a tree item on Windows --- .../eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java index 8a6fae213b8..764979cb475 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java @@ -73,6 +73,15 @@ public void checkStateChanged(final CheckStateChangedEvent event) { BusyIndicator.showWhile(treeViewer.getControl().getDisplay(), () -> { if (event.getCheckable().equals(treeViewer)) { + /* + * On Windows, checking an item does not automatically update the tree selection + * like on Linux environment. Force the checked element to become the current + * selection so SelectionListener and CheckListener stay in sync together + */ + Object currentSelection = treeViewer.getStructuredSelection().getFirstElement(); + if (!Objects.equals(currentSelection, event.getElement())) { + treeViewer.setSelection(new StructuredSelection(event.getElement()), true); + } treeItemChecked(event.getElement(), event .getChecked()); } else { From 559f16adafc661785d95aade9e264ed9f0505a1b Mon Sep 17 00:00:00 2001 From: tuanvtdeptre199 Date: Fri, 12 Jun 2026 02:29:32 +0000 Subject: [PATCH 10/52] Fix 1 --- .../src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java | 1 + 1 file changed, 1 insertion(+) diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java index 764979cb475..74adfe8495d 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/ide/dialogs/ResourceTreeAndListGroup.java @@ -23,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.Set; import org.eclipse.core.commands.common.EventManager; From d6555f379315b22d2ae04be63b352aa68c8cbeb2 Mon Sep 17 00:00:00 2001 From: Elsa Zacharia Date: Fri, 26 Sep 2025 00:06:43 +0530 Subject: [PATCH 11/52] optional autocomplete support in chevron pop up Add an optional Autocomplete support in chevron popup with preference toggle in the eclipse Settings->Preference->General page. Introduced a new autocomplete behavior for the chevron popup filter text. As the user types, matching editor names are suggested and the remaining part is auto-filled, improving navigation efficiency within the chevron pop up. Key changes: - Added `chevronAutocompleteBehavior()` to implement auto completion with suggestion. - Retained existing `normalFilterBehavior()` for plain text filtering incase the user wanted to disable the auto complete feature. - Updated `installFilter()` to switch between behaviors based on user preference - Added `isAutocompleteEnabled()` method to check the preference state --- .../swt/AbstractTableInformationControl.java | 61 ++++++++++++++++++- .../ui/internal/WorkbenchMessages.java | 7 ++- .../dialogs/WorkbenchPreferencePage.java | 16 ++++- .../eclipse/ui/internal/messages.properties | 3 + 4 files changed, 83 insertions(+), 4 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/AbstractTableInformationControl.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/AbstractTableInformationControl.java index f4333185d8f..d7e5992bf14 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/AbstractTableInformationControl.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/AbstractTableInformationControl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2018 IBM Corporation and others. + * Copyright (c) 2003, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,6 +13,8 @@ *******************************************************************************/ package org.eclipse.e4.ui.internal.workbench.renderers.swt; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.e4.ui.workbench.swt.internal.copy.SearchPattern; import org.eclipse.e4.ui.workbench.swt.internal.copy.WorkbenchSWTMessages; import org.eclipse.jface.preference.JFacePreferences; @@ -25,6 +27,8 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; @@ -312,6 +316,19 @@ public TableViewer getTableViewer() { return fTableViewer; } + private TableItem suggestCompletionFromTable(String inputText) { + if (inputText == null || inputText.isEmpty()) { + return null; + } + String lowerCaseText = inputText.toLowerCase(); + for (TableItem item : fTableViewer.getTable().getItems()) { + if (item.getText().toLowerCase().startsWith(lowerCaseText)) { + return item; + } + } + return null; + } + protected Text createFilterText(Composite parent) { fFilterText = new Text(parent, SWT.NONE); @@ -371,16 +388,56 @@ private void setInfoSystemColor() { setBackgroundColor(background); } - private void installFilter() { + private void chevronAutocompleteBehavior() { fFilterText.setMessage(WorkbenchSWTMessages.FilteredTree_FilterMessage); fFilterText.setText(""); //$NON-NLS-1$ + setMatcherString(""); //$NON-NLS-1$ + fTableViewer.refresh(); + + fFilterText.addKeyListener(new KeyAdapter() { + @Override + public void keyReleased(KeyEvent e) { + int cursor = fFilterText.getSelection().x; + String input = fFilterText.getText().substring(0, cursor); + setMatcherString(input); + fTableViewer.refresh(); + + if (e.keyCode == SWT.BS || e.keyCode == SWT.DEL || !Character.isLetterOrDigit(e.character)) + return; + + TableItem suggested = suggestCompletionFromTable(input); + if (suggested != null && suggested.getText().length() > input.length()) { + String suggestion = suggested.getText(); + fFilterText.setText(suggestion); + fFilterText.setSelection(input.length(), suggestion.length()); + fTableViewer.setSelection(new StructuredSelection(suggested.getData()), true); + } + } + }); + } + private void normalFilterBehavior() { + fFilterText.setMessage(WorkbenchSWTMessages.FilteredTree_FilterMessage); + fFilterText.setText(""); //$NON-NLS-1$ fFilterText.addModifyListener(e -> { String text = ((Text) e.widget).getText(); setMatcherString(text); + fTableViewer.refresh(); }); } + private void installFilter() { + if (isAutocompleteEnabled()) { + chevronAutocompleteBehavior(); + } else { + normalFilterBehavior(); + } + } + + private boolean isAutocompleteEnabled() { + IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode("org.eclipse.ui.workbench"); //$NON-NLS-1$ + return prefs.getBoolean("ENABLE_AUTOCOMPLETE_IN_CHEVRON", false); //$NON-NLS-1$ + } /** * The string matcher has been modified. The default implementation * refreshes the view and selects the first matched element diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java index cdc17e28774..dbaafa6d898 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2020 IBM Corporation and others. + * Copyright (c) 2005, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -468,6 +468,11 @@ public class WorkbenchMessages extends NLS { public static String PreferenceExportWarning_continue; public static String PreferenceExportWarning_applyAndContinue; + public static String Preference_Enable_Autocomplete_ChevronPopUp; + public static String Preference_Autocomplete; + + public static String Preference_Enable_Autocomplete_ChevronPopUp_ToolTip; + // --- Workbench --- public static String WorkbenchPreference_allowInplaceEditingButton; public static String WorkbenchPreference_useIPersistableEditorButton; diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/WorkbenchPreferencePage.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/WorkbenchPreferencePage.java index 1c6cd5b371c..b266a3d0d3c 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/WorkbenchPreferencePage.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/WorkbenchPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -80,6 +80,8 @@ public class WorkbenchPreferencePage extends PreferencePage implements IWorkbenc private Button showInlineRenameButton; + private Button enableAutocompleteButton; + protected static int MAX_SAVE_INTERVAL = 9999; protected static int MAX_VIEW_LIMIT = 1_000_000; @@ -112,6 +114,7 @@ protected void createSettings(Composite composite) { createStickyCyclePref(composite); createHeapStatusPref(composite); createLargeViewLimitPref(composite); + createAutocompletePref(composite); } /** @@ -388,6 +391,15 @@ protected IPreferenceStore doGetPreferenceStore() { return WorkbenchPlugin.getDefault().getPreferenceStore(); } + protected void createAutocompletePref(Composite parent) { + enableAutocompleteButton = new Button(parent, SWT.CHECK); + enableAutocompleteButton.setText(WorkbenchMessages.Preference_Enable_Autocomplete_ChevronPopUp); + enableAutocompleteButton.setToolTipText(WorkbenchMessages.Preference_Enable_Autocomplete_ChevronPopUp_ToolTip); + IPreferenceStore store = getPreferenceStore(); + boolean enabled = store.getBoolean(WorkbenchMessages.Preference_Autocomplete); + enableAutocompleteButton.setSelection(enabled); + } + /** * @see IWorkbenchPreferencePage */ @@ -423,6 +435,7 @@ protected void performDefaults() { showUserDialogButton.setSelection(store.getDefaultBoolean(IPreferenceConstants.RUN_IN_BACKGROUND)); showHeapStatusButton.setSelection( PrefUtil.getAPIPreferenceStore().getDefaultBoolean(IWorkbenchPreferenceConstants.SHOW_MEMORY_MONITOR)); + enableAutocompleteButton.setSelection(store.getDefaultBoolean(WorkbenchMessages.Preference_Autocomplete)); String defaultRenameMode = store.getDefaultString(IWorkbenchPreferenceConstants.RESOURCE_RENAME_MODE); renameModeInline = !IWorkbenchPreferenceConstants.RESOURCE_RENAME_MODE_DIALOG.equals(defaultRenameMode); @@ -446,6 +459,7 @@ public boolean performOk() { store.setValue(IPreferenceConstants.RUN_IN_BACKGROUND, showUserDialogButton.getSelection()); store.setValue(IPreferenceConstants.WORKBENCH_SAVE_INTERVAL, saveInterval.getIntValue()); store.setValue(IWorkbenchPreferenceConstants.LARGE_VIEW_LIMIT, largeViewLimit.getIntValue()); + store.setValue(WorkbenchMessages.Preference_Autocomplete, enableAutocompleteButton.getSelection()); String renameModeValue = IWorkbenchPreferenceConstants.RESOURCE_RENAME_MODE_INLINE; if (!renameModeInline) { diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties index 0fc6557edeb..61e8627893c 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties @@ -409,6 +409,9 @@ PreferenceExportWarning_title = Possible Unapplied Changes PreferenceExportWarning_message = If you changed preferences and want to export them, ensure you click 'Apply and Continue' before the export. PreferenceExportWarning_continue = &Continue PreferenceExportWarning_applyAndContinue = &Apply and Continue +Preference_Enable_Autocomplete_ChevronPopUp = Enable autocomplete option in chevron popup +Preference_Enable_Autocomplete_ChevronPopUp_ToolTip = Enable autocomplete option to complete text as you type in the chevron popup +Preference_Autocomplete=ENABLE_AUTOCOMPLETE_IN_CHEVRON # --- Workbench --- WorkbenchPreference_allowInplaceEditingButton = Allow in-place &system editors From e400d773b859ce626f6ee35c0de185c3054406e9 Mon Sep 17 00:00:00 2001 From: Andrey Loskutov Date: Fri, 3 Jul 2026 17:28:13 +0200 Subject: [PATCH 12/52] Show proper symlink decorations for broken symlinks Requires fix in platform, see https://github.com/eclipse-platform/eclipse.platform/pull/2798 See https://github.com/eclipse-platform/eclipse.platform/issues/2797 --- .../ui/internal/ide/SymlinkDecorator.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/SymlinkDecorator.java b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/SymlinkDecorator.java index cd82135a07d..a7f0c04c574 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/SymlinkDecorator.java +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/SymlinkDecorator.java @@ -14,8 +14,11 @@ *******************************************************************************/ package org.eclipse.ui.internal.ide; +import java.net.URI; import java.util.Optional; +import org.eclipse.core.filesystem.EFS; +import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourceAttributes; import org.eclipse.core.resources.mapping.ResourceMapping; @@ -25,6 +28,7 @@ import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; +import org.eclipse.ui.internal.ide.dialogs.IDEResourceInfoUtils; /** * Decorate symbolic links @@ -33,12 +37,15 @@ public class SymlinkDecorator implements ILightweightLabelDecorator { private static Optional SYMLINK; + private static final Optional LINK_WARNING; static { SYMLINK = ResourceLocator.imageDescriptorFromBundle( IDEWorkbenchPlugin.IDE_WORKBENCH, "$nl$/icons/full/ovr16/symlink_ovr.svg"); //$NON-NLS-1$ + LINK_WARNING = ResourceLocator.imageDescriptorFromBundle(IDEWorkbenchPlugin.IDE_WORKBENCH, + "$nl$/icons/full/ovr16/linkwarn_ovr.svg"); //$NON-NLS-1$ } @Override @@ -68,8 +75,18 @@ public void decorate(Object element, IDecoration decoration) { IResource resource = Adapters.adapt(element, IResource.class); if (resource != null) { ResourceAttributes resourceAttributes = resource.getResourceAttributes(); - if (resourceAttributes != null && resourceAttributes.isSymbolicLink()) { - SYMLINK.ifPresent(decoration::addOverlay); + if (resourceAttributes != null) { + if (resourceAttributes.isSymbolicLink()) { + SYMLINK.ifPresent(decoration::addOverlay); + URI location = resource.getLocationURI(); + if (location != null) { + IFileInfo fileInfo = IDEResourceInfoUtils.getFileInfo(location); + String linkTarget = fileInfo.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET); + if (linkTarget != null && !fileInfo.exists()) { + LINK_WARNING.ifPresent(t -> decoration.addOverlay(t, IDecoration.TOP_LEFT)); + } + } + } } } } From 7085a3945d402f5b749a40e4bcd26ee5ddc460a8 Mon Sep 17 00:00:00 2001 From: Deepika Udayagiri Date: Wed, 8 Jul 2026 11:36:34 +0530 Subject: [PATCH 13/52] Offer to open/show existing project from Smart Import wizard --- .../datatransfer/DataTransferMessages.java | 8 ++ .../SmartImportRootWizardPage.java | 100 ++++++++++++++++-- .../wizards/datatransfer/messages.properties | 8 ++ 3 files changed, 109 insertions(+), 7 deletions(-) diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/DataTransferMessages.java b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/DataTransferMessages.java index f564865c099..c4fe790ae6e 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/DataTransferMessages.java +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/DataTransferMessages.java @@ -197,6 +197,14 @@ public class DataTransferMessages extends NLS { public static String SmartImportProposals_hideExistingProjects; public static String SmartImportProposals_inspecitionCanceled; public static String SmartImportProposals_errorWhileInspecting; + public static String SmartImportProposals_projectAlreadyOpen_title; + public static String SmartImportProposals_projectAlreadyOpen_message; + public static String SmartImportProposals_projectAlreadyClosed_title; + public static String SmartImportProposals_projectAlreadyClosed_message; + public static String SmartImportProposals_showInProjectExplorer; + public static String SmartImportProposals_openProject; + public static String SmartImportProposals_openProjectFailed; + public static String SmartImportProposals_openFailed; public static String SmartImportReport_importedProjects; public static String SmartImportReport_importedProjectsWithCount; diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/SmartImportRootWizardPage.java b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/SmartImportRootWizardPage.java index 94c470bb766..287ff215943 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/SmartImportRootWizardPage.java +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/SmartImportRootWizardPage.java @@ -34,6 +34,7 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; @@ -41,6 +42,7 @@ import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; +import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ControlDecoration; @@ -62,6 +64,7 @@ import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.wizard.IWizard; import org.eclipse.jface.wizard.ProgressMonitorPart; +import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; @@ -88,7 +91,11 @@ import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.ui.IPageLayout; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; +import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; @@ -100,6 +107,7 @@ import org.eclipse.ui.internal.progress.ProgressManager.JobMonitor; import org.eclipse.ui.internal.registry.WorkingSetDescriptor; import org.eclipse.ui.internal.registry.WorkingSetRegistry; +import org.eclipse.ui.part.ISetSelectionTarget; import org.eclipse.ui.statushandlers.StatusManager; import org.eclipse.ui.wizards.datatransfer.ProjectConfigurator; import org.osgi.framework.FrameworkUtil; @@ -607,14 +615,21 @@ public boolean isChecked(Object element) { } }); tree.addCheckStateListener(event -> { - if (isExistingProject((File) event.getElement()) || isExistingProjectName((File) event.getElement())) { - tree.setChecked(event.getElement(), false); + File file = (File) event.getElement(); + IProject existingProject = findExistingProject(file); + if (existingProject != null) { + tree.setChecked(file, false); + promptAlreadyImportedProject(file, existingProject); + return; + } + if (isExistingProjectName(file)) { + tree.setChecked(file, false); return; } if (event.getChecked()) { - SmartImportRootWizardPage.this.directoriesToImport.add((File) event.getElement()); + SmartImportRootWizardPage.this.directoriesToImport.add(file); } else { - SmartImportRootWizardPage.this.directoriesToImport.remove(event.getElement()); + SmartImportRootWizardPage.this.directoriesToImport.remove(file); } proposalsSelectionChanged(); }); @@ -787,14 +802,19 @@ private String getValue(String s) { } } - protected boolean isExistingProject(File element) { + + protected IProject findExistingProject(File element) { for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { IPath location = project.getLocation(); if (location != null && element.equals(location.toFile())) { - return true; + return project; } } - return false; + return null; + } + + protected boolean isExistingProject(File element) { + return findExistingProject(element) != null; } protected boolean isExistingProjectName(File element) { @@ -802,6 +822,72 @@ protected boolean isExistingProjectName(File element) { return !name.isEmpty() && ResourcesPlugin.getWorkspace().getRoot().getProject(name).exists(); } + private void promptAlreadyImportedProject(File file, IProject project) { + tree.setSelection(new StructuredSelection(file), true); + boolean isOpen = project.isOpen(); + String title = isOpen ? DataTransferMessages.SmartImportProposals_projectAlreadyOpen_title + : DataTransferMessages.SmartImportProposals_projectAlreadyClosed_title; + String message = NLS.bind(isOpen ? DataTransferMessages.SmartImportProposals_projectAlreadyOpen_message + : DataTransferMessages.SmartImportProposals_projectAlreadyClosed_message, project.getName()); + String actionLabel = isOpen ? DataTransferMessages.SmartImportProposals_showInProjectExplorer + : DataTransferMessages.SmartImportProposals_openProject; + + MessageDialog dialog = new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, + new String[] { actionLabel, IDialogConstants.CANCEL_LABEL }, 0); + if (dialog.open() == 0) { + if (isOpen) { + showProjectInExplorer(project); + } else { + openProject(project); + } + if (tree.getCheckedElements().length == 0) { + getContainer().getShell().getDisplay().asyncExec(() -> { + if (getContainer() instanceof WizardDialog wizardDialog) { + wizardDialog.close(); + } + }); + } + } + } + + private void openProject(IProject project) { + try { + getContainer().run(true, true, monitor -> { + try { + project.open(monitor); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } + }); + } catch (InvocationTargetException | InterruptedException e) { + StatusManager + .getManager().handle( + new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, + NLS.bind(DataTransferMessages.SmartImportProposals_openProjectFailed, + project.getName()), + e.getCause() != null ? e.getCause() : e), + StatusManager.LOG | StatusManager.SHOW); + return; + } + showProjectInExplorer(project); + } + + private void showProjectInExplorer(IProject project) { + IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (window == null || window.getActivePage() == null) { + return; + } + try { + IViewPart view = window.getActivePage().showView(IPageLayout.ID_PROJECT_EXPLORER); + if (view instanceof ISetSelectionTarget target) { + target.selectReveal(new StructuredSelection(project)); + } + } catch (PartInitException e) { + StatusManager.getManager().handle(new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, + DataTransferMessages.SmartImportProposals_openFailed, e), StatusManager.LOG); + } + } + protected void validatePage() { // reset error message setErrorMessage(null); diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/messages.properties b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/messages.properties index 0353c8a6a20..db7514bf651 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/messages.properties +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/wizards/datatransfer/messages.properties @@ -200,6 +200,14 @@ SmartImportProposals_importAs=Import as SmartImportProposals_hideExistingProjects=&Hide already open projects SmartImportProposals_inspecitionCanceled=Inspeciton canceled SmartImportProposals_errorWhileInspecting=Error while inspecting: {0} +SmartImportProposals_projectAlreadyOpen_title=Project Already Open +SmartImportProposals_projectAlreadyOpen_message=The project ''{0}'' is already open in the workspace. +SmartImportProposals_projectAlreadyClosed_title=Project Already Exists (Closed) +SmartImportProposals_projectAlreadyClosed_message=The project ''{0}'' already exists in the workspace but is currently closed. +SmartImportProposals_showInProjectExplorer=&Show In Project Explorer +SmartImportProposals_openProject=&Open Project +SmartImportProposals_openProjectFailed=Failed to open project ''{0}'' +SmartImportProposals_openFailed=Unable to open project in Explorer view SmartImportJob_detectAndConfigureProjects=Detecting and configuring nested projects SmartImportJob_configuringSelectedDirectories=Configuring selected directories SmartImportJob_configuring=Configuring project {0} From 51eb713ea2283a732d58c64229a7d67e9d8ae894 Mon Sep 17 00:00:00 2001 From: Elsa Zacharia Date: Sun, 30 Aug 2026 23:27:47 +0530 Subject: [PATCH 14/52] Add expand/collapse hover option in Search Results tree view When hovering over a top-level project node in the tree layout, an option appears showing expand or collapse based on the node's current state. This is to individually expand or collapse tree parent items. --- .../ui/text/AbstractTextSearchViewPage.java | 152 ++++++++++++++++++ .../search2/internal/ui/SearchMessages.java | 2 + .../internal/ui/SearchMessages.properties | 2 + 3 files changed, 156 insertions(+) diff --git a/bundles/org.eclipse.search/newsearch/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java b/bundles/org.eclipse.search/newsearch/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java index 3d0a2bb2646..7a159086e55 100644 --- a/bundles/org.eclipse.search/newsearch/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java +++ b/bundles/org.eclipse.search/newsearch/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java @@ -26,14 +26,24 @@ import org.osgi.framework.FrameworkUtil; import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MouseTrackAdapter; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.ToolItem; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IProgressMonitor; @@ -54,6 +64,7 @@ import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.util.OpenStrategy; +import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.IOpenListener; @@ -279,6 +290,8 @@ public void selectionChanged(SelectionChangedEvent event) { public static final int FLAG_LAYOUT_TREE = 2; private OpenAndLinkWithEditorHelper openAndLinkWithEditorHelper; + private Shell fHoverShell; + private TreeItem fHoveredItem; /** * This constructor must be passed a combination of layout flags combined @@ -709,6 +722,8 @@ public void setLayout(int layout) { } private void disposeViewer() { + disposeHoverShell(); + fHoveredItem = null; fViewer.removeSelectionChangedListener(fViewerAdapter); fViewer.getControl().dispose(); fViewer = null; @@ -746,6 +761,7 @@ private void createViewer(Composite parent, int layout) { configureTreeViewer(viewer); fCollapseAllAction.setViewer(viewer); fExpandAllAction.setViewer(viewer); + installHoverExpandSupport(viewer); } fCopyToClipboardAction.setViewer(fViewer); @@ -1559,5 +1575,141 @@ public Integer getElementLimit() { return fElementLimit; } + private void installHoverExpandSupport(TreeViewer viewer) { + Tree tree = viewer.getTree(); + + tree.addMouseMoveListener(e -> { + TreeItem item = tree.getItem(new Point(e.x, e.y)); + + boolean overShell = fHoverShell != null && !fHoverShell.isDisposed() + && fHoverShell.getBounds().contains(tree.toDisplay(e.x, e.y)); + if (item == null || item.getParentItem() != null) { + if (!overShell) { + disposeHoverShell(); + fHoveredItem = null; + } + return; + } + Rectangle rowBounds = item.getBounds(); + Rectangle extRowBounds = new Rectangle(rowBounds.x, rowBounds.y, + rowBounds.width + 20, rowBounds.height); + boolean overRow = extRowBounds.contains(e.x, e.y); + if (!overRow) { + if (!overShell) { + disposeHoverShell(); + fHoveredItem = null; + } + return; + } + if (item == fHoveredItem) { + return; + } + disposeHoverShell(); + fHoveredItem = item; + + Object element = item.getData(); + if (element == null) { + return; + } + boolean expanded = viewer.getExpandedState(element); + showHoverShell(tree, item, element, viewer, expanded); + }); + + tree.addMouseTrackListener(new MouseTrackAdapter() { + @Override + public void mouseExit(org.eclipse.swt.events.MouseEvent e) { + if (fHoverShell == null || fHoverShell.isDisposed()) { + fHoveredItem = null; + } + } + }); + } + + /** + * Creates and displays an option to expand or collapse any single item + * + * @param expanded + * whether the parent is currently expanded + */ + private void showHoverShell(Tree tree, TreeItem item, Object element, TreeViewer viewer, boolean expanded) { + org.eclipse.jface.resource.ImageDescriptor desc = expanded + ? fCollapseAllAction.getImageDescriptor() + : fExpandAllAction.getImageDescriptor(); + if (desc == null) { + return; + } + Image actionImage = desc.createImage(false); + if (actionImage == null) { + return; + } + + Shell shell = new Shell(tree.getShell(), SWT.TOOL | SWT.ON_TOP | SWT.NO_FOCUS | SWT.NO_TRIM); + shell.setBackground(tree.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + ToolBar tb = new ToolBar(shell, SWT.FLAT); + ToolItem ti = new ToolItem(tb, SWT.PUSH); + ti.setImage(actionImage); + ti.setToolTipText(expanded ? SearchMessages.CollapseItemAction_tooltip : SearchMessages.ExpandItemAction_tooltip); + + shell.addListener(SWT.Dispose, e -> actionImage.dispose()); + shell.addMouseTrackListener(new MouseTrackAdapter() { + @Override + public void mouseExit(org.eclipse.swt.events.MouseEvent e) { + disposeHoverShell(); + fHoveredItem = null; + } + }); + + ti.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { + @Override + public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { + if (!viewer.getControl().isDisposed()) { + viewer.getControl().setRedraw(false); + try { + if (expanded) { + viewer.collapseToLevel(element, AbstractTreeViewer.ALL_LEVELS); + } else { + viewer.expandToLevel(element, AbstractTreeViewer.ALL_LEVELS); + } + } finally { + viewer.getControl().setRedraw(true); + } + } + shell.dispose(); + fHoverShell = null; + fHoveredItem = null; + } + }); + + tb.pack(); + shell.pack(); + + Rectangle textBounds = item.getTextBounds(0); + int shellHeight = shell.getSize().y; + int shellWidth = shell.getSize().x; + int centredY = textBounds.y + (textBounds.height - shellHeight) / 2; + GC gc = new GC(tree); + int textWidth; + try { + textWidth = gc.textExtent(item.getText()).x; + } finally { + gc.dispose(); + } + int desiredX = textBounds.x + textWidth + 2; + Rectangle treeDisplayBounds = tree.getDisplay().map(tree, null, tree.getClientArea()); + int maxX = treeDisplayBounds.x + treeDisplayBounds.width - shellWidth - 2; + Point desiredDisplay = tree.toDisplay(desiredX, centredY); + int finalX = Math.min(desiredDisplay.x, maxX); + shell.setLocation(finalX, desiredDisplay.y); + shell.setVisible(true); + + fHoverShell = shell; + } + + private void disposeHoverShell() { + if (fHoverShell != null && !fHoverShell.isDisposed()) { + fHoverShell.dispose(); + } + fHoverShell = null; + } } diff --git a/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.java b/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.java index 75adbe4b6a2..62edc7749da 100644 --- a/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.java +++ b/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.java @@ -84,6 +84,8 @@ private SearchMessages() { public static String CollapseAllAction_1; public static String ExpandAllAction_label; public static String ExpandAllAction_tooltip; + public static String ExpandItemAction_tooltip; + public static String CollapseItemAction_tooltip; public static String SearchView_error_noResultPage; public static String InternalSearchUI_error_unexpected; public static String NewSearchUI_error_title; diff --git a/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.properties b/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.properties index 0973f594f8a..dfc4a623359 100644 --- a/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.properties +++ b/bundles/org.eclipse.search/newsearch/org/eclipse/search2/internal/ui/SearchMessages.properties @@ -57,6 +57,8 @@ CollapseAllAction_0=Collapse All CollapseAllAction_1=Collapse All ExpandAllAction_label=Expand All ExpandAllAction_tooltip=Expand All +ExpandItemAction_tooltip=Expand item +CollapseItemAction_tooltip=Collapse item SearchView_error_noResultPage=No search result page found for search result class {0} SearchView_empty_search_label=No search results available. Start a search from the search dialog... InternalSearchUI_error_unexpected=An unexpected exception occurred during search From ff395586bf1aae2af89475ad8ec55109ee73309c Mon Sep 17 00:00:00 2001 From: Eclipse Platform Bot Date: Mon, 31 Aug 2026 20:00:07 +0000 Subject: [PATCH 15/52] Version bump(s) for 4.42 stream --- bundles/org.eclipse.search/META-INF/MANIFEST.MF | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bundles/org.eclipse.search/META-INF/MANIFEST.MF b/bundles/org.eclipse.search/META-INF/MANIFEST.MF index 726e86f7caf..969c9033d31 100644 --- a/bundles/org.eclipse.search/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.search/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.search; singleton:=true -Bundle-Version: 3.19.0.qualifier +Bundle-Version: 3.19.100.qualifier Bundle-Activator: org.eclipse.search.internal.ui.SearchPlugin Bundle-ActivationPolicy: lazy Bundle-Vendor: %providerName From a62f72a9e47b3db4a05ef7c3ae1f86236cc54783 Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Tue, 22 Sep 2026 14:12:07 +0200 Subject: [PATCH 16/52] Show Open/Close Project for mixed selections in Project Explorer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Selecting everything with Ctrl+A in the Project Explorer also selects files and non-resource elements such as working set headers. The provider enablement required every element to be a resource or working set, and the actions required every selected resource to be a project, so Open Project and Close Project disappeared for such selections. The provider is now always enabled and only skips selections that contain no resource or working set at all. The project actions enable when the selection contains a project and run on the projects only. Close Unrelated Projects no longer keeps the targets of an earlier selection when the new one has no resources, and Refresh is left out for elements it cannot refresh. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/3790 Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../ui/actions/CloseResourceAction.java | 19 +- .../actions/CloseUnrelatedProjectsAction.java | 5 +- .../ui/actions/OpenResourceAction.java | 18 +- .../plugin.xml | 9 +- .../actions/ResourceMgmtActionProvider.java | 13 +- .../CloseUnrelatedProjectsActionTest.java | 11 ++ .../ResourceMgmtActionProviderTests.java | 185 ++++++++++++++++++ 7 files changed, 239 insertions(+), 21 deletions(-) diff --git a/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseResourceAction.java b/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseResourceAction.java index fd6aee00f48..bc454cb2992 100644 --- a/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseResourceAction.java +++ b/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseResourceAction.java @@ -16,7 +16,6 @@ package org.eclipse.ui.actions; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IFile; @@ -180,7 +179,7 @@ protected void invokeOperation(IResource resource, IProgressMonitor monitor) thr @Override public void run() { // Get the items to close. - List projects = getSelectedResources(); + List projects = getActionResources(); if (projects == null || projects.isEmpty()) { // no action needs to be taken since no projects are selected return; @@ -229,14 +228,14 @@ protected boolean updateSelection(IStructuredSelection s) { // don't call super since we want to enable if open project is selected. setText(defaultText); setToolTipText(defaultToolTip); - if (!selectionIsOfType(IResource.PROJECT)) { + List projects = getSelectedResources().stream() + .filter(IProject.class::isInstance).map(IProject.class::cast).toList(); + if (projects.isEmpty()) { return false; } boolean hasOpenProjects = false; - Iterator resources = getSelectedResources().iterator(); - while (resources.hasNext()) { - IProject currentResource = (IProject) resources.next(); + for (IProject currentResource : projects) { if (currentResource.isOpen()) { if (hasOpenProjects) { setText(pluralText); @@ -258,7 +257,7 @@ public synchronized void resourceChanged(IResourceChangeEvent event) { // Warning: code duplicated in OpenResourceAction List sel = getSelectedResources(); // don't bother looking at delta if selection not applicable - if (selectionIsOfType(IResource.PROJECT)) { + if (sel.stream().anyMatch(IProject.class::isInstance)) { IResourceDelta delta = event.getDelta(); if (delta != null) { IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED); @@ -280,6 +279,12 @@ protected synchronized List getSelectedResources() { return super.getSelectedResources(); } + @Override + protected List getActionResources() { + // a mixed selection also contains files, which the IProject casts reject + return super.getActionResources().stream().filter(IProject.class::isInstance).toList(); + } + @Override protected synchronized List getSelectedNonResources() { return super.getSelectedNonResources(); diff --git a/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseUnrelatedProjectsAction.java b/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseUnrelatedProjectsAction.java index 65f94ba9a21..285f7edc107 100644 --- a/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseUnrelatedProjectsAction.java +++ b/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/CloseUnrelatedProjectsAction.java @@ -198,6 +198,8 @@ private void initAction(){ protected void clearCache() { super.clearCache(); oldSelection = Collections.emptyList(); + // a selection without resources matches the reset oldSelection and must not keep old targets + projectsToClose = new ArrayList<>(); selectionDirty = true; } @@ -260,7 +262,8 @@ protected List getSelectedResources() { @Override public void resourceChanged(IResourceChangeEvent event) { // don't bother looking at delta if selection not applicable - if (selectionIsOfType(IResource.PROJECT)) { + List selectedResources = super.getSelectedResources(); + if (selectedResources.stream().anyMatch(IProject.class::isInstance)) { IResourceDelta delta = event.getDelta(); if (delta != null) { IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED); diff --git a/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/OpenResourceAction.java b/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/OpenResourceAction.java index dd0a8693885..cd9bb2029bb 100644 --- a/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/OpenResourceAction.java +++ b/bundles/org.eclipse.ui.ide/extensions/org/eclipse/ui/actions/OpenResourceAction.java @@ -140,7 +140,7 @@ protected String getProblemsTitle() { private boolean hasOtherClosedProjects() { //count the closed projects in the selection int closedInSelection = 0; - for (IResource project : getSelectedResources()) { + for (IResource project : getActionResources()) { if (!((IProject) project).isOpen()) { closedInSelection++; } @@ -155,6 +155,12 @@ protected void invokeOperation(IResource resource, IProgressMonitor monitor) thr ((IProject) resource).open(IResource.BACKGROUND_REFRESH, monitor); } + @Override + protected List getActionResources() { + // a mixed selection also contains files, which the IProject casts reject + return super.getActionResources().stream().filter(IProject.class::isInstance).toList(); + } + /** * Returns the preference for whether to open required projects when opening * a project. Consults the preference and prompts the user if necessary. @@ -191,7 +197,7 @@ public void resourceChanged(IResourceChangeEvent event) { // Warning: code duplicated in CloseResourceAction List sel = getSelectedResources(); // don't bother looking at delta if selection not applicable - if (selectionIsOfType(IResource.PROJECT)) { + if (sel.stream().anyMatch(IProject.class::isInstance)) { IResourceDelta delta = event.getDelta(); if (delta != null) { IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED); @@ -322,13 +328,15 @@ protected boolean updateSelection(IStructuredSelection s) { // selected. setText(IDEWorkbenchMessages.OpenResourceAction_text); setToolTipText(IDEWorkbenchMessages.OpenResourceAction_toolTip); - if (!selectionIsOfType(IResource.PROJECT)) { + List projects = getSelectedResources().stream() + .filter(IProject.class::isInstance).map(IProject.class::cast).toList(); + if (projects.isEmpty()) { return false; } boolean hasClosedProjects = false; - for (IResource currentResource : getSelectedResources()) { - if (!((IProject) currentResource).isOpen()) { + for (IProject currentResource : projects) { + if (!currentResource.isOpen()) { if (hasClosedProjects) { setText(IDEWorkbenchMessages.OpenResourceAction_text_plural); setToolTipText(IDEWorkbenchMessages.OpenResourceAction_toolTip_plural); diff --git a/bundles/org.eclipse.ui.navigator.resources/plugin.xml b/bundles/org.eclipse.ui.navigator.resources/plugin.xml index 7eec1464661..3eed4c57ba0 100644 --- a/bundles/org.eclipse.ui.navigator.resources/plugin.xml +++ b/bundles/org.eclipse.ui.navigator.resources/plugin.xml @@ -237,13 +237,8 @@ class="org.eclipse.ui.internal.navigator.resources.actions.ResourceMgmtActionProvider" id="org.eclipse.ui.navigator.resources.ResourceMgmtActions"> - - - - - - - + + diff --git a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ResourceMgmtActionProvider.java b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ResourceMgmtActionProvider.java index 28111551293..2e313510f44 100644 --- a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ResourceMgmtActionProvider.java +++ b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ResourceMgmtActionProvider.java @@ -22,9 +22,11 @@ import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.WorkspaceJob; +import org.eclipse.core.runtime.Adapters; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; @@ -114,6 +116,9 @@ public void fillActionBars(IActionBars actionBars) { @Override public void fillContextMenu(IMenuManager menu) { IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); + if (!selection.isEmpty() && selection.stream().noneMatch(ResourceMgmtActionProvider::isResourceOrWorkingSet)) { + return; + } boolean hasOpenProjects = false; boolean hasClosedProjects = false; boolean hasBuilder = true; // false if any project is closed or does not have builder @@ -145,7 +150,9 @@ public void fillContextMenu(IMenuManager menu) { // a non-project selection. // Put another way: the 'refresh' item is NOT shown if ALL selections are closed // projects. - if (hasOpenProjects || selectionContainsNonProject) { + // RefreshAction rejects elements that are neither resources nor working sets + if ((hasOpenProjects || selectionContainsNonProject) + && selection.stream().allMatch(ResourceMgmtActionProvider::isResourceOrWorkingSet)) { refreshAction.selectionChanged(selection); menu.appendToGroup(ICommonMenuConstants.GROUP_BUILD, refreshAction); menu.appendToGroup(ICommonMenuConstants.GROUP_BUILD, new Separator()); @@ -162,6 +169,10 @@ public void fillContextMenu(IMenuManager menu) { } } + private static boolean isResourceOrWorkingSet(Object element) { + return element instanceof IWorkingSet || Adapters.adapt(element, IResource.class) != null; + } + private static List selectionToProjects(IStructuredSelection selection) { if (selection == null) { return Collections.emptyList(); diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/CloseUnrelatedProjectsActionTest.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/CloseUnrelatedProjectsActionTest.java index b6ae59c39d2..ef6839baf4b 100644 --- a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/CloseUnrelatedProjectsActionTest.java +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/CloseUnrelatedProjectsActionTest.java @@ -119,6 +119,17 @@ private static void processUIEvents() { } } + @Test + public void testDisabledWhenSelectionHasNoResources() throws Exception { + CloseUnrelatedProjectsAction action = new CloseUnrelatedProjectsAction(() -> shell); + + select(action, a); + assertTrue(action.isEnabled(), "action must be enabled while unrelated open project C exists"); + + select(action, new Object()); + assertFalse(action.isEnabled(), "action must not keep the targets of the previous selection"); + } + @Test public void testDisabledAfterAllUnrelatedProjectsClosedAndSelectionChanges() throws Exception { CloseUnrelatedProjectsAction action = new CloseUnrelatedProjectsAction(() -> shell); diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/ResourceMgmtActionProviderTests.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/ResourceMgmtActionProviderTests.java index 128451a678b..bc4e5ff21f9 100644 --- a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/ResourceMgmtActionProviderTests.java +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/resources/ResourceMgmtActionProviderTests.java @@ -10,10 +10,14 @@ *******************************************************************************/ package org.eclipse.ui.tests.navigator.resources; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.util.List; + import org.eclipse.core.resources.ICommand; +import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; @@ -26,8 +30,12 @@ import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.actions.ActionContext; +import org.eclipse.ui.actions.CloseResourceAction; +import org.eclipse.ui.actions.OpenResourceAction; +import org.eclipse.ui.internal.ide.misc.ProjectReferenceGraph; import org.eclipse.ui.internal.navigator.NavigatorContentService; import org.eclipse.ui.internal.navigator.extensions.CommonActionExtensionSite; import org.eclipse.ui.internal.navigator.resources.actions.ResourceMgmtActionProvider; @@ -118,6 +126,158 @@ public void testFillContextMenu_openProjectNoBuilderSelection() throws CoreExcep } } + /** + * A file selected together with an open project keeps Close Project present + * and enabled. + */ + @Test + public void testFillContextMenu_fileAndOpenProjectSelection_closeProjectEnabled() + throws CoreException, InterruptedException { + IProject openProj = ResourcesPlugin.getWorkspace().getRoot().getProject("Test"); + openProj.open(null); + // Close Unrelated Projects answers its enablement from the cached graph + assertTrue(ProjectReferenceGraph.getInstance().refresh(null), + "the project reference graph did not become current"); + ResourceMgmtActionProvider provider = providerForObjects(_p1, openProj.getFile(".project")); + provider.fillContextMenu(manager); + assertTrue(menuHasContribution("org.eclipse.ui.CloseResourceAction"), + "Close Project should be in the menu"); + assertTrue(isMenuContributionEnabled("org.eclipse.ui.CloseResourceAction"), + "Close Project should be enabled when open projects are in the selection"); + assertTrue(menuHasContribution("org.eclipse.ui.CloseUnrelatedProjectsAction"), + "Close Unrelated Projects should be in the menu"); + assertTrue(isMenuContributionEnabled("org.eclipse.ui.CloseUnrelatedProjectsAction"), + "Close Unrelated Projects should be enabled when open projects are in the selection"); + } + + /** + * An open project selected together with a non-resource element, such as a + * working set header, gets Close Project but not the Refresh it cannot run. + */ + @Test + public void testFillContextMenu_mixedSelectionOpenProjectAndNonAdaptableElement() throws CoreException { + IProject openProj = ResourcesPlugin.getWorkspace().getRoot().getProject("Test"); + openProj.open(null); + Object nonResource = new Object(); + ResourceMgmtActionProvider provider = providerForObjects(openProj, nonResource); + provider.fillContextMenu(manager); + checkMenuHasCorrectContributions(false, false, false, true, true); + } + + /** + * Mixed selections reach the provider through the navigator's action service, + * which evaluates its enablement from plugin.xml. + */ + @Test + public void testActionService_mixedSelections() throws CoreException { + IProject openProj = ResourcesPlugin.getWorkspace().getRoot().getProject("Test"); + openProj.open(null); + _p2.close(null); + Object nonResource = new Object(); + + assertTrue(actionServiceMenuHas( + new StructuredSelection(new Object[] { openProj, openProj.getFile(".project"), nonResource }), + CloseResourceAction.ID), "Close Project must be offered for an open project in a mixed selection"); + assertTrue(actionServiceMenuHas(new StructuredSelection(new Object[] { _p2, openProj.getFile(".project"), nonResource }), + OpenResourceAction.ID), "Open Project must be offered for a closed project in a mixed selection"); + } + + /** + * A closed project in a mixed selection is what Open Project runs on. + */ + @Test + public void testOpenResourceAction_closedProjectInMixedSelection() throws CoreException { + _p2.close(null); + IFile file = _project.getFile(".project"); + var action = new OpenResourceAction(() -> _commonNavigator.getViewSite().getShell()) { + List exposedActionResources() { + return getActionResources(); + } + }; + action.selectionChanged(new StructuredSelection(new Object[] { _p2, file, new Object() })); + + assertTrue(action.isEnabled(), "Open Project must be enabled for a closed project in a mixed selection"); + assertEquals(List.of(_p2), action.exposedActionResources()); + } + + private boolean actionServiceMenuHas(IStructuredSelection selection, String actionId) { + MenuManager menu = new MenuManager(); + menu.add(new GroupMarker(ICommonMenuConstants.GROUP_BUILD)); + _actionService.setContext(new ActionContext(selection)); + _actionService.fillContextMenu(menu); + for (IContributionItem item : menu.getItems()) { + if (actionId.equals(item.getId()) && item.isEnabled()) { + return true; + } + } + return false; + } + + /** + * A selection without any resource or working set gets no entries. + */ + @Test + public void testFillContextMenu_nonResourceSelectionOnly() { + ResourceMgmtActionProvider provider = providerForObjects(new Object()); + provider.fillContextMenu(manager); + checkMenuHasCorrectContributions(false, false, false, false, false); + } + + /** + * Open projects selected together with their child folders still get Close + * Project. + */ + @Test + public void testFillContextMenu_twoOpenProjectsWithChildResourcesSelection() throws CoreException { + IFolder srcFolder = _project.getFolder("src"); + IFolder binFolder = _project.getFolder("bin"); + ResourceMgmtActionProvider provider = providerForObjects(_p1, _p2, srcFolder, binFolder); + provider.fillContextMenu(manager); + checkMenuHasCorrectContributions(false, true, false, true, true); + } + + /** + * Close Project runs on the projects of a mixed selection only. + */ + @Test + public void testCloseResourceAction_actionResourcesContainProjectsOnly() throws CoreException { + IProject openProj = ResourcesPlugin.getWorkspace().getRoot().getProject("Test"); + openProj.open(null); + IFile projectFile = openProj.getFile(".project"); + StructuredSelection mixed = new StructuredSelection(new Object[] { openProj, projectFile, new Object() }); + + var action = new CloseResourceAction(() -> _commonNavigator.getViewSite().getShell()) { + List exposedActionResources() { + return getActionResources(); + } + }; + action.selectionChanged(mixed); + + assertEquals(List.of(openProj), action.exposedActionResources(), + "Close Project must operate on projects only, not files or non-resource elements"); + } + + /** + * Open Project runs on the projects of a mixed selection only. + */ + @Test + public void testOpenResourceAction_actionResourcesContainProjectsOnly() throws CoreException { + IProject openProj = ResourcesPlugin.getWorkspace().getRoot().getProject("Test"); + openProj.open(null); + IFile projectFile = openProj.getFile(".project"); + StructuredSelection mixed = new StructuredSelection(new Object[] { openProj, projectFile, new Object() }); + + var action = new OpenResourceAction(() -> _commonNavigator.getViewSite().getShell()) { + List exposedActionResources() { + return getActionResources(); + } + }; + action.selectionChanged(mixed); + + assertEquals(List.of(openProj), action.exposedActionResources(), + "Open Project must operate on projects only, not files or non-resource elements"); + } + /** * Test for 'open project' that doesn't have a builder attached - only 'open * project' should be disabled @@ -158,6 +318,19 @@ public void testFillContextMenu_openProjectWithBuilderSelection() throws CoreExc } } + /* + * Return a provider for a mixed/arbitrary selection (Object[]) + */ + private ResourceMgmtActionProvider providerForObjects(Object... selectedElements) { + ICommonActionExtensionSite cfg = new CommonActionExtensionSite("NA", "NA", + CommonViewerSiteFactory.createCommonViewerSite(_commonNavigator.getViewSite()), + (NavigatorContentService) _contentService, _viewer); + ResourceMgmtActionProvider provider = new ResourceMgmtActionProvider(); + provider.setContext(new ActionContext(new StructuredSelection(selectedElements))); + provider.init(cfg); + return provider; + } + /* * Return a provider, given the selected navigator items */ @@ -206,4 +379,16 @@ private boolean menuHasContribution(String contribution) { return false; } + /* + * Check whether the named menu entry is enabled + */ + private boolean isMenuContributionEnabled(String contribution) { + for (IContributionItem thisItem : manager.getItems()) { + if (thisItem.getId() != null && thisItem.getId().equals(contribution)) { + return thisItem.isEnabled(); + } + } + return false; + } + } From a8d3892ac611cdd968d2d5e76f89dc5e425dcee1 Mon Sep 17 00:00:00 2001 From: Carsten Hammer Date: Sat, 12 Sep 2026 18:20:50 +0200 Subject: [PATCH 17/52] Count distinct files across the complete CompositeChange tree The preview file count depended on the first child's shape and could change when sibling groups were reordered. Traverse composite children and identify distinct workspace files from leaf change metadata instead. Handle opaque multi-file changes without exposing selectable children, and retain the existing selection-independent overview semantics. Add 13 JUnit regression tests to the existing LTK core test suite. Assisted-by: OpenAI ChatGPT Signed-off-by: Carsten Hammer --- .../ltk/core/refactoring/CompositeChange.java | 55 ++++- .../ltk/core/refactoring/tests/AllTests.java | 3 +- .../tests/CompositeChangeTest.java | 198 ++++++++++++++++++ 3 files changed, 245 insertions(+), 11 deletions(-) create mode 100644 tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/CompositeChangeTest.java diff --git a/bundles/org.eclipse.ltk.core.refactoring/src/org/eclipse/ltk/core/refactoring/CompositeChange.java b/bundles/org.eclipse.ltk.core.refactoring/src/org/eclipse/ltk/core/refactoring/CompositeChange.java index 70f09caa42c..0e80c069508 100644 --- a/bundles/org.eclipse.ltk.core.refactoring/src/org/eclipse/ltk/core/refactoring/CompositeChange.java +++ b/bundles/org.eclipse.ltk.core.refactoring/src/org/eclipse/ltk/core/refactoring/CompositeChange.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2022 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -16,9 +16,12 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Set; +import org.eclipse.core.runtime.Adapters; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; @@ -27,6 +30,9 @@ import org.eclipse.core.runtime.SafeRunner; import org.eclipse.core.runtime.SubMonitor; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; + import org.eclipse.ltk.internal.core.refactoring.RefactoringCoreMessages; import org.eclipse.ltk.internal.core.refactoring.RefactoringCorePlugin; @@ -510,22 +516,51 @@ public String toString() { } /** - * @return Amount of changed files + * Returns the number of distinct workspace files identified by this change tree. + * Nested composite changes are traversed, and files affected by more than one + * change are counted only once. For non-composite changes, files are obtained + * from {@link Change#getAffectedObjects()}; when those objects are unknown, + * {@link Change#getModifiedElement()} is used instead. Elements can be files or + * adapt to {@link IFile} or {@link IResource}. + *

+ * Elements that do not identify a file are not counted. This method does not + * inspect workspace contents or expand folders. It counts all changes, + * independently of their enablement state, without modifying the change tree. + *

+ * + * @return the number of distinct identified files * @since 3.13 */ public int getFilenumber() { - if(fChanges.size()>0) { - if (fChanges.get(0) instanceof CompositeChange) { - CompositeChange obj= (CompositeChange) fChanges.get(0); - return obj.getAmount(); + Set files= new HashSet<>(); + collectFiles(this, files); + return files.size(); + } + + private static void collectFiles(Change change, Set files) { + if (change instanceof CompositeChange composite) { + for (Change child : composite.getChildren()) { + collectFiles(child, files); + } + } else { + Object[] affectedObjects= change.getAffectedObjects(); + if (affectedObjects == null) { + addFile(change.getModifiedElement(), files); + } else { + for (Object affected : affectedObjects) { + addFile(affected, files); + } } - return 1; } - return 0; } - private int getAmount() { - return fChanges.size(); + private static void addFile(Object element, Set files) { + IFile file= Adapters.adapt(element, IFile.class); + if (file != null) { + files.add(file); + } else if (Adapters.adapt(element, IResource.class) instanceof IFile resourceFile) { + files.add(resourceFile); + } } } diff --git a/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/AllTests.java b/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/AllTests.java index c71b337a2bf..2c4d79e2f8b 100644 --- a/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/AllTests.java +++ b/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/AllTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -24,6 +24,7 @@ @Suite @SelectClasses({ + CompositeChangeTest.class, RefactoringContextTest.class, XmlProcessorFactoryLtkTest.class, ParticipantTests.class, diff --git a/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/CompositeChangeTest.java b/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/CompositeChangeTest.java new file mode 100644 index 00000000000..8b1dc77e771 --- /dev/null +++ b/tests/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/CompositeChangeTest.java @@ -0,0 +1,198 @@ +/******************************************************************************* + * Copyright (c) 2026 Carsten Hammer and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.ltk.core.refactoring.tests; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jface.text.Document; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.CompositeChange; +import org.eclipse.ltk.core.refactoring.NullChange; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.TextFileChange; + +public class CompositeChangeTest { + + @Test + public void testEmptyChanges() { + assertEquals(0, composite().getFilenumber()); + assertEquals(0, composite(composite()).getFilenumber()); + } + + @Test + public void testDirectFileChanges() { + assertEquals(2, composite(textChange("/project/A.txt"), textChange("/project/B.txt")).getFilenumber()); + } + + @Test + public void testAllSiblingGroupsAreCounted() { + assertEquals(3, composite( + composite(textChange("/project/A.txt")), + composite(textChange("/project/B.txt"), textChange("/project/C.txt"))).getFilenumber()); + assertEquals(3, composite( + composite(textChange("/project/B.txt"), textChange("/project/C.txt")), + composite(textChange("/project/A.txt"))).getFilenumber()); + } + + @Test + public void testMixedAndDeeplyNestedChanges() { + CompositeChange nested= composite(composite(composite(textChange("/project/B.txt")))); + nested.markAsSynthetic(); + assertEquals(3, composite(textChange("/project/A.txt"), nested, + composite(), textChange("/project/C.txt")).getFilenumber()); + } + + @Test + public void testSeveralChangesToTheSameFileAreCountedOnce() { + assertEquals(1, composite(composite(textChange("/project/A.txt"), textChange("/project/A.txt")), + textChange("/project/A.txt")).getFilenumber()); + } + + @Test + public void testEqualNamesInDifferentProjectsAreDifferentFiles() { + assertEquals(2, composite(textChange("/one/A.txt"), textChange("/two/A.txt")).getFilenumber()); + } + + @Test + public void testOpaqueChangeCanAffectSeveralFiles() { + IFile first= file("/project/A.txt"); + IFile second= file("/project/B.txt"); + Change atomic= change(null, first, second, first); + TextFileChange duplicate= textChange("/project/B.txt"); + CompositeChange root= composite(atomic, duplicate); + assertEquals(2, root.getFilenumber()); + assertArrayEquals(new Change[] { atomic, duplicate }, root.getChildren()); + assertSame(root, atomic.getParent()); + assertTrue(atomic.isEnabled()); + } + + @Test + public void testUnknownAffectedObjectsDoNotHideSiblingFiles() { + assertEquals(2, composite(change(null, (Object[]) null), textChange("/project/A.txt"), + change(file("/project/B.txt"), (Object[]) null)).getFilenumber()); + } + + @Test + public void testResourceAdaptableElements() { + IFile first= file("/project/A.txt"); + IAdaptable element= adaptable(first, IResource.class); + assertEquals(2, composite(change(element, (Object[]) null), + change(null, element, adaptable(file("/project/B.txt"), IResource.class))).getFilenumber()); + } + + @Test + public void testFileAdaptableElements() { + IAdaptable element= adaptable(file("/project/A.txt"), IFile.class); + assertEquals(1, composite(change(null, element), change(element, (Object[]) null)).getFilenumber()); + } + + @Test + public void testNonFileElementsAreNotCountedAsFiles() { + var project= ResourcesPlugin.getWorkspace().getRoot().getProject("project"); + assertEquals(0, composite(new NullChange(), change(null, project, project.getFolder("folder"), + new Document("text"), null), change(null, (Object[]) null)).getFilenumber()); + } + + @Test + public void testExplicitlyEmptyAffectedObjects() { + assertEquals(0, composite(change(file("/project/A.txt"))).getFilenumber()); + } + + @Test + public void testCountDoesNotChangeSelectionOrTree() { + TextFileChange first= textChange("/project/A.txt"); + TextFileChange second= textChange("/project/B.txt"); + CompositeChange nested= composite(second); + nested.setEnabled(false); + CompositeChange root= composite(first, nested); + Change[] originalChildren= root.getChildren(); + assertEquals(2, root.getFilenumber()); + assertEquals(2, root.getFilenumber()); + assertArrayEquals(originalChildren, root.getChildren()); + assertSame(root, first.getParent()); + assertSame(nested, second.getParent()); + assertTrue(first.isEnabled()); + assertFalse(nested.isEnabled()); + assertFalse(second.isEnabled()); + } + + private static CompositeChange composite(Change... children) { + return new CompositeChange("changes", children); + } + + private static IFile file(String path) { + // Handles suffice: counting must not read or change workspace contents. + return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path)); + } + + private static TextFileChange textChange(String path) { + IFile file= file(path); + return new TextFileChange(file.getName(), file); + } + + private static IAdaptable adaptable(IFile file, Class type) { + return new IAdaptable() { + @Override + public T getAdapter(Class adapter) { + return adapter == type ? adapter.cast(file) : null; + } + }; + } + + private static Change change(Object modified, Object... affected) { + return new Change() { + @Override + public String getName() { + return "test change"; + } + + @Override + public Object getModifiedElement() { + return modified; + } + + @Override + public Object[] getAffectedObjects() { + return affected; + } + + @Override + public void initializeValidationData(IProgressMonitor pm) { + throw new AssertionError("Counting must not initialize a change"); + } + + @Override + public RefactoringStatus isValid(IProgressMonitor pm) { + throw new AssertionError("Counting must not validate a change"); + } + + @Override + public Change perform(IProgressMonitor pm) { + throw new AssertionError("Counting must not perform a change"); + } + }; + } +} From 0db9d4ddca3a9cff5eb9c41bb12c8623af8e8dc7 Mon Sep 17 00:00:00 2001 From: Goutam Adwant Date: Sat, 26 Sep 2026 23:24:30 -0700 Subject: [PATCH 18/52] Fix duplicate page registration in FormEditor.addPage(IFormPage) addPage(IFormPage) went through MultiPageEditorPart.addPage(Control), which calls the overridden addPage(int, Control) and so registered the page control (null for a lazily created page) in 'pages' before configurePage registered the form page itself. The page table then held more entries than tabs, kept disposed controls after removePage, and a lazily added control page could be skipped, leaving later form pages with wrong indices. Add the tab through the superclass directly, as addPage(int, IFormPage) already does, so each form page is registered once. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/4107 --- .../eclipse/ui/forms/editor/FormEditor.java | 5 +- .../build.properties | 1 + .../eclipse/ui/tests/forms/AllFormsTests.java | 2 + .../FormEditorPageRegistrationTest.java | 126 ++++++++++++++++++ .../editor/PageRegistrationFormEditor.java | 74 ++++++++++ tests/org.eclipse.ui.tests.forms/plugin.xml | 13 ++ 6 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/FormEditorPageRegistrationTest.java create mode 100644 tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/PageRegistrationFormEditor.java create mode 100644 tests/org.eclipse.ui.tests.forms/plugin.xml diff --git a/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/editor/FormEditor.java b/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/editor/FormEditor.java index d0c5971781b..b4b1555e4c1 100644 --- a/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/editor/FormEditor.java +++ b/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/editor/FormEditor.java @@ -191,7 +191,10 @@ public Object getSelectedPage() { * the form page to add */ public int addPage(IFormPage page) throws PartInitException { - int i = super.addPage(page.getPartControl()); + int i = getPageCount(); + // Call the superclass directly: this.addPage(int, Control) would also + // add the control to 'pages'; configurePage registers the form page. + super.addPage(i, page.getPartControl()); configurePage(i, page); return i; } diff --git a/tests/org.eclipse.ui.tests.forms/build.properties b/tests/org.eclipse.ui.tests.forms/build.properties index e0fa9d81fe3..f02a91a595e 100755 --- a/tests/org.eclipse.ui.tests.forms/build.properties +++ b/tests/org.eclipse.ui.tests.forms/build.properties @@ -14,6 +14,7 @@ bin.includes = .,\ META-INF/,\ about.html,\ + plugin.xml,\ test.xml output.. = bin/ source.. = forms/ diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java index 1fbd271b2d8..6c1a019c5de 100755 --- a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/AllFormsTests.java @@ -16,6 +16,7 @@ package org.eclipse.ui.tests.forms; +import org.eclipse.ui.tests.forms.editor.FormEditorPageRegistrationTest; import org.eclipse.ui.tests.forms.events.AllEventsTests; import org.eclipse.ui.tests.forms.layout.AllLayoutTests; import org.eclipse.ui.tests.forms.util.AllUtilityTests; @@ -29,6 +30,7 @@ */ @Suite @SelectClasses({ + FormEditorPageRegistrationTest.class, // AllEventsTests.class, // AllLayoutTests.class, // AllUtilityTests.class, // diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/FormEditorPageRegistrationTest.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/FormEditorPageRegistrationTest.java new file mode 100644 index 00000000000..cb09c2a2341 --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/FormEditorPageRegistrationTest.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * Copyright (c) 2026 Goutam Adwant and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.ui.tests.forms.editor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.util.Arrays; +import java.util.List; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IPersistableElement; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.forms.editor.IFormPage; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that {@link org.eclipse.ui.forms.editor.FormEditor} keeps exactly one + * entry per tab in its page table. + */ +public class FormEditorPageRegistrationTest { + + private IWorkbenchPage workbenchPage; + private PageRegistrationFormEditor editor; + + @BeforeEach + public void setUp() throws PartInitException { + workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + editor = (PageRegistrationFormEditor) workbenchPage.openEditor(new TestEditorInput(), PageRegistrationFormEditor.ID); + } + + @AfterEach + public void tearDown() { + if (editor != null) { + workbenchPage.closeEditor(editor, false); + } + } + + @Test + public void addPageRegistersEachFormPageOnce() { + List formPages = editor.getFormPages(); + assertEquals(3, editor.getTabCount()); + assertEquals(formPages, editor.getRegisteredPages()); + for (int i = 0; i < formPages.size(); i++) { + assertPageAt(i, formPages.get(i)); + } + } + + @Test + public void removePageKeepsPageTableInSyncWithTabs() { + List formPages = editor.getFormPages(); + editor.removePage(1); + assertEquals(2, editor.getTabCount()); + assertEquals(List.of(formPages.get(0), formPages.get(2)), editor.getRegisteredPages()); + assertPageAt(0, formPages.get(0)); + assertPageAt(1, formPages.get(2)); + } + + @Test + public void insertedControlPageShiftsFormPages() { + List formPages = editor.getFormPages(); + editor.addPage(1, (Control) null); + assertEquals(4, editor.getTabCount()); + assertEquals(Arrays.asList(formPages.get(0), null, formPages.get(1), formPages.get(2)), + editor.getRegisteredPages()); + assertPageAt(0, formPages.get(0)); + assertPageAt(2, formPages.get(1)); + assertPageAt(3, formPages.get(2)); + } + + private void assertPageAt(int index, IFormPage formPage) { + assertEquals(index, formPage.getIndex()); + assertSame(formPage, editor.findPage(formPage.getId())); + assertSame(formPage, editor.setActivePage(formPage.getId())); + assertEquals(index, editor.getActivePage()); + assertSame(formPage, editor.getActivePageInstance()); + assertSame(formPage, editor.getSelectedPage()); + } + + private static final class TestEditorInput implements IEditorInput { + + @Override + public T getAdapter(Class adapter) { + return null; + } + + @Override + public boolean exists() { + return false; + } + + @Override + public ImageDescriptor getImageDescriptor() { + return ImageDescriptor.getMissingImageDescriptor(); + } + + @Override + public String getName() { + return "FormEditorPageRegistrationTest"; + } + + @Override + public IPersistableElement getPersistable() { + return null; + } + + @Override + public String getToolTipText() { + return getName(); + } + } +} diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/PageRegistrationFormEditor.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/PageRegistrationFormEditor.java new file mode 100644 index 00000000000..229dfa055b9 --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/editor/PageRegistrationFormEditor.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2026 Goutam Adwant and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.ui.tests.forms.editor; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.forms.editor.FormEditor; +import org.eclipse.ui.forms.editor.FormPage; +import org.eclipse.ui.forms.editor.IFormPage; + +/** + * Form editor with a lazily created, an eagerly created and another lazily + * created form page, exposing its page table for inspection. + */ +public class PageRegistrationFormEditor extends FormEditor { + + public static final String ID = "org.eclipse.ui.tests.forms.editor.PageRegistrationFormEditor"; + + private final List formPages = new ArrayList<>(); + + @Override + protected void addPages() { + try { + addFormPage(new FormPage(this, "first", "First")); + FormPage eager = new FormPage(this, "second", "Second"); + eager.createPartControl(getContainer()); + addFormPage(eager); + addFormPage(new FormPage(this, "third", "Third")); + } catch (PartInitException e) { + throw new IllegalStateException(e); + } + } + + private void addFormPage(IFormPage page) throws PartInitException { + addPage(page); + formPages.add(page); + } + + List getFormPages() { + return formPages; + } + + List getRegisteredPages() { + return new ArrayList<>(pages); + } + + int getTabCount() { + return getPageCount(); + } + + @Override + public void doSave(IProgressMonitor monitor) { + } + + @Override + public void doSaveAs() { + } + + @Override + public boolean isSaveAsAllowed() { + return false; + } +} diff --git a/tests/org.eclipse.ui.tests.forms/plugin.xml b/tests/org.eclipse.ui.tests.forms/plugin.xml new file mode 100644 index 00000000000..49fb8af2f2d --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/plugin.xml @@ -0,0 +1,13 @@ + + + + + + + + From 58f2edda545298b5f05b920728a1a2e8eccd0a1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lios=20GILLES?= Date: Mon, 5 Oct 2026 17:13:43 +0200 Subject: [PATCH 19/52] Add preference to render detached windows as top level shells A detached window is created as a child shell of the workbench window shell. The window manager keeps a child window with its owner, so clicking in a detached view that was moved over another application (e.g. on a second monitor) also brings the whole workbench window to the front, over that application. WBWRenderer already creates a top level shell for a window tagged with IPresentationEngine.WINDOW_TOP_LEVEL. Add the DETACHED_WINDOWS_TOP_LEVEL preference (node org.eclipse.e4.ui.workbench.renderers.swt, default false) that does the same for all detached windows, and a check box for it in General > Appearance. A top level shell has its own task bar entry, so a detached window made top level by the preference: - can be minimized (SWT.MIN, unless a style override is set), - has the label of the part it shows as title when the window has no label of its own, instead of an empty title. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Feo5dzUJyYJAvWuN78uu2X --- .../workbench/renderers/swt/WBWRenderer.java | 139 ++++++++++++++++- .../ui/internal/WorkbenchMessages.java | 3 + .../internal/dialogs/ViewsPreferencePage.java | 17 +++ .../eclipse/ui/internal/messages.properties | 3 + .../e4/ui/tests/workbench/MWindowTest.java | 143 +++++++++++++++++- 5 files changed, 302 insertions(+), 3 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/WBWRenderer.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/WBWRenderer.java index c47c15ea4ff..0fe77291200 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/WBWRenderer.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/WBWRenderer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2018 IBM Corporation and others. + * Copyright (c) 2008, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -28,6 +28,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.eclipse.core.runtime.Platform; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.core.services.events.IEventBroker; @@ -48,6 +49,7 @@ import org.eclipse.e4.ui.model.application.ui.MUIElement; import org.eclipse.e4.ui.model.application.ui.MUILabel; import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective; +import org.eclipse.e4.ui.model.application.ui.advanced.MPlaceholder; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.e4.ui.model.application.ui.basic.MPartStack; import org.eclipse.e4.ui.model.application.ui.basic.MTrimBar; @@ -98,6 +100,40 @@ public class WBWRenderer extends SWTPartRenderer { private static String ShellMinimizedTag = "shellMinimized"; //$NON-NLS-1$ private static String ShellMaximizedTag = "shellMaximized"; //$NON-NLS-1$ + /** + * A named preference of the + * {@link CTabRendering#PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT} + * node: when true, the detached windows are rendered as top level + * shells instead of children of the shell of their window, as if they had the + * {@link IPresentationEngine#WINDOW_TOP_LEVEL} tag. + *

+ * The window manager keeps a child shell with its parent: activating a + * detached window brings the workbench window to the front too, over the + * other applications. A top level detached window is activated alone. + *

+ *

+ * Such a shell has its own task bar entry: it can be minimized and, when the + * window has no label, its title is the label of the part it shows. + *

+ *

+ * The preference is read when the shell of a detached window is created. + *

+ */ + public static final String DETACHED_WINDOWS_TOP_LEVEL = "DETACHED_WINDOWS_TOP_LEVEL"; //$NON-NLS-1$ + + /** + * Default value of the {@link #DETACHED_WINDOWS_TOP_LEVEL} preference: the + * detached windows are children of the shell of their window. + */ + public static final boolean DETACHED_WINDOWS_TOP_LEVEL_DEFAULT = false; + + /** + * Marks the shell of a detached window made top level by the + * {@link #DETACHED_WINDOWS_TOP_LEVEL} preference: its title follows the part + * it shows. + */ + private static final String DETACHED_TOP_LEVEL_SHELL = "detachedTopLevelShell"; //$NON-NLS-1$ + private class WindowSizeUpdateJob implements Runnable { public List windowsToUpdate = new ArrayList<>(); @@ -202,6 +238,32 @@ private void subscribeTopicLabelChanged(@UIEventTopic(UIEvents.UILabel.TOPIC_ALL } } + /** + * A top level detached window has its own task bar entry: when it has no + * label, its title follows the label of the part it shows. + */ + @Inject + @Optional + private void subscribeTopicPartLabelChanged(@UIEventTopic(UIEvents.UILabel.TOPIC_ALL) Event event) { + if (!(event.getProperty(UIEvents.EventTags.ELEMENT) instanceof MPart part)) { + return; + } + String attName = (String) event.getProperty(UIEvents.EventTags.ATTNAME); + if (UIEvents.UILabel.LABEL.equals(attName) || UIEvents.UILabel.LOCALIZED_LABEL.equals(attName)) { + updateDetachedWindowTitle(getWindowOf(part.getCurSharedRef() != null ? part.getCurSharedRef() : part)); + } + } + + @Inject + @Optional + private void subscribeTopicDetachedWindowSelectionChanged( + @UIEventTopic(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT) Event event) { + if (event.getProperty(UIEvents.EventTags.ELEMENT) instanceof MElementContainer container + && !(container instanceof MApplication)) { + updateDetachedWindowTitle(getWindowOf(container)); + } + } + @Inject @Optional private void subscribeTopicWindowChanged(@UIEventTopic(UIEvents.Window.TOPIC_ALL) Event event) { @@ -376,10 +438,16 @@ public Object createWidget(MUIElement element, Object parent) { wbwModel.getTags().add("topLevel"); //$NON-NLS-1$ } else { int style = SWT.TITLE | SWT.RESIZE | SWT.MAX | SWT.CLOSE | rtlStyle; - style = styleOverride == -1 ? style : styleOverride; if (wbwModel.getTags().contains(IPresentationEngine.WINDOW_TOP_LEVEL)) { + style = styleOverride == -1 ? style : styleOverride; + wbwShell = new Shell(display, style); + } else if (isDetachedWindowTopLevel()) { + // A top level window has its own task bar entry: it can be minimized + style = styleOverride == -1 ? style | SWT.MIN : styleOverride; wbwShell = new Shell(display, style); + wbwShell.setData(DETACHED_TOP_LEVEL_SHELL, Boolean.TRUE); } else { + style = styleOverride == -1 ? style : styleOverride; wbwShell = new Shell(parentShell, style); } @@ -472,6 +540,8 @@ public Save[] promptToSave(Collection dirtyParts) { if (wbwModel.getLabel() != null) { wbwShell.setText(wbwModel.getLocalizedLabel()); + } else { + updateDetachedWindowTitle(wbwModel, wbwShell); } Image windowImage = getImage(wbwModel); @@ -487,6 +557,71 @@ public Save[] promptToSave(Collection dirtyParts) { return newWidget; } + private static boolean isDetachedWindowTopLevel() { + // Use the preferences service so product customization (default scope) is honored + return Platform.getPreferencesService().getBoolean( + CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT, DETACHED_WINDOWS_TOP_LEVEL, + DETACHED_WINDOWS_TOP_LEVEL_DEFAULT, null); + } + + private static MWindow getWindowOf(MUIElement element) { + MUIElement current = element; + while (current != null && !(current instanceof MWindow)) { + current = current.getParent(); + } + return (MWindow) current; + } + + private void updateDetachedWindowTitle(MWindow window) { + if (window != null && window.getRenderer() == this && window.getLabel() == null + && window.getWidget() instanceof Shell shell) { + updateDetachedWindowTitle(window, shell); + } + } + + /** + * Sets the title of a detached window made top level by the + * {@link #DETACHED_WINDOWS_TOP_LEVEL} preference, when it has no label, to the + * label of the part it shows. The detached windows usually have no label: a + * child shell has no task bar entry, but a top level shell has one. + */ + private static void updateDetachedWindowTitle(MWindow window, Shell shell) { + if (shell.isDisposed() || shell.getData(DETACHED_TOP_LEVEL_SHELL) == null) { + return; + } + MPart part = getShownPart(window); + String title = part == null || part.getLocalizedLabel() == null ? "" : part.getLocalizedLabel(); //$NON-NLS-1$ + if (!title.equals(shell.getText())) { + shell.setText(title); + } + } + + /** + * @return the part shown by the container: its selected element or, if none, + * its first visible child + */ + private static MPart getShownPart(MElementContainer container) { + MUIElement shown = container.getSelectedElement(); + if (shown == null) { + for (MUIElement child : container.getChildren()) { + if (child.isToBeRendered() && child.isVisible()) { + shown = child; + break; + } + } + } + if (shown instanceof MPlaceholder placeholder) { + shown = placeholder.getRef(); + } + if (shown instanceof MPart part) { + return part; + } + if (shown instanceof MElementContainer childContainer) { + return getShownPart(childContainer); + } + return null; + } + private void setCloseHandler(MWindow window) { IEclipseContext context = window.getContext(); // no direct model parent, must be a detached window diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java index 469de885aeb..c2dfacf29ab 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java @@ -491,6 +491,9 @@ public class WorkbenchMessages extends NLS { public static String ViewsPreference_hideIconsForViewTabs; public static String ViewsPreference_viewTabs_dirty_indicator_label; public static String ViewsPreference_showDirtyIndicatorForTabs; + public static String ViewsPreference_detachedWindows_label; + public static String ViewsPreference_detachedWindowsTopLevel; + public static String ViewsPreference_detachedWindowsTopLevel_tooltip; public static String ToggleFullScreenMode_ActivationPopup_Description; public static String ToggleFullScreenMode_ActivationPopup_Description_NoKeybinding; public static String ToggleFullScreenMode_ActivationPopup_DoNotShowAgain; diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java index cd61235dfd7..0dfd164cb16 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java @@ -52,6 +52,7 @@ import org.eclipse.e4.ui.model.application.MApplication; import org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering; import org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer; +import org.eclipse.e4.ui.workbench.renderers.swt.WBWRenderer; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; @@ -126,6 +127,8 @@ public class ViewsPreferencePage extends PreferencePage implements IWorkbenchPre private Button showDirtyIndicatorForTabs; + private Button detachedWindowsTopLevel; + @Override protected Control createContents(Composite parent) { initializeDialogUnits(parent); @@ -258,6 +261,7 @@ private void createThemeIndependentComposits(Composite comp) { createColoredLabelsPref(comp); createEnableMruPref(comp); createShowDirtyIndicatorForTabs(comp); + createDetachedWindowsTopLevelPref(comp); } protected void createShowFullTextForViewTabs(Composite composite) { @@ -285,6 +289,16 @@ protected void createShowDirtyIndicatorForTabs(Composite composite) { WorkbenchMessages.ViewsPreference_showDirtyIndicatorForTabs, actualValue); } + protected void createDetachedWindowsTopLevelPref(Composite composite) { + boolean actualValue = getSwtRendererPreference(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL, + WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL_DEFAULT); + createLabel(composite, ""); //$NON-NLS-1$ + createLabel(composite, WorkbenchMessages.ViewsPreference_detachedWindows_label); + detachedWindowsTopLevel = createCheckButton(composite, WorkbenchMessages.ViewsPreference_detachedWindowsTopLevel, + actualValue); + detachedWindowsTopLevel.setToolTipText(WorkbenchMessages.ViewsPreference_detachedWindowsTopLevel_tooltip); + } + private boolean getSwtRendererPreference(String prefName, boolean defaultValue) { return Platform.getPreferencesService().getBoolean(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT, prefName, defaultValue, null); @@ -459,6 +473,7 @@ public boolean performOk() { // Dirty indicator is independent of CSS theming, so always store it prefs.putBoolean(CTabRendering.SHOW_DIRTY_INDICATOR_ON_TABS, showDirtyIndicatorForTabs.getSelection()); + prefs.putBoolean(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL, detachedWindowsTopLevel.getSelection()); IPreferenceStore apiStore = PrefUtil.getAPIPreferenceStore(); apiStore.setValue(IWorkbenchPreferenceConstants.USE_COLORED_LABELS, useColoredLabels.getSelection()); @@ -600,6 +615,8 @@ protected void performDefaults() { } showDirtyIndicatorForTabs.setSelection(defaultPrefs.getBoolean(CTabRendering.SHOW_DIRTY_INDICATOR_ON_TABS, CTabRendering.SHOW_DIRTY_INDICATOR_ON_TABS_DEFAULT)); + detachedWindowsTopLevel.setSelection(defaultPrefs.getBoolean(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL, + WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL_DEFAULT)); IPreferenceStore apiStore = PrefUtil.getAPIPreferenceStore(); useColoredLabels.setSelection(apiStore.getDefaultBoolean(IWorkbenchPreferenceConstants.USE_COLORED_LABELS)); diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties index 8920f9043be..b520407430b 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties @@ -436,6 +436,9 @@ ViewsPreference_hideIconsForViewTabs = Hide icons ViewsPreference_viewTabs_icons_and_titles_label = Tab icons and titles in view areas: ViewsPreference_viewTabs_dirty_indicator_label = Indicator for unsaved changes in view and editor tabs: ViewsPreference_showDirtyIndicatorForTabs = Indicate unsaved changes by overlaying the close button +ViewsPreference_detachedWindows_label = Detached windows: +ViewsPreference_detachedWindowsTopLevel = Activate detached windows independently of the workbench window +ViewsPreference_detachedWindowsTopLevel_tooltip = When enabled, clicking in a detached window does not bring the workbench window to the front.\nApplies to the windows detached afterwards and, after a restart, to all the detached windows. ToggleFullScreenMode_ActivationPopup_Description=You have gone full screen. Use the Toggle Full Screen command ({0}) to deactivate. ToggleFullScreenMode_ActivationPopup_Description_NoKeybinding=You have gone full screen. Use the Toggle Full Screen command to deactivate. ToggleFullScreenMode_ActivationPopup_DoNotShowAgain=Do not show again diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/MWindowTest.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/MWindowTest.java index 47a2a711cb7..d756183fe34 100644 --- a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/MWindowTest.java +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/MWindowTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2024 IBM Corporation and others. + * Copyright (c) 2009, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -26,6 +26,8 @@ import jakarta.inject.Inject; import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.ui.internal.workbench.swt.AbstractPartRenderer; import org.eclipse.e4.ui.model.application.MApplication; @@ -39,6 +41,8 @@ import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.e4.ui.tests.rules.WorkbenchContextExtension; import org.eclipse.e4.ui.workbench.modeling.EModelService; +import org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering; +import org.eclipse.e4.ui.workbench.renderers.swt.WBWRenderer; import org.eclipse.jface.action.MenuManager; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; @@ -415,6 +419,143 @@ public void testDetachedWindow() { assertNull(detachedShell.getImage()); } + @Test + public void testDetachedWindowIsChildShellByDefault() { + final MWindow window = ems.createModelElement(MWindow.class); + window.setLabel("MyWindow"); + final MWindow detachedWindow = ems.createModelElement(MWindow.class); + detachedWindow.setLabel("DetachedWindow"); + window.getWindows().add(detachedWindow); + + application.getChildren().add(window); + contextRule.createAndRunWorkbench(window); + + Shell topShell = (Shell) window.getWidget(); + Shell detachedShell = (Shell) detachedWindow.getWidget(); + assertEquals(topShell, detachedShell.getParent(), "Detached shell should be a child of the window shell"); + } + + @Test + public void testDetachedWindowTopLevelPreference() { + IEclipsePreferences prefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + prefs.putBoolean(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL, true); + try { + final MWindow window = ems.createModelElement(MWindow.class); + window.setLabel("MyWindow"); + final MWindow detachedWindow = ems.createModelElement(MWindow.class); + detachedWindow.setLabel("DetachedWindow"); + window.getWindows().add(detachedWindow); + + application.getChildren().add(window); + contextRule.createAndRunWorkbench(window); + + Shell detachedShell = (Shell) detachedWindow.getWidget(); + assertNotNull(detachedShell); + assertNull(detachedShell.getParent(), "Detached shell should be a top level shell"); + assertEquals(window, ems.getContainer(detachedWindow)); + } finally { + prefs.remove(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL); + } + } + + @Test + public void testDetachedPartTopLevelPreference() { + IEclipsePreferences prefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + prefs.putBoolean(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL, true); + try { + final MWindow window = createWindowWithOneView(); + application.getChildren().add(window); + contextRule.createAndRunWorkbench(window); + + // Detach the part of a rendered window, as the Detach menu does + MPart part = getContributedPart(window); + ems.detach(part, 100, 100, 300, 200); + + assertEquals(1, window.getWindows().size()); + MWindow detachedWindow = window.getWindows().get(0); + Shell detachedShell = (Shell) detachedWindow.getWidget(); + assertNotNull(detachedShell); + assertNull(detachedShell.getParent(), "Detached shell should be a top level shell"); + assertTrue((detachedShell.getStyle() & SWT.MIN) != 0, "Top level detached shell should be minimizable"); + assertEquals("Sample View", detachedShell.getText(), "Title should be the label of the detached part"); + + part.setLabel("Renamed View"); + while (detachedShell.getDisplay().readAndDispatch()) { + } + assertEquals("Renamed View", detachedShell.getText(), "Title should follow the label of the part"); + } finally { + prefs.remove(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL); + } + } + + @Test + public void testDetachedWindowTitleFollowsSelectedPart() { + IEclipsePreferences prefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + prefs.putBoolean(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL, true); + try { + final MWindow window = createWindowWithOneView(); + final MWindow detachedWindow = ems.createModelElement(MWindow.class); + MPartStack stack = ems.createModelElement(MPartStack.class); + detachedWindow.getChildren().add(stack); + MPart partA = createSampleView("Part A"); + MPart partB = createSampleView("Part B"); + stack.getChildren().add(partA); + stack.getChildren().add(partB); + stack.setSelectedElement(partA); + window.getWindows().add(detachedWindow); + + application.getChildren().add(window); + contextRule.createAndRunWorkbench(window); + + Shell detachedShell = (Shell) detachedWindow.getWidget(); + assertNull(detachedShell.getParent(), "Detached shell should be a top level shell"); + assertEquals("Part A", detachedShell.getText()); + + stack.setSelectedElement(partB); + while (detachedShell.getDisplay().readAndDispatch()) { + } + assertEquals("Part B", detachedShell.getText()); + + // A label of the window itself wins over the label of its parts + detachedWindow.setLabel("Window Label"); + while (detachedShell.getDisplay().readAndDispatch()) { + } + partB.setLabel("Renamed Part B"); + while (detachedShell.getDisplay().readAndDispatch()) { + } + assertEquals("Window Label", detachedShell.getText()); + + // The main window keeps its own title + assertEquals("MyWindow", ((Shell) window.getWidget()).getText()); + } finally { + prefs.remove(WBWRenderer.DETACHED_WINDOWS_TOP_LEVEL); + } + } + + @Test + public void testDetachedWindowTitleUnchangedByDefault() { + final MWindow window = createWindowWithOneView(); + application.getChildren().add(window); + contextRule.createAndRunWorkbench(window); + + MPart part = getContributedPart(window); + ems.detach(part, 100, 100, 300, 200); + + Shell detachedShell = (Shell) window.getWindows().get(0).getWidget(); + assertEquals(window.getWidget(), detachedShell.getParent()); + assertEquals("", detachedShell.getText(), "A child detached shell keeps its empty title"); + } + + private MPart createSampleView(String label) { + MPart part = ems.createModelElement(MPart.class); + part.setLabel(label); + part.setContributionURI("bundleclass://org.eclipse.e4.ui.tests/org.eclipse.e4.ui.tests.workbench.SampleView"); + return part; + } + private MPart getContributedPart(MWindow window) { MPartSashContainer psc = (MPartSashContainer) window.getChildren().get(0); MPartStack stack = (MPartStack) psc.getChildren().get(0); From d18b5d7048b7d24d03fd74b3f2bcb6afd25407cb Mon Sep 17 00:00:00 2001 From: Christian Schima Date: Thu, 8 Oct 2026 21:51:33 +0200 Subject: [PATCH 20/52] Update project explorer tree view when projects are added/removed. --- .../WorkingSetsContentProvider.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetsContentProvider.java b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetsContentProvider.java index d904211911e..199fa546619 100644 --- a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetsContentProvider.java +++ b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetsContentProvider.java @@ -22,6 +22,9 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Adapters; import org.eclipse.core.runtime.IAdaptable; @@ -86,6 +89,24 @@ public class WorkingSetsContentProvider implements ICommonContentProvider { } }; + private final IResourceChangeListener resourceChangeListener = event -> { + IResourceDelta delta = event.getDelta(); + if (delta == null || !hasProjectChanges(delta)) { + return; + } + + PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { + if (helper != null && viewer != null && !viewer.getControl().isDisposed()) { + helper.refreshWorkingSetTreeState(); + viewer.refresh(); + } + }); + }; + + private boolean hasProjectChanges(IResourceDelta delta) { + return delta.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.REMOVED, IResource.PROJECT).length > 0; + } + @Override public void init(ICommonContentExtensionSite aConfig) { NavigatorContentService cs = (NavigatorContentService) aConfig.getService(); @@ -99,6 +120,8 @@ public void init(ICommonContentExtensionSite aConfig) { workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager(); workingSetManager.addPropertyChangeListener(workingSetManagerListener); + ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener, + IResourceChangeEvent.POST_CHANGE); } @Override @@ -175,6 +198,7 @@ public void dispose() { helper = null; extensionStateModel.removePropertyChangeListener(rootModeListener); workingSetManager.removePropertyChangeListener(workingSetManagerListener); + ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener); } @Override From d4345b937457eb4a2c1b473aefc879f1f2dbcbb3 Mon Sep 17 00:00:00 2001 From: Edward Lo Date: Fri, 11 Sep 2026 04:15:46 +0000 Subject: [PATCH 21/52] Fix regex Replace All rematching line-start anchors Collect all matches first, then replace from last to first so patterns like "^ " with an empty replacement remove only one leading space per line instead of all leading spaces. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/2820 Signed-off-by: Edward Lo --- .../findandreplace/FindReplaceLogic.java | 43 ++++++++++++++++--- .../findandreplace/FindReplaceLogicTest.java | 34 ++++++++++++++- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java index 14f846ba9c1..dacee5bf8f7 100644 --- a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2023 Vector Informatik GmbH and others. + * Copyright (c) 2023, 2026 Vector Informatik GmbH and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -10,6 +10,7 @@ * * Contributors: * Vector Informatik GmbH - initial API and implementation + * Edward Lo - fix replaceAll rematching line-start regex (issue 2820) *******************************************************************************/ package org.eclipse.ui.internal.findandreplace; @@ -422,6 +423,12 @@ private void restoreSelectionIfEmpty() { /** * Replaces all occurrences of the user's findString with the replace string. * Returns the number of replacements that occur. + *

+ * Matches are collected first and then replaced from last to first. This + * avoids re-matching the same logical position after a replacement (for + * example regex {@code ^ } with an empty replacement would otherwise keep + * matching at the line start and remove all leading spaces). + *

* * @return the number of occurrences * @@ -434,16 +441,42 @@ private int replaceAll() { List replacements = new ArrayList<>(); executeInForwardMode(() -> { executeWithReplaceAllEnabled(() -> { - Point currentSelection = new Point(0, 0); - while (findAndSelect(currentSelection.x + currentSelection.y) != -1) { - currentSelection = replaceSelection(); - replacements.add(currentSelection); + List matches = findAllMatches(); + // Replace from last to first so earlier match offsets stay valid + for (int i = matches.size() - 1; i >= 0; i--) { + Point match = matches.get(i); + // Re-select to restore find/replace state (including regex groups) + if (findAndSelect(match.x) != match.x) { + continue; + } + replacements.add(replaceSelection()); } }); }); return replacements.size(); } + /** + * Finds all matches going forward, advancing the search past each match. For + * zero-length matches the search continues one character after the match to + * avoid an infinite loop. + * + * @return the match regions in document order (offset, length) + */ + private List findAllMatches() { + List matches = new ArrayList<>(); + int searchOffset = 0; + while (findAndSelect(searchOffset) != -1) { + Point match = target.getSelection(); + matches.add(new Point(match.x, match.y)); + searchOffset = match.x + match.y; + if (match.y == 0) { + searchOffset++; + } + } + return matches; + } + private void executeInForwardMode(Runnable runnable) { if (isActive(SearchOptions.FORWARD)) { runnable.run(); diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java index 5f4f75326ea..8029bbf4e7b 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2023 Vector Informatik GmbH and others. + * Copyright (c) 2023, 2026 Vector Informatik GmbH and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -10,6 +10,7 @@ * * Contributors: * Vector Informatik GmbH - initial API and implementation + * Edward Lo - test replaceAll line-start regex (issue 2820) *******************************************************************************/ package org.eclipse.ui.internal.findandreplace; @@ -189,6 +190,37 @@ public void testPerformReplaceAllForwardRegEx() { + "^"); } + /** + * Replace All with a line-start regex must not rematch the same line after an + * empty replacement (see https://github.com/eclipse-platform/eclipse.platform.ui/issues/2820). + */ + @Test + public void testPerformReplaceAllRegExLineStartAnchor() { + TextViewer textViewer= setupTextViewer(" hello" + lineSeparator() + " world" + lineSeparator() + " three"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "^ ", ""); + findReplaceLogic.performReplaceAll(); + // One leading space removed per line, not all leading spaces + assertThat(textViewer.getDocument().get(), equalTo(" hello" + lineSeparator() + " world" + lineSeparator() + " three")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); + } + + @Test + public void testPerformReplaceAllRegExZeroLengthLineStart() { + TextViewer textViewer= setupTextViewer("a" + lineSeparator() + "b"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "^", ">"); + findReplaceLogic.performReplaceAll(); + assertThat(textViewer.getDocument().get(), equalTo(">a" + lineSeparator() + ">b")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); + } + @Test public void testPerformReplaceAllForward() { TextViewer textViewer= setupTextViewer("hello@eclipse.com looks.almost@like_an_email"); From 66171aa061ceaf581fbb10a67165f3afc983a28c Mon Sep 17 00:00:00 2001 From: Edward Lo Date: Sat, 12 Sep 2026 13:58:29 +0000 Subject: [PATCH 22/52] test: drop zero-length ^ Replace All case (unsupported by adapter) FindReplaceDocumentAdapter returns no match when group().isEmpty(), so bare "^" never finds. Keep the ^[space] regression for issue 2820. --- .../findandreplace/FindReplaceLogicTest.java | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java index 8029bbf4e7b..7398175b815 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java @@ -208,18 +208,8 @@ public void testPerformReplaceAllRegExLineStartAnchor() { expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); } - @Test - public void testPerformReplaceAllRegExZeroLengthLineStart() { - TextViewer textViewer= setupTextViewer("a" + lineSeparator() + "b"); - IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); - findReplaceLogic.activate(SearchOptions.REGEX); - findReplaceLogic.activate(SearchOptions.FORWARD); - - setFindAndReplaceString(findReplaceLogic, "^", ">"); - findReplaceLogic.performReplaceAll(); - assertThat(textViewer.getDocument().get(), equalTo(">a" + lineSeparator() + ">b")); - expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); - } + // Note: bare "^" (zero-length) is not exercised here — FindReplaceDocumentAdapter + // deliberately ignores empty regex matches (group().isEmpty()), so such a find never hits. @Test public void testPerformReplaceAllForward() { From 22dff87dbc15255f2911e4016edba0f19da29287 Mon Sep 17 00:00:00 2001 From: Ares16x16 Date: Thu, 17 Sep 2026 20:58:27 +0800 Subject: [PATCH 23/52] fix: drop unreachable guard around match re-selection FindReplaceDocumentAdapter#replace() does not take an offset: it uses the matcher's current match and expands $n from it. Collecting all matches before replacing leaves that matcher exhausted, so each match has to be re-established before it is replaced - without the re-selection every replacement fails. The additional comparison of the re-selected offset against the stored one was defensive only. It never triggered: matches are replaced last to first, so the text of every pending match is unchanged and a forward search from its offset necessarily returns the same offset. Being unreachable, it also cannot be covered by a test. Drop it and document why the re-selection itself is required instead. Also let selectAll() reuse findAllMatches() rather than duplicating the same match walk, as raised in review. Add regression tests for re-matching during replace all: the anchor cases fail on the previous implementation, while the group-expansion case pins the re-selection requirement (it fails if the re-selection is removed). --- .../findandreplace/FindReplaceLogic.java | 11 +- .../findandreplace/FindReplaceLogicTest.java | 125 ++++++++++++++++++ 2 files changed, 127 insertions(+), 9 deletions(-) diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java index dacee5bf8f7..ce62d0b3339 100644 --- a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java @@ -445,10 +445,7 @@ private int replaceAll() { // Replace from last to first so earlier match offsets stay valid for (int i = matches.size() - 1; i >= 0; i--) { Point match = matches.get(i); - // Re-select to restore find/replace state (including regex groups) - if (findAndSelect(match.x) != match.x) { - continue; - } + findAndSelect(match.x); replacements.add(replaceSelection()); } }); @@ -509,11 +506,7 @@ private void executeWithReplaceAllEnabled(Runnable runnable) { private int selectAll() { List selections = new ArrayList<>(); executeInForwardMode(() -> { - Point currentSeletion = new Point(0, 0); - while (findAndSelect(currentSeletion.x + currentSeletion.y) != -1) { - currentSeletion = target.getSelection(); - selections.add(currentSeletion); - } + selections.addAll(findAllMatches()); if (target instanceof IFindReplaceTargetExtension4 selectableTarget) { IRegion[] selectedRegions = selections.stream().map(selection -> new Region(selection.x, selection.y)) .toArray(IRegion[]::new); diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java index 7398175b815..3ffd0b05e2a 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java @@ -210,6 +210,131 @@ public void testPerformReplaceAllRegExLineStartAnchor() { // Note: bare "^" (zero-length) is not exercised here — FindReplaceDocumentAdapter // deliberately ignores empty regex matches (group().isEmpty()), so such a find never hits. + /** + * A single-character line-start pattern must not be rematched at the same line start + * after the replacement removed the character it matched. This is the shapes of + * https://github.com/eclipse-platform/eclipse.platform.ui/issues/2820 where every + * character on a line matches at the line start. + */ + @Test + public void testPerformReplaceAllRegExWordBoundaryAnchorIsNotRematched() { + TextViewer textViewer= setupTextViewer("aa"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "\\ba", ""); + findReplaceLogic.performReplaceAll(); + // "aa" has a word boundary before the first "a" only, so one match, not two + assertThat(textViewer.getDocument().get(), equalTo("a")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); + } + + /** + * A line-start anchor on a line other than the first must also be matched exactly once, + * i.e. the search must not restart at the offset it already processed. + */ + @Test + public void testPerformReplaceAllRegExLineStartAnchorOnLaterLineIsNotRematched() { + TextViewer textViewer= setupTextViewer(lineSeparator() + "aa"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "^a", ""); + findReplaceLogic.performReplaceAll(); + // only the "a" starting the second line is at a line start + assertThat(textViewer.getDocument().get(), equalTo(lineSeparator() + "a")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); + } + + /** + * A line consisting only of whitespace must not be emptied completely: the pattern matches + * once per line, so exactly one match is consumed per line. + */ + @Test + public void testPerformReplaceAllRegExLineStartAnchorOnWhitespaceOnlyLine() { + TextViewer textViewer= setupTextViewer(" "); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "^ ", ""); + findReplaceLogic.performReplaceAll(); + // one leading space removed, not all three + assertThat(textViewer.getDocument().get(), equalTo(" ")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); + } + + /** + * A non-greedy line-start pattern matches at most once per line, even when the line keeps + * matching after the replacement. + */ + @Test + public void testPerformReplaceAllRegExLineStartWhitespaceIsReplacedOncePerLine() { + TextViewer textViewer= setupTextViewer(" a" + lineSeparator() + " b" + lineSeparator() + "c"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "^\\s*", ""); + findReplaceLogic.performReplaceAll(); + // the two indented lines are stripped once each; the third line has no leading whitespace + assertThat(textViewer.getDocument().get(), equalTo("a" + lineSeparator() + "b" + lineSeparator() + "c")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); + } + + /** + * Replacing a line-start pattern with a non-empty string must still produce one replacement + * per line and no extra ones. + */ + @Test + public void testPerformReplaceAllRegExLineStartAnchorWithReplacement() { + TextViewer textViewer= setupTextViewer(" a" + lineSeparator() + " b"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "^ ", ">"); + findReplaceLogic.performReplaceAll(); + assertThat(textViewer.getDocument().get(), equalTo("> a" + lineSeparator() + "> b")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); + } + + /** + * Group references in the replacement must be expanded for every match. Collecting all + * matches before replacing leaves the find/replace matcher exhausted, so each match has to + * be re-established before it is replaced - without that, replacement fails entirely. + */ + @Test + public void testPerformReplaceAllRegExGroupsAreExpandedForEachMatch() { + TextViewer textViewer= setupTextViewer("hello@eclipse.com"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "(\\w+)@(\\w+)", "$2@$1"); + findReplaceLogic.performReplaceAll(); + assertThat(textViewer.getDocument().get(), equalTo("eclipse@hello.com")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); + } + + /** + * Trailing whitespace is a regression guard rather than a fix: a greedy pattern matches a + * whole whitespace run at once, so this already behaved this way before the change. + */ + @Test + public void testPerformReplaceAllRegExTrailingWhitespaceIsRemovedOncePerLine() { + TextViewer textViewer= setupTextViewer("a " + lineSeparator() + "b "); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.REGEX); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, " +$", ""); + findReplaceLogic.performReplaceAll(); + assertThat(textViewer.getDocument().get(), equalTo("a" + lineSeparator() + "b")); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); + } @Test public void testPerformReplaceAllForward() { From 11ab7648675949527cfbc99071fa7da16ec98243 Mon Sep 17 00:00:00 2001 From: Edward Lo Date: Thu, 17 Sep 2026 21:30:39 +0800 Subject: [PATCH 24/52] Document why the match is re-selected before each replacement replaceSelection() does not take an offset: it reads the adapter's current match and expands $n from it. Document this on the findAndSelect(match.x) call so the necessity of the re-selection is clear, following up on the review discussion where the surrounding guard was removed. Signed-off-by: Edward Lo --- .../eclipse/ui/internal/findandreplace/FindReplaceLogic.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java index ce62d0b3339..8b7c8a7a2cb 100644 --- a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java @@ -445,6 +445,8 @@ private int replaceAll() { // Replace from last to first so earlier match offsets stay valid for (int i = matches.size() - 1; i >= 0; i--) { Point match = matches.get(i); + // replaceSelection() reads the adapter's current match and expands $n from it, + // so the match has to be re-established before each replacement. findAndSelect(match.x); replacements.add(replaceSelection()); } From 9fac351add6334d273f62382941d8a817ada77bf Mon Sep 17 00:00:00 2001 From: Heiko Klare Date: Mon, 5 Oct 2026 17:56:01 +0200 Subject: [PATCH 25/52] Replace hamcrest usage with JUnit 5 assertions --- .../findandreplace/FindReplaceLogicTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java index 3ffd0b05e2a..5fa226e726f 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java @@ -204,7 +204,7 @@ public void testPerformReplaceAllRegExLineStartAnchor() { setFindAndReplaceString(findReplaceLogic, "^ ", ""); findReplaceLogic.performReplaceAll(); // One leading space removed per line, not all leading spaces - assertThat(textViewer.getDocument().get(), equalTo(" hello" + lineSeparator() + " world" + lineSeparator() + " three")); + assertEquals(" hello" + lineSeparator() + " world" + lineSeparator() + " three", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); } @@ -226,7 +226,7 @@ public void testPerformReplaceAllRegExWordBoundaryAnchorIsNotRematched() { setFindAndReplaceString(findReplaceLogic, "\\ba", ""); findReplaceLogic.performReplaceAll(); // "aa" has a word boundary before the first "a" only, so one match, not two - assertThat(textViewer.getDocument().get(), equalTo("a")); + assertEquals("a", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); } @@ -244,7 +244,7 @@ public void testPerformReplaceAllRegExLineStartAnchorOnLaterLineIsNotRematched() setFindAndReplaceString(findReplaceLogic, "^a", ""); findReplaceLogic.performReplaceAll(); // only the "a" starting the second line is at a line start - assertThat(textViewer.getDocument().get(), equalTo(lineSeparator() + "a")); + assertEquals(lineSeparator() + "a", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); } @@ -262,7 +262,7 @@ public void testPerformReplaceAllRegExLineStartAnchorOnWhitespaceOnlyLine() { setFindAndReplaceString(findReplaceLogic, "^ ", ""); findReplaceLogic.performReplaceAll(); // one leading space removed, not all three - assertThat(textViewer.getDocument().get(), equalTo(" ")); + assertEquals(" ", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); } @@ -280,7 +280,7 @@ public void testPerformReplaceAllRegExLineStartWhitespaceIsReplacedOncePerLine() setFindAndReplaceString(findReplaceLogic, "^\\s*", ""); findReplaceLogic.performReplaceAll(); // the two indented lines are stripped once each; the third line has no leading whitespace - assertThat(textViewer.getDocument().get(), equalTo("a" + lineSeparator() + "b" + lineSeparator() + "c")); + assertEquals("a" + lineSeparator() + "b" + lineSeparator() + "c", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); } @@ -297,7 +297,7 @@ public void testPerformReplaceAllRegExLineStartAnchorWithReplacement() { setFindAndReplaceString(findReplaceLogic, "^ ", ">"); findReplaceLogic.performReplaceAll(); - assertThat(textViewer.getDocument().get(), equalTo("> a" + lineSeparator() + "> b")); + assertEquals("> a" + lineSeparator() + "> b", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); } @@ -315,7 +315,7 @@ public void testPerformReplaceAllRegExGroupsAreExpandedForEachMatch() { setFindAndReplaceString(findReplaceLogic, "(\\w+)@(\\w+)", "$2@$1"); findReplaceLogic.performReplaceAll(); - assertThat(textViewer.getDocument().get(), equalTo("eclipse@hello.com")); + assertEquals("eclipse@hello.com", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 1); } @@ -332,7 +332,7 @@ public void testPerformReplaceAllRegExTrailingWhitespaceIsRemovedOncePerLine() { setFindAndReplaceString(findReplaceLogic, " +$", ""); findReplaceLogic.performReplaceAll(); - assertThat(textViewer.getDocument().get(), equalTo("a" + lineSeparator() + "b")); + assertEquals("a" + lineSeparator() + "b", textViewer.getDocument().get()); expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); } From 661d76b7de0a131c382aa4c811ac809c9c42b7a6 Mon Sep 17 00:00:00 2001 From: Luise Ravnskjaer <13628062+ravnskjaer@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:23:15 +0200 Subject: [PATCH 26/52] Migrate OpenCloseWindowTest and OpenClosePerspectiveTest to JUnit5 #3639 - Remove dependency on PerformanceTestCaseJunit4. - Migrate OpenCloseWindowTest to use PerformanceMeter directly. - Migrate OpenClosePerspectiveTest to use PerformanceTestCaseJunit5. - Use CloseTestWindowsExtension instead of CloseTestWindowsRule. - Use @ParameterizedTest instead of @RunWith(Parameterized.class) Part of the work for #3639 --- .../performance/OpenClosePerspectiveTest.java | 48 +++++------ .../performance/OpenCloseWindowTest.java | 81 +++++++++---------- 2 files changed, 59 insertions(+), 70 deletions(-) diff --git a/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenClosePerspectiveTest.java b/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenClosePerspectiveTest.java index acb4e1d1429..e5ad3d7583b 100644 --- a/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenClosePerspectiveTest.java +++ b/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenClosePerspectiveTest.java @@ -20,9 +20,8 @@ import static org.eclipse.ui.tests.harness.util.UITestUtil.processEvents; import static org.eclipse.ui.tests.performance.UIPerformanceTestUtil.exercise; -import java.util.Arrays; -import java.util.Collection; import java.util.HashMap; +import java.util.stream.Stream; import org.eclipse.core.commands.Command; import org.eclipse.core.commands.ExecutionException; @@ -31,7 +30,7 @@ import org.eclipse.core.commands.ParameterizedCommand; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.test.performance.Dimension; -import org.eclipse.test.performance.PerformanceTestCaseJunit4; +import org.eclipse.test.performance.PerformanceTestCaseJunit5; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.IViewReference; @@ -41,39 +40,30 @@ import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.internal.WorkbenchPlugin; -import org.eclipse.ui.tests.harness.util.CloseTestWindowsRule; +import org.eclipse.ui.tests.harness.util.CloseTestWindowsExtension; import org.eclipse.ui.tests.harness.util.EmptyPerspective; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class OpenClosePerspectiveTest extends PerformanceTestCaseJunit4 { +class OpenClosePerspectiveTest extends PerformanceTestCaseJunit5 { - @ClassRule - public static final UIPerformanceTestRule uiPerformanceTestRule = new UIPerformanceTestRule(); + @RegisterExtension + static UIPerformanceTestRule uiPerformanceTestRule = new UIPerformanceTestRule(); - @Rule - public final CloseTestWindowsRule closeTestWindows = new CloseTestWindowsRule(); + @RegisterExtension + CloseTestWindowsExtension closeTestWindows = new CloseTestWindowsExtension(); - private final String id; - - @Parameters(name = "{index}: {0}") - public static Collection data() { - return Arrays.asList(new Object[][] { { EmptyPerspective.PERSP_ID2 }, { UIPerformanceTestRule.PERSPECTIVE1 }, - { "org.eclipse.ui.resourcePerspective" }, { "org.eclipse.jdt.ui.JavaPerspective" }, - { "org.eclipse.debug.ui.DebugPerspective" } }); - } - - public OpenClosePerspectiveTest(String id) { - this.id = id; + static Stream data() { + return Stream.of(Arguments.of(EmptyPerspective.PERSP_ID2), Arguments.of(UIPerformanceTestRule.PERSPECTIVE1), + Arguments.of("org.eclipse.ui.resourcePerspective"), Arguments.of("org.eclipse.jdt.ui.JavaPerspective"), + Arguments.of("org.eclipse.debug.ui.DebugPerspective")); } - @Test - public void test() throws Throwable { + @ParameterizedTest(name = "{index}: {0}") + @MethodSource("data") + void test(String id) throws Throwable { // Get the two perspectives to switch between. final IPerspectiveRegistry registry = WorkbenchPlugin.getDefault() .getPerspectiveRegistry(); diff --git a/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenCloseWindowTest.java b/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenCloseWindowTest.java index 8e7d4f70fb3..cf251da314d 100644 --- a/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenCloseWindowTest.java +++ b/tests/org.eclipse.ui.tests.performance/src/org/eclipse/ui/tests/performance/OpenCloseWindowTest.java @@ -18,57 +18,56 @@ import static org.eclipse.ui.tests.harness.util.UITestUtil.processEvents; import static org.eclipse.ui.tests.performance.UIPerformanceTestUtil.exercise; -import java.util.Arrays; -import java.util.Collection; +import java.util.stream.Stream; -import org.eclipse.test.performance.PerformanceTestCaseJunit4; +import org.eclipse.test.performance.Performance; +import org.eclipse.test.performance.PerformanceMeter; import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.tests.harness.util.CloseTestWindowsRule; +import org.eclipse.ui.tests.harness.util.CloseTestWindowsExtension; import org.eclipse.ui.tests.harness.util.EmptyPerspective; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class OpenCloseWindowTest extends PerformanceTestCaseJunit4 { +class OpenCloseWindowTest { - @ClassRule - public static final UIPerformanceTestRule uiPerformanceTestRule = new UIPerformanceTestRule(); + @RegisterExtension + static UIPerformanceTestRule uiPerformanceTestRule = new UIPerformanceTestRule(); - @Rule - public final CloseTestWindowsRule closeTestWindows = new CloseTestWindowsRule(); + @RegisterExtension + CloseTestWindowsExtension closeTestWindows = new CloseTestWindowsExtension(); - private final String id; - - @Parameters(name = "{index}: {0}") - public static Collection data() { - return Arrays.asList(new Object[][] { { EmptyPerspective.PERSP_ID2 }, { UIPerformanceTestRule.PERSPECTIVE1 }, - { "org.eclipse.ui.resourcePerspective" }, { "org.eclipse.jdt.ui.JavaPerspective" }, - { "org.eclipse.debug.ui.DebugPerspective" } }); - } - - public OpenCloseWindowTest(String id) { - this.id = id; + static Stream data() { + return Stream.of(Arguments.of(EmptyPerspective.PERSP_ID2), Arguments.of(UIPerformanceTestRule.PERSPECTIVE1), + Arguments.of("org.eclipse.ui.resourcePerspective"), Arguments.of("org.eclipse.jdt.ui.JavaPerspective"), + Arguments.of("org.eclipse.debug.ui.DebugPerspective")); } - @Test - public void test() throws Throwable { - exercise(() -> { - processEvents(); - EditorTestHelper.calmDown(500, 30000, 500); + @ParameterizedTest(name = "{index}: {0}") + @MethodSource("data") + void test(String id, TestInfo testInfo) throws Throwable { + Performance perf = Performance.getDefault(); + String scenarioId = this.getClass().getName() + "." + testInfo.getDisplayName(); + PerformanceMeter meter = perf.createPerformanceMeter(scenarioId); + try { + exercise(() -> { + processEvents(); + EditorTestHelper.calmDown(500, 30000, 500); - startMeasuring(); - IWorkbenchWindow window = openTestWindow(id); - processEvents(); - window.close(); - processEvents(); - stopMeasuring(); - }); + meter.start(); + IWorkbenchWindow window = openTestWindow(id); + processEvents(); + window.close(); + processEvents(); + meter.toString(); + }); - commitMeasurements(); - assertPerformance(); + meter.commit(); + perf.assertPerformance(meter); + } finally { + meter.dispose(); + } } } From 6d40989f67947d4674f5d9ec3480b8acaa649d42 Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Sun, 18 Oct 2026 17:31:53 +0200 Subject: [PATCH 27/52] Restore lines visibility of trees and tables on theme reset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit swt-lines-visible was never undone, so a Tree or Table kept its grid lines after the theme was switched or re-applied without that rule. The handler now remembers the value the widget had before CSS first styled it, and the Tree and Table element resets restore it, which keeps lines that the application turned on itself. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../e4/ui/css/swt/dom/TableElement.java | 2 ++ .../e4/ui/css/swt/dom/TreeElement.java | 2 ++ .../CSSPropertyLinesVisibleSWTHandler.java | 32 ++++++++++++++++--- .../e4/ui/tests/css/swt/TableTest.java | 29 ++++++++++++++++- .../eclipse/e4/ui/tests/css/swt/TreeTest.java | 14 +++++++- 5 files changed, 73 insertions(+), 6 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableElement.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableElement.java index a66130aa654..8616c0918ca 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableElement.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableElement.java @@ -15,6 +15,7 @@ import java.util.function.Supplier; import org.eclipse.e4.ui.css.core.engine.CSSEngine; +import org.eclipse.e4.ui.css.swt.properties.custom.CSSPropertyLinesVisibleSWTHandler; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; @@ -30,6 +31,7 @@ public TableElement(Control control, CSSEngine engine) { public void reset() { setHeaderColor(null); setHeaderBackgroundColor(null); + CSSPropertyLinesVisibleSWTHandler.restoreDefaultLinesVisible(getControl()); super.reset(); } diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TreeElement.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TreeElement.java index c58e284db6a..506b5dc9878 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TreeElement.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TreeElement.java @@ -15,6 +15,7 @@ import java.util.function.Supplier; import org.eclipse.e4.ui.css.core.engine.CSSEngine; +import org.eclipse.e4.ui.css.swt.properties.custom.CSSPropertyLinesVisibleSWTHandler; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Tree; @@ -32,6 +33,7 @@ public Tree getTree() { public void reset() { setHeaderColor(null); setHeaderBackgroundColor(null); + CSSPropertyLinesVisibleSWTHandler.restoreDefaultLinesVisible(getControl()); super.reset(); } diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/properties/custom/CSSPropertyLinesVisibleSWTHandler.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/properties/custom/CSSPropertyLinesVisibleSWTHandler.java index 35d34a19769..fcae853668c 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/properties/custom/CSSPropertyLinesVisibleSWTHandler.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/properties/custom/CSSPropertyLinesVisibleSWTHandler.java @@ -23,19 +23,43 @@ public class CSSPropertyLinesVisibleSWTHandler extends AbstractCSSPropertySWTHandler { + private static final String DEFAULT_LINES_VISIBLE = "org.eclipse.e4.ui.css.swt.defaultLinesVisible"; //$NON-NLS-1$ + + /** + * Restores the lines visibility the control had before CSS styled it. + */ + public static void restoreDefaultLinesVisible(Control control) { + if (control.getData(DEFAULT_LINES_VISIBLE) instanceof Boolean linesVisible) { + control.setData(DEFAULT_LINES_VISIBLE, null); + if (control instanceof Table table) { + table.setLinesVisible(linesVisible); + } else if (control instanceof Tree tree) { + tree.setLinesVisible(linesVisible); + } + } + } + @Override protected void applyCSSProperty(Control control, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { if (value instanceof CssPrimitive) { boolean linesVisible = (Boolean) engine.convert(value, Boolean.class, control.getDisplay()); - if (control instanceof Table) { - ((Table) control).setLinesVisible(linesVisible); - } else if (control instanceof Tree) { - ((Tree) control).setLinesVisible(linesVisible); + if (control instanceof Table table) { + storeDefaultLinesVisible(table, table.getLinesVisible()); + table.setLinesVisible(linesVisible); + } else if (control instanceof Tree tree) { + storeDefaultLinesVisible(tree, tree.getLinesVisible()); + tree.setLinesVisible(linesVisible); } } } + private static void storeDefaultLinesVisible(Control control, boolean linesVisible) { + if (control.getData(DEFAULT_LINES_VISIBLE) == null) { + control.setData(DEFAULT_LINES_VISIBLE, Boolean.valueOf(linesVisible)); + } + } + @Override protected String retrieveCSSProperty(Control control, String property, String pseudo, CSSEngine engine) throws Exception { diff --git a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TableTest.java b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TableTest.java index 9c4e3b5d171..d68f3e6b6b6 100644 --- a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TableTest.java +++ b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TableTest.java @@ -14,6 +14,10 @@ package org.eclipse.e4.ui.tests.css.swt; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.StringReader; import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.swt.SWT; @@ -72,4 +76,27 @@ void testTableHeaderColor() { assertEquals(BLUE, tableToTest.getHeaderForeground().getRGB()); } -} \ No newline at end of file + @Test + void testTableLinesVisibleReset() { + Table widgetToTest = createTestTable("Table { swt-lines-visible: true; }"); + assertTrue(widgetToTest.getLinesVisible()); + + css.getEngine().reset(); + + assertFalse(widgetToTest.getLinesVisible()); + } + + @Test + void testTableLinesVisibleResetKeepsProgrammaticValue() throws Exception { + Table widgetToTest = createTestTable(""); + widgetToTest.setLinesVisible(true); + css.getEngine().parseStyleSheet(new StringReader("Table { swt-lines-visible: false; }")); + css.getEngine().applyStyles(widgetToTest, false); + assertFalse(widgetToTest.getLinesVisible()); + + css.getEngine().reset(); + + assertTrue(widgetToTest.getLinesVisible()); + } + +} diff --git a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TreeTest.java b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TreeTest.java index e9e413ee7b2..1488778deb3 100644 --- a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TreeTest.java +++ b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/TreeTest.java @@ -16,6 +16,8 @@ import static org.eclipse.e4.ui.tests.css.swt.CssSwtEngine.BLUE; import static org.eclipse.e4.ui.tests.css.swt.CssSwtEngine.RED; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.swt.SWT; @@ -67,4 +69,14 @@ void testTreeHeaderColor() { assertEquals(BLUE, tableToTest.getHeaderForeground().getRGB()); } -} \ No newline at end of file + @Test + void testTreeLinesVisibleReset() { + Tree widgetToTest = createTestTree("Tree { swt-lines-visible: true; }"); + assertTrue(widgetToTest.getLinesVisible()); + + css.getEngine().reset(); + + assertFalse(widgetToTest.getLinesVisible()); + } + +} From 2829536ae6218a11c4a60e51eed472de1295d473 Mon Sep 17 00:00:00 2001 From: Philipp SALZGEBER Date: Fri, 2 Oct 2026 11:01:38 +0200 Subject: [PATCH 28/52] WizardDialog resizes itself in an endless loop after a DPI change eclipse-platform/eclipse.platform#2986 WizardDialog builds its shell with SWT.RESIZE but inherits isResizable() == false from Dialog, so hookZoomChangeListenerForDefaultSizedDialogs() installs adaptDefaultSizeListener on every wizard. That listener calls shell.setSize(shell.computeSize(...)), which sends the next SWT.Resize, and it has no re-entrancy guard: whenever the computed size is not a fixed point the listener recurses until the stack is exhausted. Let WizardDialog report the SWT.RESIZE bit of its shell style, and make the listener skip a nested call and a size that has not changed. Fixes https://github.com/eclipse-platform/eclipse.platform/issues/2986 Signed-off-by: Philipp SALZGEBER --- .../src/org/eclipse/jface/dialogs/Dialog.java | 18 ++- .../eclipse/jface/wizard/WizardDialog.java | 10 ++ .../jface/tests/dialogs/DialogTest.java | 110 ++++++++++++++++++ .../tests/wizards/TheTestWizardDialog.java | 5 + .../jface/tests/wizards/WizardTest.java | 37 ++++++ 5 files changed, 177 insertions(+), 3 deletions(-) diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/dialogs/Dialog.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/dialogs/Dialog.java index 12e534ad85b..11e5cbfdf73 100644 --- a/bundles/org.eclipse.jface/src/org/eclipse/jface/dialogs/Dialog.java +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/dialogs/Dialog.java @@ -16,6 +16,7 @@ import java.util.Arrays; import java.util.HashMap; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.core.runtime.IProgressMonitor; @@ -1109,13 +1110,24 @@ private void hookZoomChangeListenerForDefaultSizedDialogs() { } AtomicReference customResizeListener = new AtomicReference<>(); + // setSize() sends the next SWT.Resize, which calls this listener again. Without the + // re-entrancy guard the listener recurses until the stack is exhausted whenever the + // computed size is not a fixed point, e.g. because a scrollbar appears and disappears + // with it. + AtomicBoolean adaptingDefaultSize = new AtomicBoolean(); Listener adaptDefaultSizeListener = event -> { Shell shell = getShell(); - if (shell == null || shell.isDisposed()) { + if (shell == null || shell.isDisposed() || !adaptingDefaultSize.compareAndSet(false, true)) { return; } - Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); - shell.setSize(size); + try { + Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + if (!size.equals(shell.getSize())) { + shell.setSize(size); + } + } finally { + adaptingDefaultSize.set(false); + } }; AtomicReference zoomChangeListener = new AtomicReference<>(); zoomChangeListener.set(event -> { diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/wizard/WizardDialog.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/wizard/WizardDialog.java index 562d5493509..6b83af04a29 100644 --- a/bundles/org.eclipse.jface/src/org/eclipse/jface/wizard/WizardDialog.java +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/wizard/WizardDialog.java @@ -342,6 +342,16 @@ public int getShellStyle() { return super.getShellStyle(); } + /** + * A wizard dialog is resizable unless a caller has stripped {@link SWT#RESIZE} from its shell + * style, so the answer is read from that style instead of being inherited from + * Dialog, which always answers false. + */ + @Override + protected boolean isResizable() { + return (getShellStyle() & SWT.RESIZE) != 0; + } + private static int getShellModality(boolean modal) { return modal ? SWT.PRIMARY_MODAL : SWT.NONE; } diff --git a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/dialogs/DialogTest.java b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/dialogs/DialogTest.java index c8b47776b56..cea75e6265e 100644 --- a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/dialogs/DialogTest.java +++ b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/dialogs/DialogTest.java @@ -13,20 +13,30 @@ ******************************************************************************/ package org.eclipse.jface.tests.dialogs; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Shell; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; public class DialogTest { + /** Width the growing test content adds per size computation. */ + private static final int GROWTH = 50; + /** * The dialog being tested. */ @@ -77,6 +87,106 @@ public void testButtonAlignmentBug272583() { forceLayoutDialog.close(); } + /** + * A default-sized, non-resizable dialog adapts its size after a zoom change. + * The adaptation calls Shell.setSize, which sends the next + * SWT.Resize to the same listener. The listener must not recurse + * when the computed size keeps changing, must still adapt on a later resize, + * and must not resize when the computed size is unchanged. + */ + @Test + public void testZoomChangeAdaptationOfDefaultSizedDialogTerminates() { + GrowingContentDialog growingDialog = new GrowingContentDialog(); + dialog = growingDialog; + growingDialog.setBlockOnOpen(false); + growingDialog.create(); + Shell shell = growingDialog.getShell(); + Control firstChild = shell.getChildren()[0]; + Point initialSize = shell.getSize(); + // the adaptation is hooked only for a dialog that reports its default size + // after creation; where the platform reports another size for a shell that + // is not open yet, there is nothing to test + assumeFalse(growingDialog.resizeOccurredBeforeInitializeBounds(), + "a resize before initializeBounds marks the dialog as custom-sized"); + assumeTrue(initialSize.equals(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true)), + "the dialog must report its default size for the adaptation to be hooked"); + + // every computed size differs from the previous one, so a listener without + // re-entrancy guard recurses until the stack is exhausted + int widthBeforeZoomChange = growingDialog.content.preferredWidth; + growingDialog.content.growOnEveryComputeSize = true; + firstChild.notifyListeners(SWT.ZoomChanged, new Event()); + shell.notifyListeners(SWT.Resize, new Event()); + assertTrue(growingDialog.content.preferredWidth > widthBeforeZoomChange, + "the adaptation computes the size after the zoom change"); + Point adaptedSize = shell.getSize(); + assertNotEquals(initialSize, adaptedSize, "the dialog adapts its size once after the zoom change"); + + // a later independent resize adapts to the new preferred size + growingDialog.content.growOnEveryComputeSize = false; + growingDialog.content.preferredWidth += GROWTH; + shell.notifyListeners(SWT.Resize, new Event()); + Point resizedSize = shell.getSize(); + assertNotEquals(adaptedSize, resizedSize, "a later resize adapts the dialog to its new preferred size"); + + // an unchanged computed size causes no further resize + int[] resizeEvents = { 0 }; + shell.addListener(SWT.Resize, _ -> resizeEvents[0]++); + shell.notifyListeners(SWT.Resize, new Event()); + assertEquals(resizedSize, shell.getSize(), "an unchanged computed size keeps the size"); + assertEquals(1, resizeEvents[0], "an unchanged computed size sends no further resize"); + } + + /** + * A dialog whose content reports a preferred width that can grow with every + * computation, so that the computed shell size is never a fixed point while + * growing is on. + */ + private class GrowingContentDialog extends Dialog { + + GrowingContent content; + + GrowingContentDialog() { + super((Shell) null); + } + + boolean resizeOccurredBeforeInitializeBounds() { + return resizeHasOccurred; + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite area = (Composite) super.createDialogArea(parent); + content = new GrowingContent(area); + content.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + return area; + } + } + + /** + * The content has to be wider and higher than the rest of the dialog, so that + * its preferred size determines the computed shell size on every platform. A + * narrow content would leave the button bar as the widest part, and growing it + * would not change the size of the shell. + */ + private static class GrowingContent extends Composite { + + int preferredWidth = 600; + boolean growOnEveryComputeSize; + + GrowingContent(Composite parent) { + super(parent, SWT.NONE); + } + + @Override + public Point computeSize(int wHint, int hHint, boolean changed) { + if (growOnEveryComputeSize) { + preferredWidth += GROWTH; + } + return new Point(preferredWidth, 400); + } + } + /** * A dialog that explicitly invokes a layout operation prior to the shell being * opened. Calls to moveBelow(Control) should be followed by a layout operation diff --git a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/TheTestWizardDialog.java b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/TheTestWizardDialog.java index ad488612a48..8ccfd096843 100644 --- a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/TheTestWizardDialog.java +++ b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/TheTestWizardDialog.java @@ -35,6 +35,11 @@ public Button getFinishedButton() { return getButton(IDialogConstants.FINISH_ID); } + @Override + public boolean isResizable() { + return super.isResizable(); + } + @Override public Button getCancelButton() { return getButton(IDialogConstants.CANCEL_ID); diff --git a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/WizardTest.java b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/WizardTest.java index 46fb8d1b9b8..9e033f06bce 100644 --- a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/WizardTest.java +++ b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/wizards/WizardTest.java @@ -25,8 +25,11 @@ import org.eclipse.jface.dialogs.IPageChangingListener; import org.eclipse.jface.util.ILogger; import org.eclipse.jface.util.Policy; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Shell; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -253,6 +256,40 @@ public void testWizardPageDispose() { } + /** + * A wizard dialog is resizable, so a zoom change must not install the + * adaptation to the computed size that non-resizable dialogs get: a size + * requested afterwards has to stay. + */ + @Test + public void testResizableWizardKeepsRequestedSizeAfterZoomChange() { + assertTrue(dialog.isResizable(), "a wizard dialog with the default shell style is resizable"); + Shell shell = dialog.getShell(); + + shell.getChildren()[0].notifyListeners(SWT.ZoomChanged, new Event()); + Point requestedSize = new Point(shell.getSize().x + 60, shell.getSize().y + 40); + shell.setSize(requestedSize); + shell.notifyListeners(SWT.Resize, new Event()); + + assertEquals(requestedSize, shell.getSize(), "the requested size is kept after a zoom change"); + } + + /** + * Removing SWT.RESIZE from the shell style before the shell is created gives a + * fixed-size wizard dialog. + */ + @Test + public void testWizardWithoutResizeStyleIsNotResizable() { + TheTestWizardDialog fixedSizeDialog = new TheTestWizardDialog(null, new TheTestWizard()); + fixedSizeDialog.setShellStyle(fixedSizeDialog.getShellStyle() & ~SWT.RESIZE); + try { + fixedSizeDialog.create(); + assertFalse(fixedSizeDialog.isResizable(), "a wizard dialog without SWT.RESIZE is not resizable"); + } finally { + fixedSizeDialog.close(); + } + } + //---------------------------------------------------- @BeforeEach From bb9c080a38e9602e67a9c91b3aa290865de26c64 Mon Sep 17 00:00:00 2001 From: "Knoll, Vladislav" Date: Fri, 23 Oct 2026 10:20:48 +0200 Subject: [PATCH 29/52] Find/Replace: replace the selected match instead of the last found one Replacing a selected occurrence of the find string could change a different part of the document or silently do nothing. This happened whenever the selection no longer corresponded to the target's most recent search, e.g., after an undo restored a replaced match or after the user manually selected another occurrence of the find string. Replace now always acts on the selected match: if the selection is an occurrence of the find string, exactly that occurrence is replaced; otherwise, the next match is searched and selected as before. The target replaces the match of its most recent search, which is independent of the selection and outdated by any document change. FindReplaceLogic therefore searches forward from the start of the selection before replacing and only keeps the selection if that search yields exactly the selected text, which makes the selection the single source of truth for what gets replaced. Assisted-by: Claude Opus 5.5 --- .../findandreplace/FindReplaceLogic.java | 29 +++++++++- .../findandreplace/FindReplaceLogicTest.java | 54 ++++++++++++++++++ .../findandreplace/FindReplaceUITest.java | 56 ++++++++++++++++++- .../FindReplaceOverlayInEditorTest.java | 22 ++++++++ 4 files changed, 158 insertions(+), 3 deletions(-) diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java index 14f846ba9c1..fda60cc64da 100644 --- a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java @@ -522,8 +522,11 @@ private int findIndex(int startPosition) { @Override public int findAndSelect(int offset) { + return findAndSelect(offset, isAvailableAndActive(SearchOptions.FORWARD)); + } + + private int findAndSelect(int offset, boolean forwardSearch) { boolean wholeWordSearch = isAvailableAndActive(SearchOptions.WHOLE_WORD); - boolean forwardSearch = isAvailableAndActive(SearchOptions.FORWARD); boolean caseSensitiveSearch = isAvailableAndActive(SearchOptions.CASE_SENSITIVE); boolean regexSearch = isAvailableAndActive(SearchOptions.REGEX); @@ -616,7 +619,7 @@ public boolean performReplaceAndFind() { @Override public boolean performSelectAndReplace() { resetStatus(); - if (!isFindStringSelected()) { + if (!selectMatchAtSelection()) { performSearch(); } if (getStatus().wasSuccessful()) { @@ -634,6 +637,28 @@ public boolean performSelectAndReplace() { return false; } + /** + * Searches again for the find string at the start of the current selection. + * The target replaces the match of its most recent search, which becomes stale + * as soon as the document changes, e.g., by an undo. Searching again ensures + * that a subsequent replace refers to the selected text. + * + * @return whether the selection is exactly a match of the find string + */ + private boolean selectMatchAtSelection() { + if (target == null || !isFindStringSelected()) { + return false; + } + Point selection = target.getSelection(); + if (findAndSelect(selection.x, true) == selection.x && selection.equals(target.getSelection())) { + return true; + } + if (target instanceof IFindReplaceTargetExtension extension) { + extension.setSelection(selection.x, selection.y); + } + return false; + } + private boolean isFindStringSelected() { String selectedString = getCurrentSelection(); if (isAvailableAndActive(SearchOptions.REGEX)) { diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java index 5f4f75326ea..5968a87432b 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java @@ -231,6 +231,60 @@ public void testPerformSelectAndReplace() { expectStatusEmpty(findReplaceLogic); } + @Test + public void testReplaceAfterMovingSelectionToAnotherMatch() { + assertReplaceAfterMovingSelection(true, false); + } + + @Test + public void testReplaceAfterMovingSelectionToAnotherMatchBackwards() { + assertReplaceAfterMovingSelection(false, false); + } + + @Test + public void testRegexReplaceAfterMovingSelectionToAnotherMatch() { + assertReplaceAfterMovingSelection(true, true); + } + + @Test + public void testRegexReplaceAfterMovingSelectionToAnotherMatchBackwards() { + assertReplaceAfterMovingSelection(false, true); + } + + private void assertReplaceAfterMovingSelection(boolean forward, boolean regex) { + TextViewer textViewer= setupTextViewer("word one word two"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + if (forward) { + findReplaceLogic.activate(SearchOptions.FORWARD); + } + if (regex) { + findReplaceLogic.activate(SearchOptions.REGEX); + } + setFindAndReplaceString(findReplaceLogic, regex ? "w(\\w+)" : "word", regex ? "$1" : "X"); + assertEquals(9, findReplaceLogic.findAndSelect(forward ? 9 : 12)); + textViewer.setSelectedRange(0, 4); + + assertTrue(findReplaceLogic.performSelectAndReplace()); + assertEquals(regex ? "ord one word two" : "X one word two", textViewer.getDocument().get()); + expectStatusEmpty(findReplaceLogic); + } + + @Test + public void testReplaceAfterDocumentChangeShiftsMatch() throws Exception { + TextViewer textViewer= setupTextViewer("word one word two"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + setFindAndReplaceString(findReplaceLogic, "word", "X"); + assertEquals(9, findReplaceLogic.findAndSelect(9)); + + textViewer.getDocument().replace(0, 0, "prefix "); + textViewer.setSelectedRange(16, 4); + + assertTrue(findReplaceLogic.performSelectAndReplace()); + assertEquals("prefix word one X two", textViewer.getDocument().get()); + expectStatusEmpty(findReplaceLogic); + } + @Test public void testPerformSelectAndReplaceRegEx() { TextViewer textViewer= setupTextViewer("HelloWorld!"); diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceUITest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceUITest.java index a23d1b84623..271b43f7a7c 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceUITest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceUITest.java @@ -13,7 +13,9 @@ ******************************************************************************/ package org.eclipse.ui.internal.findandreplace; +import static org.eclipse.ui.internal.findandreplace.FindReplaceTestUtil.waitForFocus; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -21,18 +23,20 @@ import org.junit.jupiter.api.TestInfo; import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Control; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextViewer; +import org.eclipse.jface.text.TextViewerUndoManager; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.FindReplaceAction; public abstract class FindReplaceUITest { - + protected TestInfo testInfo; private TextViewer fTextViewer; @@ -250,6 +254,56 @@ public void testSimpleReplace() { assertEquals("oo oo oo", fTextViewer.getDocument().get()); } + @Test + public void testReplaceAgainAfterUndoWithNoRemainingMatch() { + assertReplaceAgainAfterUndo("word", false); + } + + @Test + public void testReplaceAgainAfterUndoWithAnotherMatch() { + assertReplaceAgainAfterUndo("word one word two", false); + } + + @Test + public void testRegexReplaceAgainAfterUndo() { + assertReplaceAgainAfterUndo("word one word two", true); + } + + private void assertReplaceAgainAfterUndo(String content, boolean regex) { + initializeTextViewerWithFindReplaceUI(content); + TextViewerUndoManager undoManager= new TextViewerUndoManager(10); + undoManager.connect(fTextViewer); + try { + dialog.select(SearchOptions.INCREMENTAL); + dialog.select(SearchOptions.WRAP); + if (regex) { + dialog.select(SearchOptions.REGEX); + } + dialog.setFindText(regex ? "w(\\w+)" : "word"); + dialog.setReplaceText(regex ? "$1" : "X"); + String expected= (regex ? "ord" : "X") + content.substring(4); + + dialog.performReplace(); + assertEquals(expected, fTextViewer.getDocument().get()); + Control inputField= fTextViewer.getTextWidget().getDisplay().getFocusControl(); + fTextViewer.getTextWidget().getShell().forceActive(); + fTextViewer.getTextWidget().forceFocus(); + waitForFocus(fTextViewer.getTextWidget()::isFocusControl, testInfo.getTestMethod().get().getName()); + assertTrue(undoManager.undoable()); + undoManager.undo(); + assertEquals(content, fTextViewer.getDocument().get()); + assertTrue(dialog.isShown()); + assertTrue(undoManager.redoable()); + inputField.getShell().forceActive(); + inputField.forceFocus(); + waitForFocus(inputField::isFocusControl, testInfo.getTestMethod().get().getName()); + dialog.performReplace(); + assertEquals(expected, fTextViewer.getDocument().get()); + } finally { + undoManager.disconnect(); + } + } + @Test public void testReplaceAllInSelection() { openTextViewer("line" + System.lineSeparator() + "line" + System.lineSeparator() + "line"); diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlayInEditorTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlayInEditorTest.java index 374ebbddab4..f0270074f86 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlayInEditorTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/overlay/FindReplaceOverlayInEditorTest.java @@ -244,6 +244,28 @@ public void testEnterMeansSomethingElseInEachInputField() throws Exception { "Enter in the replace field must replace the current match in the document"); //$NON-NLS-1$ } + @Test + public void testReplaceAgainAfterUndoInEditor() throws Exception { + focusSearchField(); + searchField.setText("word"); //$NON-NLS-1$ + Text replaceField = showReplaceField(); + replaceField.setText("X"); //$NON-NLS-1$ + type(replaceField, SWT.NONE, SWT.CR); + assertEquals("X one word two", documentText()); //$NON-NLS-1$ + + editor.setFocus(); + waitForFocus(editorWidget()::isFocusControl, testName); + executeCommand("org.eclipse.ui.edit.undo"); //$NON-NLS-1$ + assertEquals(CONTENT, documentText()); + assertTrue(searchField.isVisible(), "Undo must leave the overlay open"); //$NON-NLS-1$ + + replaceField.forceFocus(); + waitForFocus(replaceField::isFocusControl, testName); + type(replaceField, SWT.NONE, SWT.CR); + + assertEquals("X one word two", documentText()); //$NON-NLS-1$ + } + /** * The editor's Find Next and Find Previous stay meaningful while an input field * has focus, so they must search on for what is typed there, exactly as the From ad19908bb0b8769effa9a4fcfd27b0f7f40a502c Mon Sep 17 00:00:00 2001 From: Sven Reinhardt Date: Sat, 31 Oct 2026 16:21:13 +0100 Subject: [PATCH 30/52] Add auto-incrementing counter placeholder to Find/Replace #3842 Adds a #{start,step,pad} counter placeholder to regular expression replace strings of Find/Replace. During Replace All or Replace/Find the placeholder expands to an auto-incrementing number with optional zero-padding, e.g. "$1_#{1,1,2}" produces "Match1_01", "Match1_02", ... - The placeholder is only expanded in regular expression mode, plain replace strings are inserted literally as before. - start and step are limited to 9 digits and pad to 20, so that parsing can not fail while typing. - Padding does not count the minus sign, digits are always ASCII. - The counter restarts with each Replace All and whenever the replace string changes; consecutive single replacements continue counting. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/3842 Co-Authored-By: Claude Opus 5.5 --- ...ocumentAdapterContentProposalProvider.java | 1 + .../jface/text/RegExMessages.properties | 17 ++ .../findandreplace/FindReplaceLogic.java | 32 ++- .../findandreplace/ReplaceCounter.java | 147 +++++++++++ .../findandreplace/FindReplaceLogicTest.java | 243 ++++++++++++++++++ .../findandreplace/ReplaceCounterTest.java | 205 +++++++++++++++ 6 files changed, 642 insertions(+), 3 deletions(-) create mode 100644 bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/ReplaceCounter.java create mode 100644 tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/ReplaceCounterTest.java diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java index 65e95c6da50..05c3fc9795f 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java @@ -230,6 +230,7 @@ public IContentProposal[] computeReplaceProposals() { addBracketProposal("\\c", 2, RegExMessages.getString("displayString_bs_c"), RegExMessages.getString("additionalInfo_bs_c")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addBsProposal("\\C", RegExMessages.getString("displayString_replace_bs_C"), RegExMessages.getString("additionalInfo_replace_bs_C")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } + addBracketProposal("#{1,1,3}", 8, RegExMessages.getString("displayString_counter"), RegExMessages.getString("additionalInfo_counter")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fPriorityProposals.addAll(fProposals); return fPriorityProposals.toArray(new IContentProposal[fPriorityProposals.size()]); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/RegExMessages.properties b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/RegExMessages.properties index 50560585d98..e1d35853e1e 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/RegExMessages.properties +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/RegExMessages.properties @@ -541,3 +541,20 @@ Find: "foo" Replace: "my\\Cbar\\CFar"\n\ "Foo" will be replaced by "myBarFar".\n\n\ Note that the content of a group ($i, \\i) is currently inserted unmodified. +displayString_counter=#{start,step,pad} - Auto-incrementing counter +additionalInfo_counter=#{start,step,pad} - Inserts an auto-incrementing counter (regular expression mode only).\n\n\ +Syntax: #{start,step,pad}\n\ + start \u2014 initial value (may be negative, at most 9 digits)\n\ + step \u2014 increment per replacement (negative for descending, at most 9 digits)\n\ + pad \u2014 minimum digit width without sign, zero-padded (0 = no padding, at most 20)\n\n\ +Examples:\n\ + #{1,1,3} \u2192 001, 002, 003, ...\n\ + #{10,5,0} \u2192 10, 15, 20, ...\n\ + #{100,-1,0} \u2192 100, 99, 98, ...\n\n\ +Can be combined with text and regex groups:\n\ + item_#{1,1,2} \u2192 item_01, item_02, ...\n\ + $1_#{1,1,2} \u2192 Match1_01, Match1_02, ...\n\n\ +The counter restarts with each Replace All and whenever the replace string changes; \ +consecutive single replacements continue counting.\n\ +Only the first counter placeholder is expanded.\n\ +A $ or \\ directly in front of the placeholder must be escaped (e.g. \\$#{1,1,0}). diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java index 14f846ba9c1..ddcd0fe778f 100644 --- a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogic.java @@ -63,6 +63,7 @@ public class FindReplaceLogic implements IFindReplaceLogic { private String findString = ""; //$NON-NLS-1$ private String replaceString = ""; //$NON-NLS-1$ + private ReplaceCounter replaceCounter; private final Map>> activationChangedListeners = new HashMap<>(); private final Map>> availabilityChangedListeners = new HashMap<>(); @@ -118,7 +119,28 @@ public void setFindString(String findString) { @Override public void setReplaceString(String replaceString) { - this.replaceString = Objects.requireNonNull(replaceString); + Objects.requireNonNull(replaceString); + // keep the counter state if the text did not change, so that consecutive + // single replacements continue counting + if (!replaceString.equals(this.replaceString)) { + this.replaceCounter = ReplaceCounter.parse(replaceString); + } + this.replaceString = replaceString; + } + + /** + * Returns the effective replace string for the current replacement. If regex + * search is active and the replace string contains a counter placeholder + * ({@code #{start,step,pad}}), the placeholder is replaced by the next counter + * value. Otherwise the raw replace string is returned unchanged. + * + * @return the replace string with counter placeholder expanded (if any) + */ + private String buildReplaceString() { + if (replaceCounter != null && isAvailableAndActive(SearchOptions.REGEX)) { + return replaceCounter.expand(replaceString); + } + return replaceString; } @Override @@ -432,6 +454,9 @@ private int replaceAll() { } List replacements = new ArrayList<>(); + if (replaceCounter != null) { + replaceCounter.reset(); + } executeInForwardMode(() -> { executeWithReplaceAllEnabled(() -> { Point currentSelection = new Point(0, 0); @@ -546,11 +571,12 @@ public int findAndSelect(int offset) { * @return the selection after replacing, i.e. the inserted text */ private Point replaceSelection() { + String effectiveReplaceString = buildReplaceString(); if (target instanceof IFindReplaceTargetExtension3) { - ((IFindReplaceTargetExtension3) target).replaceSelection(replaceString, + ((IFindReplaceTargetExtension3) target).replaceSelection(effectiveReplaceString, isAvailableAndActive(SearchOptions.REGEX)); } else { - target.replaceSelection(replaceString); + target.replaceSelection(effectiveReplaceString); } return target.getSelection(); diff --git a/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/ReplaceCounter.java b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/ReplaceCounter.java new file mode 100644 index 00000000000..66741c05063 --- /dev/null +++ b/bundles/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/findandreplace/ReplaceCounter.java @@ -0,0 +1,147 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to Eclipse Foundation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Contributors to Eclipse Foundation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.findandreplace; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Provides an auto-incrementing counter that can be embedded in regular + * expression Find/Replace replace strings using the placeholder syntax + * {@code #{start,step,pad}}. + * + *

+ * Syntax: {@code #{start,step,pad}} where + *

    + *
  • {@code start} — initial value (integer of at most 9 digits, may be + * negative)
  • + *
  • {@code step} — increment per replacement (integer of at most 9 + * digits, may be negative for descending sequences)
  • + *
  • {@code pad} — minimum number of digits, zero-padded, not counting + * a minus sign (0 = no padding, at most {@value #MAX_PAD})
  • + *
+ * + *

+ * Examples: + *

    + *
  • {@code #{1,1,3}} — produces {@code 001}, {@code 002}, + * {@code 003}, …
  • + *
  • {@code #{10,5,0}} — produces {@code 10}, {@code 15}, {@code 20}, + * …
  • + *
  • {@code #{100,-1,0}} — produces {@code 100}, {@code 99}, + * {@code 98}, …
  • + *
+ * + *

+ * The placeholder may be combined with literal text and regex back-references, + * for example {@code $1_#{1,1,2}} produces {@code Match1_01}, + * {@code Match1_02}, … Only the first placeholder in a replace string is + * expanded. Since the counter value is inserted before the replace string is + * interpreted as a regular expression replacement, a {@code $} or {@code \} + * directly in front of the placeholder must be escaped (e.g. + * {@code \$#{1,1,0}}), otherwise it forms a group reference with the counter + * value. + */ +public final class ReplaceCounter { + + /** Maximum supported value for the {@code pad} parameter. */ + static final int MAX_PAD = 20; + + /** + * Pattern matching the counter placeholder {@code #{start,step,pad}}. + * Captures: group 1 = start, group 2 = step, group 3 = pad. The number of + * digits is limited so that the values always fit into an {@code int}. + */ + static final Pattern COUNTER_PATTERN = Pattern.compile("#\\{(-?\\d{1,9}),(-?\\d{1,9}),(\\d{1,2})\\}"); //$NON-NLS-1$ + + private final int start; + private final int step; + private final int pad; + private long current; + + /** + * Creates a counter with the given parameters. + * + * @param start initial counter value + * @param step increment applied after each {@link #next()} call + * @param pad minimum digit width (0 = no padding), limited to + * {@value #MAX_PAD} + */ + public ReplaceCounter(int start, int step, int pad) { + this.start = start; + this.step = step; + this.pad = Math.max(0, Math.min(pad, MAX_PAD)); + this.current = start; + } + + /** Resets the counter to the initial {@code start} value. */ + public void reset() { + current = start; + } + + /** + * Returns the current counter value as a (possibly zero-padded) string, then + * advances the counter by {@code step}. A minus sign is not counted as a + * digit, i.e. {@code -5} with a padding of 3 is formatted as {@code -005}. + * + * @return formatted counter value + */ + public String next() { + long value = current; + current += step; + String digits = Long.toString(Math.abs(value)); + StringBuilder result = new StringBuilder(Math.max(pad, digits.length()) + 1); + if (value < 0) { + result.append('-'); + } + for (int i = digits.length(); i < pad; i++) { + result.append('0'); + } + return result.append(digits).toString(); + } + + /** + * Replaces the first counter placeholder in {@code template} with the + * {@link #next()} value. + * + * @param template the replace string possibly containing {@code #{...}} + * @return the template with the placeholder replaced by the next counter value + */ + public String expand(String template) { + Matcher matcher = COUNTER_PATTERN.matcher(template); + if (matcher.find()) { + return matcher.replaceFirst(Matcher.quoteReplacement(next())); + } + return template; + } + + /** + * Parses the first counter placeholder found in {@code replaceString} and + * returns a new {@link ReplaceCounter} with the corresponding parameters. + * Returns {@code null} if no placeholder is present. + * + * @param replaceString string to parse + * @return a new counter, or {@code null} + */ + public static ReplaceCounter parse(String replaceString) { + Matcher matcher = COUNTER_PATTERN.matcher(replaceString); + if (matcher.find()) { + int start = Integer.parseInt(matcher.group(1)); + int step = Integer.parseInt(matcher.group(2)); + int pad = Integer.parseInt(matcher.group(3)); + return new ReplaceCounter(start, step, pad); + } + return null; + } +} diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java index 5f4f75326ea..53ccb2e2447 100644 --- a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/FindReplaceLogicTest.java @@ -1147,4 +1147,247 @@ private void expectStatusIsMessageWithString(IFindReplaceLogic findReplaceLogic, assertEquals(message, ((InvalidRegExStatus) findReplaceLogic.getStatus()).getMessage()); } + // ----------------------------------------------------------------------- + // Counter placeholder #{start,step,pad} integration tests + // ----------------------------------------------------------------------- + + @Test + public void testReplaceAll_withCounter_paddedAscending() { + TextViewer textViewer= setupTextViewer("a a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,3}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("001 002 003", textViewer.getDocument().get()); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); + } + + @Test + public void testReplaceAll_withCounter_unpaddedLargeStep() { + TextViewer textViewer= setupTextViewer("x x x"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "x", "#{10,10,0}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("10 20 30", textViewer.getDocument().get()); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); + } + + @Test + public void testReplaceAll_withCounter_resetsOnNewReplaceString() { + TextViewer textViewer= setupTextViewer("a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}"); + findReplaceLogic.performReplaceAll(); + assertEquals("1 2", textViewer.getDocument().get()); + + // Reset document and perform again with the same replace string set anew + textViewer.setDocument(new Document("a a")); + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}"); + findReplaceLogic.performReplaceAll(); + assertEquals("1 2", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withCounter_counterResetsBetweenReplaceAllCalls() { + TextViewer textViewer= setupTextViewer("a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}"); + findReplaceLogic.performReplaceAll(); + assertEquals("1 2", textViewer.getDocument().get()); + + // Second Replace All on new content must restart from 1, not continue from 3 + textViewer.setDocument(new Document("a a")); + findReplaceLogic.performReplaceAll(); + assertEquals("1 2", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withCounter_descendingSequence() { + TextViewer textViewer= setupTextViewer("z z z z"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "z", "#{10,-2,0}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("10 8 6 4", textViewer.getDocument().get()); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 4); + } + + @Test + public void testReplaceAll_withCounter_combinedWithLiteralText() { + TextViewer textViewer= setupTextViewer("x x"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "x", "item_#{1,1,2}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("item_01 item_02", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withoutCounter_behavesAsPlainReplace() { + TextViewer textViewer= setupTextViewer("a a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "b"); + findReplaceLogic.performReplaceAll(); + + assertEquals("b b b", textViewer.getDocument().get()); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); + } + + @Test + public void testReplaceAll_withCounter_andRegex() { + TextViewer textViewer= setupTextViewer("aa bb cc"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "(\\w+)", "$1_#{1,1,2}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("aa_01 bb_02 cc_03", textViewer.getDocument().get()); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 3); + } + + @Test + public void testSelectAndReplace_withCounter_incrementsAcrossCalls() { + TextViewer textViewer= setupTextViewer("a a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}"); + + findReplaceLogic.performSearch(); + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 a a", textViewer.getDocument().get()); + + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 2 a", textViewer.getDocument().get()); + + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 2 3", textViewer.getDocument().get()); + } + + @Test + public void testSelectAndReplace_withCounter_continuesWhenSameReplaceStringIsSetAgain() { + TextViewer textViewer= setupTextViewer("a a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}"); + findReplaceLogic.performSearch(); + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 a a", textViewer.getDocument().get()); + + // e.g. a modify event of the replace field without actual text change + findReplaceLogic.setReplaceString("#{1,1,0}"); + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 2 a", textViewer.getDocument().get()); + } + + @Test + public void testSelectAndReplace_withCounter_restartsWhenReplaceStringChanges() { + TextViewer textViewer= setupTextViewer("a a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}"); + findReplaceLogic.performSearch(); + findReplaceLogic.performSelectAndReplace(); + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 2 a", textViewer.getDocument().get()); + + findReplaceLogic.setReplaceString("x#{1,1,0}"); + findReplaceLogic.performSelectAndReplace(); + assertEquals("1 2 x1", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withCounter_withoutRegex_insertsPlaceholderLiterally() { + TextViewer textViewer= setupTextViewer("a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,3}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("#{1,1,3} #{1,1,3}", textViewer.getDocument().get()); + expectStatusIsReplaceAllWithCount(findReplaceLogic, 2); + } + + @Test + public void testReplaceAll_withCounter_paddingExcludesMinusSign() { + TextViewer textViewer= setupTextViewer("a a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{-1,1,2}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("-01 00 01", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withCounter_onlyFirstPlaceholderIsExpanded() { + TextViewer textViewer= setupTextViewer("a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{1,1,0}-#{5,1,0}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("1-#{5,1,0} 2-#{5,1,0}", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withCounter_escapedDollarInFrontOfPlaceholder() { + TextViewer textViewer= setupTextViewer("a a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "\\$#{1,1,0}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("$1 $2", textViewer.getDocument().get()); + } + + @Test + public void testReplaceAll_withCounter_tooLargeNumbersAreInsertedLiterally() { + TextViewer textViewer= setupTextViewer("a"); + IFindReplaceLogic findReplaceLogic= setupFindReplaceLogicObject(textViewer); + findReplaceLogic.activate(SearchOptions.FORWARD); + findReplaceLogic.activate(SearchOptions.REGEX); + + setFindAndReplaceString(findReplaceLogic, "a", "#{99999999999,1,0}"); + findReplaceLogic.performReplaceAll(); + + assertEquals("#{99999999999,1,0}", textViewer.getDocument().get()); + } + } diff --git a/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/ReplaceCounterTest.java b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/ReplaceCounterTest.java new file mode 100644 index 00000000000..60c9d93cd0b --- /dev/null +++ b/tests/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/internal/findandreplace/ReplaceCounterTest.java @@ -0,0 +1,205 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to Eclipse Foundation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Contributors to Eclipse Foundation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.findandreplace; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +public class ReplaceCounterTest { + + // ----------------------------------------------------------------------- + // parse + // ----------------------------------------------------------------------- + + @Test + public void parse_returnsNull_whenNoPlaceholder() { + assertNull(ReplaceCounter.parse("no counter here")); + assertNull(ReplaceCounter.parse("")); + } + + @Test + public void parse_returnsNull_forIncompleteSyntax() { + assertNull(ReplaceCounter.parse("#{1,1}")); // missing pad + assertNull(ReplaceCounter.parse("{1,1,3}")); // missing # + assertNull(ReplaceCounter.parse("#{1,1,-3}")); // negative pad + } + + @Test + public void parse_returnsNull_forNumbersExceedingLimits() { + assertNull(ReplaceCounter.parse("#{99999999999,1,0}")); + assertNull(ReplaceCounter.parse("#{1,99999999999,0}")); + assertNull(ReplaceCounter.parse("#{1,1,99999999999}")); + assertNull(ReplaceCounter.parse("#{1,1,100}")); + } + + @Test + public void parse_acceptsMaximumNumberOfDigits() { + ReplaceCounter counter = ReplaceCounter.parse("#{-999999999,999999999,0}"); + assertNotNull(counter); + assertEquals("-999999999", counter.next()); + assertEquals("0", counter.next()); + } + + @Test + public void parse_limitsPadding() { + ReplaceCounter counter = ReplaceCounter.parse("#{1,1,99}"); + assertNotNull(counter); + assertEquals("0".repeat(ReplaceCounter.MAX_PAD - 1) + "1", counter.next()); + } + + @Test + public void parse_returnsCounter_withCorrectParameters() { + ReplaceCounter counter = ReplaceCounter.parse("#{1,1,3}"); + assertNotNull(counter); + // Verify behaviour rather than private state: + assertEquals("001", counter.next()); + assertEquals("002", counter.next()); + } + + @Test + public void parse_handlesNegativeStep() { + ReplaceCounter counter = ReplaceCounter.parse("#{100,-1,0}"); + assertNotNull(counter); + assertEquals("100", counter.next()); + assertEquals("99", counter.next()); + } + + @Test + public void parse_handlesNegativeStart() { + ReplaceCounter counter = ReplaceCounter.parse("#{-5,5,0}"); + assertNotNull(counter); + assertEquals("-5", counter.next()); + assertEquals("0", counter.next()); + assertEquals("5", counter.next()); + } + + // ----------------------------------------------------------------------- + // next / padding + // ----------------------------------------------------------------------- + + @Test + public void next_producesZeroPaddedValues() { + ReplaceCounter counter = new ReplaceCounter(1, 1, 3); + assertEquals("001", counter.next()); + assertEquals("002", counter.next()); + assertEquals("003", counter.next()); + } + + @Test + public void next_producesUnpaddedValues_whenPadZero() { + ReplaceCounter counter = new ReplaceCounter(10, 5, 0); + assertEquals("10", counter.next()); + assertEquals("15", counter.next()); + assertEquals("20", counter.next()); + } + + @Test + public void next_descending() { + ReplaceCounter counter = new ReplaceCounter(5, -1, 0); + assertEquals("5", counter.next()); + assertEquals("4", counter.next()); + assertEquals("3", counter.next()); + } + + @Test + public void next_paddingExcludesMinusSign() { + ReplaceCounter counter = new ReplaceCounter(-2, 1, 3); + assertEquals("-002", counter.next()); + assertEquals("-001", counter.next()); + assertEquals("000", counter.next()); + assertEquals("001", counter.next()); + } + + @Test + public void next_doesNotOverflowIntRange() { + ReplaceCounter counter = new ReplaceCounter(Integer.MAX_VALUE, 1, 0); + assertEquals(Integer.toString(Integer.MAX_VALUE), counter.next()); + assertEquals(Long.toString(Integer.MAX_VALUE + 1L), counter.next()); + } + + @Test + public void next_usesAsciiDigitsIndependentOfDefaultLocale() { + Locale defaultLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.forLanguageTag("th-TH-u-nu-thai")); + ReplaceCounter counter = new ReplaceCounter(7, 1, 3); + assertEquals("007", counter.next()); + } finally { + Locale.setDefault(defaultLocale); + } + } + + @Test + public void constructor_limitsPadding() { + ReplaceCounter counter = new ReplaceCounter(1, 1, 1000); + assertEquals(ReplaceCounter.MAX_PAD, counter.next().length()); + } + + @Test + public void next_largeStep() { + ReplaceCounter counter = new ReplaceCounter(0, 100, 0); + assertEquals("0", counter.next()); + assertEquals("100", counter.next()); + } + + // ----------------------------------------------------------------------- + // reset + // ----------------------------------------------------------------------- + + @Test + public void reset_restoresStartValue() { + ReplaceCounter counter = new ReplaceCounter(1, 1, 2); + counter.next(); + counter.next(); + counter.reset(); + assertEquals("01", counter.next()); + } + + // ----------------------------------------------------------------------- + // expand + // ----------------------------------------------------------------------- + + @Test + public void expand_replacesSinglePlaceholder() { + ReplaceCounter counter = new ReplaceCounter(1, 1, 3); + assertEquals("item_001_end", counter.expand("item_#{1,1,3}_end")); + assertEquals("item_002_end", counter.expand("item_#{1,1,3}_end")); + } + + @Test + public void expand_replacesOnlyFirstPlaceholder() { + ReplaceCounter counter = ReplaceCounter.parse("#{1,1,0}-#{5,1,0}"); + assertEquals("1-#{5,1,0}", counter.expand("#{1,1,0}-#{5,1,0}")); + } + + @Test + public void expand_returnsTemplateUnchanged_whenNoPlaceholder() { + ReplaceCounter counter = new ReplaceCounter(1, 1, 0); + String plain = "no placeholder here"; + assertEquals(plain, counter.expand(plain)); + } + + @Test + public void expand_doesNotConsumeTick_whenNoPlaceholder() { + ReplaceCounter counter = new ReplaceCounter(1, 1, 0); + counter.expand("no placeholder"); + // counter must not have moved + assertEquals("1", counter.next()); + } +} From 18fb92d4d30c06ea8a86f8c0130cf79c84206576 Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Sun, 1 Nov 2026 18:39:16 +0100 Subject: [PATCH 31/52] Rebuild the Section title bar image when its colors change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Section kept its title bar gradient image until the next resize, so after a theme switch open forms showed the title bars of the previous theme. Changing a title bar color or the background now drops the image. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../org/eclipse/ui/forms/widgets/Section.java | 26 +++-- .../tests/forms/widgets/AllWidgetsTests.java | 2 +- .../ui/tests/forms/widgets/SectionTest.java | 103 ++++++++++++++++++ 3 files changed, 122 insertions(+), 9 deletions(-) create mode 100644 tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/SectionTest.java diff --git a/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/widgets/Section.java b/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/widgets/Section.java index f99c23fb5f4..b8a6f6d9a12 100644 --- a/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/widgets/Section.java +++ b/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/forms/widgets/Section.java @@ -90,13 +90,7 @@ public Section(Composite parent, int style) { descriptionControl = new Label(this, SWT.WRAP | rtl); } if ((style & TITLE_BAR) != 0) { - Listener listener = e -> { - Image image = Section.super.getBackgroundImage(); - if (image != null) { - FormImages.getInstance().markFinished(image, getDisplay()); - } - Section.super.setBackgroundImage(null); - }; + Listener listener = e -> clearHeaderImage(); addListener(SWT.Dispose, listener); addListener(SWT.Resize, listener); } @@ -184,7 +178,11 @@ public Control getSeparatorControl() { */ @Override public void setBackground(Color bg) { + boolean changed = !getBackground().equals(bg); super.setBackground(bg); + if (changed) { + clearHeaderImage(); + } if (descriptionControl != null && (getExpansionStyle() & DESCRIPTION) != 0) { descriptionControl.setBackground(bg); @@ -320,7 +318,19 @@ private void putTitleBarColor(String key, Color color) { if (titleColors == null) { titleColors = new Hashtable<>(); } - titleColors.put(key, color); + if (!color.equals(titleColors.put(key, color))) { + clearHeaderImage(); + redraw(); + } + } + + /** Drops the cached title bar image so that the next paint rebuilds it. */ + private void clearHeaderImage() { + Image image = super.getBackgroundImage(); + if (image != null) { + FormImages.getInstance().markFinished(image, getDisplay()); + } + super.setBackgroundImage(null); } @Override diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/AllWidgetsTests.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/AllWidgetsTests.java index 41725826f78..a37f105a48f 100644 --- a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/AllWidgetsTests.java +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/AllWidgetsTests.java @@ -20,7 +20,7 @@ * Tests forms widgets (automated). */ @Suite -@SelectClasses({ ExpandableCompositeTest.class, FormTextModelTest.class, ScrolledFormTest.class }) +@SelectClasses({ ExpandableCompositeTest.class, FormTextModelTest.class, ScrolledFormTest.class, SectionTest.class }) public class AllWidgetsTests { } diff --git a/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/SectionTest.java b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/SectionTest.java new file mode 100644 index 00000000000..f68c77eb70e --- /dev/null +++ b/tests/org.eclipse.ui.tests.forms/forms/org/eclipse/ui/tests/forms/widgets/SectionTest.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright (c) 2026 vogella GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * vogella GmbH - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.forms.widgets; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.Section; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class SectionTest { + + private static final Color BODY = new Color(255, 255, 255); + private static final Color LIGHT_TITLE = new Color(234, 234, 234); + private static final Color DARK_TITLE = new Color(79, 83, 85); + + private Shell shell; + private Section section; + + @BeforeEach + public void createSection() { + shell = new Shell(Display.getDefault()); + section = new Section(shell, ExpandableComposite.TITLE_BAR); + section.setText("Title"); + section.setSize(200, 100); + section.setBackground(BODY); + section.setTitleBarBackground(LIGHT_TITLE); + section.setTitleBarGradientBackground(LIGHT_TITLE); + } + + @AfterEach + public void disposeShell() { + shell.dispose(); + } + + @Test + public void testTitleBarColorChangeRebuildsHeaderImage() { + Image before = paintedHeaderImage(); + + section.setTitleBarBackground(DARK_TITLE); + + assertNull(section.getBackgroundImage()); + assertNotSame(before, paintedHeaderImage()); + } + + @Test + public void testUnchangedTitleBarColorKeepsHeaderImage() { + Image before = paintedHeaderImage(); + + section.setTitleBarBackground(new Color(LIGHT_TITLE.getRGB())); + section.setBackground(new Color(BODY.getRGB())); + + assertSame(before, section.getBackgroundImage()); + } + + @Test + public void testBackgroundChangeDropsHeaderImage() { + paintedHeaderImage(); + + section.setBackground(DARK_TITLE); + + assertNull(section.getBackgroundImage()); + } + + private Image paintedHeaderImage() { + Image target = new Image(section.getDisplay(), 200, 100); + GC gc = new GC(target); + try { + Event event = new Event(); + event.gc = gc; + section.notifyListeners(SWT.Paint, event); + } finally { + gc.dispose(); + target.dispose(); + } + Image headerImage = section.getBackgroundImage(); + assertNotNull(headerImage); + return headerImage; + } +} From 88070a91dbbcad7a6a406e53da24ee861ea58458 Mon Sep 17 00:00:00 2001 From: Deepika Udayagiri Date: Wed, 7 Oct 2026 12:40:22 +0530 Subject: [PATCH 32/52] Show pinned editors first in chevron and Ctrl+E when enabled --- .../renderers/swt/BasicPartList.java | 15 +- .../renderers/swt/PinnedEditorsOrder.java | 80 ++++++++++ .../renderers/swt/CTabRendering.java | 13 +- .../ide/dialogs/IDEEditorsPreferencePage.java | 3 +- .../ui/internal/WorkbenchMessages.java | 4 +- .../ui/internal/WorkbookEditorsHandler.java | 11 +- .../dialogs/EditorsPreferencePage.java | 30 +++- .../eclipse/ui/internal/messages.properties | 4 +- .../internal/WorkbookEditorsHandlerTest.java | 140 ++++++++++++++++-- 9 files changed, 280 insertions(+), 20 deletions(-) create mode 100644 bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/PinnedEditorsOrder.java diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/BasicPartList.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/BasicPartList.java index 63f57378ec1..fec6560a543 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/BasicPartList.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/BasicPartList.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -122,10 +122,15 @@ public BasicPartList(Shell parent, int shellStyle, int treeStyler, this.renderer = renderer; // this.saveHandler = saveHandler; if (mru && getTableViewer() != null) { + boolean pinnedFirst = shouldShowPinnedEditorsFirst(); getTableViewer().setComparator(new ViewerComparator() { @Override public int category(Object element) { if (element instanceof MPart part) { + if (pinnedFirst && PinnedEditorsOrder.isPinned(part)) { + // pinned editors form one block above all others + return -2; + } CTabItem item = BasicPartList.this.renderer.findItemForPart(part); if (item != null && !item.isShowing()) { return -1; @@ -170,9 +175,17 @@ private List getInput() { list.add(element); } } + if (PartStackUtil.isEditorStack(input)) { + return PinnedEditorsOrder.pinnedFirst(list, + element -> element instanceof MPart part && PinnedEditorsOrder.isPinned(part)); + } return list; } + private boolean shouldShowPinnedEditorsFirst() { + return PartStackUtil.isEditorStack(input) && PinnedEditorsOrder.isEnabled(); + } + public void setInput() { getTableViewer().setInput(getInput()); selectFirstMatch(); diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/PinnedEditorsOrder.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/PinnedEditorsOrder.java new file mode 100644 index 00000000000..f4b58eb5e9b --- /dev/null +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/internal/workbench/renderers/swt/PinnedEditorsOrder.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.e4.ui.internal.workbench.renderers.swt; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import org.eclipse.core.runtime.Platform; +import org.eclipse.e4.ui.model.application.ui.basic.MPart; +import org.eclipse.e4.ui.workbench.IPresentationEngine; +import org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering; + +/** + * Single place for the "show pinned editors first" behavior of the editor + * drop-down lists (chevron list and Ctrl+E). The preference only affects the + * order of these lists, tabs are never moved. + */ +public final class PinnedEditorsOrder { + + private PinnedEditorsOrder() { + // utility class + } + + /** + * @return whether pinned editors should be listed before the other editors + */ + public static boolean isEnabled() { + return Platform.getPreferencesService().getBoolean( + CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT, + CTabRendering.SHOW_PINNED_EDITORS_FIRST, + CTabRendering.SHOW_PINNED_EDITORS_FIRST_DEFAULT, + null); + } + + /** + * @return whether the given part is pinned + */ + public static boolean isPinned(MPart part) { + return part.getTags().contains(IPresentationEngine.ADORNMENT_PIN); + } + + /** + * Returns the given elements with the pinned ones first. The relative order + * inside the pinned and inside the other elements is preserved. If the + * preference is disabled, the elements are returned unchanged. + * + * @param elements the elements in their regular order + * @param isPinned tells whether an element is pinned + * @return a list with the pinned elements first + */ + public static List pinnedFirst(List elements, Predicate isPinned) { + if (!isEnabled()) { + return elements; + } + List result = new ArrayList<>(elements.size()); + for (T element : elements) { + if (isPinned.test(element)) { + result.add(element); + } + } + for (T element : elements) { + if (!isPinned.test(element)) { + result.add(element); + } + } + return result; + } +} diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/CTabRendering.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/CTabRendering.java index 9f11ab0bb5c..9b31c64a5b5 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/CTabRendering.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/CTabRendering.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2020 IBM Corporation and others. + * Copyright (c) 2010, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -91,6 +91,17 @@ public class CTabRendering extends CTabFolderRenderer implements ICTabRendering, */ public static final boolean SHOW_DIRTY_INDICATOR_ON_TABS_DEFAULT = true; + /** + * A named preference for whether pinned editors are listed first in the editor + * chevron list and in the editor quick switch list (Ctrl+E). + */ + public static final String SHOW_PINNED_EDITORS_FIRST = "SHOW_PINNED_EDITORS_FIRST"; //$NON-NLS-1$ + + /** + * Default value for "show pinned editors first" preference + */ + public static final boolean SHOW_PINNED_EDITORS_FIRST_DEFAULT = false; + private static int MIN_VIEW_CHARS = 1; private static int MAX_VIEW_CHARS = Integer.MAX_VALUE; diff --git a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/dialogs/IDEEditorsPreferencePage.java b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/dialogs/IDEEditorsPreferencePage.java index 13d631e8276..d5f7525f3f9 100644 --- a/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/dialogs/IDEEditorsPreferencePage.java +++ b/bundles/org.eclipse.ui.ide/src/org/eclipse/ui/internal/ide/dialogs/IDEEditorsPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -61,6 +61,7 @@ protected Control createContents(Composite parent) { createAllowInplaceEditorPref(composite); createUseIPersistablePref(composite); createPromptWhenStillOpenPref(composite); + createShowPinnedEditorsFirstPref(composite); createEditorReuseGroup(composite); createAlignMultiPageEditorTabs(composite); diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java index e92931653d2..bd8006a2fbd 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2020 IBM Corporation and others. + * Copyright (c) 2005, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -472,6 +472,8 @@ public class WorkbenchMessages extends NLS { public static String WorkbenchPreference_allowInplaceEditingButton; public static String WorkbenchPreference_useIPersistableEditorButton; public static String WorkbenchPreference_promptWhenStillOpenButton; + public static String WorkbenchPreference_showPinnedEditorsFirstButton; + public static String WorkbenchPreference_showPinnedEditorsFirstStoreError; public static String WorkbenchPreference_stickyCycleButton; public static String WorkbenchPreference_RunInBackgroundButton; public static String WorkbenchPreference_RunInBackgroundToolTip; diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbookEditorsHandler.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbookEditorsHandler.java index dbb4d2f7bb3..08705d89273 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbookEditorsHandler.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbookEditorsHandler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2019 IBM Corporation and others. + * Copyright (c) 2007, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -33,6 +33,7 @@ import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.e4.ui.internal.workbench.renderers.swt.DirtyIndicatorPainter; +import org.eclipse.e4.ui.internal.workbench.renderers.swt.PinnedEditorsOrder; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering; import org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer; @@ -117,7 +118,7 @@ private List getParts(WorkbenchPage page) { refs.add((EditorReference) ier); } } - return refs; + return PinnedEditorsOrder.pinnedFirst(refs, EditorReference::isPinned); } /** @@ -483,12 +484,12 @@ protected ParameterizedCommand getForwardCommand() { @Override protected int getCurrentItemIndex() { - if (isMruEnabled()) { + if (isMruEnabled() && !PinnedEditorsOrder.isEnabled()) { return 0; } // We need to find previously selected part and return the index of the - // part before this part in our list, which ordered not by use but by - // position + // part before this part in our list, which is not ordered purely by use + // (positional order, or pinned editors moved to the top) WorkbenchPage page = (WorkbenchPage) window.getActivePage(); List sortedByUse = page.getSortedEditorReferences(); diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/EditorsPreferencePage.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/EditorsPreferencePage.java index 1aca9a93217..197f8b4b404 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/EditorsPreferencePage.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/EditorsPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -18,6 +18,11 @@ import static org.eclipse.swt.events.SelectionListener.widgetSelectedAdapter; +import org.eclipse.core.runtime.preferences.DefaultScope; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; +import org.eclipse.e4.ui.internal.workbench.renderers.swt.PinnedEditorsOrder; +import org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering; import org.eclipse.jface.action.Action; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; @@ -46,6 +51,7 @@ import org.eclipse.ui.internal.WorkbenchMessages; import org.eclipse.ui.internal.WorkbenchPlugin; import org.eclipse.ui.internal.util.PrefUtil; +import org.osgi.service.prefs.BackingStoreException; /** * The Editors preference page of the workbench. @@ -74,6 +80,8 @@ public class EditorsPreferencePage extends PreferencePage implements IWorkbenchP private Button promptWhenStillOpenEditor; + private Button showPinnedEditorsFirst; + private Button allowInplaceEditor; private ComboFieldEditor multiPageEditorTabPositionComboField; @@ -88,6 +96,7 @@ protected Control createContents(Composite parent) { createAllowInplaceEditorPref(composite); createUseIPersistablePref(composite); createPromptWhenStillOpenPref(composite); + createShowPinnedEditorsFirstPref(composite); createEditorReuseGroup(composite); // ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).setPreferenceVisibility(editorReuseGroup, // showMultipleEditorTabs); @@ -136,6 +145,13 @@ protected void createPromptWhenStillOpenPref(Composite composite) { setButtonLayoutData(promptWhenStillOpenEditor); } + protected void createShowPinnedEditorsFirstPref(Composite composite) { + showPinnedEditorsFirst = new Button(composite, SWT.CHECK); + showPinnedEditorsFirst.setText(WorkbenchMessages.WorkbenchPreference_showPinnedEditorsFirstButton); + showPinnedEditorsFirst.setSelection(PinnedEditorsOrder.isEnabled()); + setButtonLayoutData(showPinnedEditorsFirst); + } + protected void createAlignMultiPageEditorTabs(Composite parent) { Composite comboComposite = new Composite(parent, SWT.NONE); comboComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).create()); @@ -176,6 +192,9 @@ protected void performDefaults() { useIPersistableEditor.setSelection(store.getDefaultBoolean(IPreferenceConstants.USE_IPERSISTABLE_EDITORS)); promptWhenStillOpenEditor.setSelection(getAPIPreferenceStore() .getDefaultBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN)); + showPinnedEditorsFirst.setSelection(DefaultScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT) + .getBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, CTabRendering.SHOW_PINNED_EDITORS_FIRST_DEFAULT)); reuseEditors.setSelection(store.getDefaultBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN)); reuseEditorsThreshold.loadDefault(); reuseEditorsThreshold.getLabelControl(editorReuseThresholdGroup).setEnabled(reuseEditors.getSelection()); @@ -194,6 +213,15 @@ public boolean performOk() { getAPIPreferenceStore().setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, promptWhenStillOpenEditor.getSelection()); + IEclipsePreferences renderersPrefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + renderersPrefs.putBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, showPinnedEditorsFirst.getSelection()); + try { + renderersPrefs.flush(); + } catch (BackingStoreException e) { + WorkbenchPlugin.log(WorkbenchMessages.WorkbenchPreference_showPinnedEditorsFirstStoreError, e); + } + // store the reuse editors setting store.setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, reuseEditors.getSelection()); reuseEditorsThreshold.store(); diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties index c1c3b2bdc7c..2fa44773e17 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/messages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2020 IBM Corporation and others. +# Copyright (c) 2000, 2026 IBM Corporation and others. # # This program and the accompanying materials # are made available under the terms of the Eclipse Public License 2.0 @@ -414,6 +414,8 @@ PreferenceExportWarning_applyAndContinue = &Apply and Continue WorkbenchPreference_allowInplaceEditingButton = Allow in-place &system editors WorkbenchPreference_useIPersistableEditorButton = Restore &editor state on startup WorkbenchPreference_promptWhenStillOpenButton = Pr&ompt to save on close even if still open elsewhere +WorkbenchPreference_showPinnedEditorsFirstButton = Show &pinned editors first in editor lists (chevron and Ctrl+E) +WorkbenchPreference_showPinnedEditorsFirstStoreError = Failed to store the preference to show pinned editors first. WorkbenchPreference_stickyCycleButton = Keep &next/previous editor, view and perspectives dialog open WorkbenchPreference_RunInBackgroundButton=Always r&un in background WorkbenchPreference_RunInBackgroundToolTip=Run long operations in the background where possible diff --git a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/internal/WorkbookEditorsHandlerTest.java b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/internal/WorkbookEditorsHandlerTest.java index 22bad7811ad..608d9f58d52 100644 --- a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/internal/WorkbookEditorsHandlerTest.java +++ b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/internal/WorkbookEditorsHandlerTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2022 vogella GmbH. + * Copyright (c) 2022, 2026 vogella GmbH. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -10,6 +10,7 @@ * * Contributors: * Fabian Pfaff (vogella GmbH) - initial API and implementation + * IBM Corporation - pinned editors first in chevron list and Ctrl+E ******************************************************************************/ package org.eclipse.ui.tests.internal; @@ -26,16 +27,23 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; +import org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering; +import org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; +import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.internal.WorkbenchPage; +import org.eclipse.ui.internal.WorkbenchPartReference; import org.eclipse.ui.internal.WorkbookEditorsHandler; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.tests.harness.util.CloseTestWindowsRule; @@ -68,15 +76,25 @@ public final void setUp() throws CoreException { @After public final void tearDown() throws Exception { - if (project1 != null) { - project1.delete(true, true, null); - project1 = null; - } - if (project2 != null) { - project2.delete(true, true, null); - project2 = null; + try { + if (project1 != null) { + project1.delete(true, true, null); + project1 = null; + } + if (project2 != null) { + project2.delete(true, true, null); + project2 = null; + } + if (activePage != null) { + activePage.closeAllEditors(false); + } + } finally { + IEclipsePreferences renderersPrefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + renderersPrefs.remove(CTabRendering.SHOW_PINNED_EDITORS_FIRST); + renderersPrefs.remove(StackRenderer.MRU_KEY); + renderersPrefs.flush(); } - activePage.closeAllEditors(false); } @Test @@ -372,6 +390,110 @@ public String getName() { assertEquals("Display text should match name of editor input", editorInputName, handler.tableItemTexts.get(1)); } + @Test + public void testShowPinnedEditorsFirstPreference() throws Exception { + String file1Name = "file1.txt"; + String file2Name = "file2.txt"; + String file3Name = "file3.txt"; + String file4Name = "file4.txt"; + IDE.openEditor(activePage, FileUtil.createFile(file1Name, project1), true); + IEditorPart editor2 = IDE.openEditor(activePage, FileUtil.createFile(file2Name, project1), true); + IDE.openEditor(activePage, FileUtil.createFile(file3Name, project1), true); + IEditorPart editor4 = IDE.openEditor(activePage, FileUtil.createFile(file4Name, project1), true); + + // Pin editors 2 and 4 + WorkbenchPartReference ref2 = (WorkbenchPartReference) ((WorkbenchPage) activePage).getReference(editor2); + ref2.setPinned(true); + WorkbenchPartReference ref4 = (WorkbenchPartReference) ((WorkbenchPage) activePage).getReference(editor4); + ref4.setPinned(true); + + ICommandService cmdService = PlatformUI.getWorkbench().getService(ICommandService.class); + final Command cmd = cmdService.getCommand("org.eclipse.ui.window.openEditorDropDown"); + IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); + + IEclipsePreferences renderersPrefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + + // 1. In default MRU mode when preference is disabled (false): + // Expects standard MRU activation history order: [file4.txt, file3.txt, file2.txt, file1.txt] + renderersPrefs.putBoolean(StackRenderer.MRU_KEY, true); + renderersPrefs.putBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, false); + WorkbookEditorsHandlerTestable handlerMruDisabled = new WorkbookEditorsHandlerTestable(); + cmd.setHandler(handlerMruDisabled); + handlerMruDisabled.execute(handlerService.createExecutionEvent(cmd, null)); + assertEquals(List.of(file4Name, file3Name, file2Name, file1Name), handlerMruDisabled.tableItemTexts); + + // When preference is enabled (true) in MRU mode: + // Pinned editors first in MRU order (file4, file2), followed by unpinned in MRU order (file3, file1) + renderersPrefs.putBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, true); + WorkbookEditorsHandlerTestable handlerMruEnabled = new WorkbookEditorsHandlerTestable(); + cmd.setHandler(handlerMruEnabled); + handlerMruEnabled.execute(handlerService.createExecutionEvent(cmd, null)); + assertEquals(List.of(file4Name, file2Name, file3Name, file1Name), handlerMruEnabled.tableItemTexts); + + // 2. In non-MRU (tab index) mode when preference is disabled (false): + // Expects standard tab index order: [file1.txt, file2.txt, file3.txt, file4.txt] + renderersPrefs.putBoolean(StackRenderer.MRU_KEY, false); + renderersPrefs.putBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, false); + WorkbookEditorsHandlerTestable handlerNonMruDisabled = new WorkbookEditorsHandlerTestable(); + cmd.setHandler(handlerNonMruDisabled); + handlerNonMruDisabled.execute(handlerService.createExecutionEvent(cmd, null)); + assertEquals(List.of(file1Name, file2Name, file3Name, file4Name), handlerNonMruDisabled.tableItemTexts); + + // When preference is enabled (true) in non-MRU mode: + // Pinned editors first in screen tab order (file2, file4), followed by unpinned in screen tab order (file1, file3) + renderersPrefs.putBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, true); + WorkbookEditorsHandlerTestable handlerNonMruEnabled = new WorkbookEditorsHandlerTestable(); + cmd.setHandler(handlerNonMruEnabled); + handlerNonMruEnabled.execute(handlerService.createExecutionEvent(cmd, null)); + assertEquals(List.of(file2Name, file4Name, file1Name, file3Name), handlerNonMruEnabled.tableItemTexts); + } + + @Test + public void testShowPinnedEditorsFirstPreselectsPreviouslyUsedEditorInMruMode() throws Exception { + String file1Name = "file1.txt"; + String file2Name = "file2.txt"; + String file3Name = "file3.txt"; + String file4Name = "file4.txt"; + IDE.openEditor(activePage, FileUtil.createFile(file1Name, project1), true); + IEditorPart editor2 = IDE.openEditor(activePage, FileUtil.createFile(file2Name, project1), true); + IEditorPart editor3 = IDE.openEditor(activePage, FileUtil.createFile(file3Name, project1), true); + IEditorPart editor4 = IDE.openEditor(activePage, FileUtil.createFile(file4Name, project1), true); + + WorkbenchPartReference ref2 = (WorkbenchPartReference) ((WorkbenchPage) activePage).getReference(editor2); + WorkbenchPartReference ref3 = (WorkbenchPartReference) ((WorkbenchPage) activePage).getReference(editor3); + WorkbenchPartReference ref4 = (WorkbenchPartReference) ((WorkbenchPage) activePage).getReference(editor4); + + ICommandService cmdService = PlatformUI.getWorkbench().getService(ICommandService.class); + final Command cmd = cmdService.getCommand("org.eclipse.ui.window.openEditorDropDown"); + IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); + + IEclipsePreferences renderersPrefs = InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); + renderersPrefs.putBoolean(StackRenderer.MRU_KEY, true); + renderersPrefs.putBoolean(CTabRendering.SHOW_PINNED_EDITORS_FIRST, true); + + // MRU order is file4, file3, file2, file1. With file2 and file4 pinned the list + // is file4, file2, file3, file1. The previously used editor (file3) is no + // longer at index 1 and must still be the preselected one. + ref2.setPinned(true); + ref4.setPinned(true); + WorkbookEditorsHandlerTestable handler = new WorkbookEditorsHandlerTestable(); + cmd.setHandler(handler); + handler.execute(handlerService.createExecutionEvent(cmd, null)); + assertEquals(List.of(file4Name, file2Name, file3Name, file1Name), handler.tableItemTexts); + assertEquals(List.of(file3Name), handler.selectionTexts); + + // Previously used editor (file3) is pinned and therefore the first entry. + ref4.setPinned(false); + ref3.setPinned(true); + WorkbookEditorsHandlerTestable handlerFirstEntry = new WorkbookEditorsHandlerTestable(); + cmd.setHandler(handlerFirstEntry); + handlerFirstEntry.execute(handlerService.createExecutionEvent(cmd, null)); + assertEquals(List.of(file3Name, file2Name, file4Name, file1Name), handlerFirstEntry.tableItemTexts); + assertEquals(List.of(file3Name), handlerFirstEntry.selectionTexts); + } + class WorkbookEditorsHandlerTestable extends WorkbookEditorsHandler { List selectionTexts; List tableItemTexts; From 6612d0418adbdc1125941abb268f8c242c3340e2 Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Thu, 15 Oct 2026 00:47:24 +0200 Subject: [PATCH 33/52] Set the SVG currentColor from the CSS theme at startup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SVG icons using fill="currentColor" are always rasterized black, which makes them unreadable in the dark theme. The new Shell property swt-svg-current-color passes the theme color to SWT once per session, before the workbench window contents are rasterized, so currentColor icons in workbench window contents follow the theme without per-theme icon copies. Product window icons are initialized before theme application and are outside the scope of this startup recoloring. A theme switch freezes the color, also when the starting theme did not set one, so cached and new rasterizations never mix colors before the restart. An explicit swt.svg.currentColor system property still takes precedence. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../META-INF/MANIFEST.MF | 2 +- .../css/swt/internal/theme/ThemeEngine.java | 5 ++ .../META-INF/MANIFEST.MF | 4 +- bundles/org.eclipse.e4.ui.css.swt/plugin.xml | 8 ++ .../CSSPropertySVGCurrentColorHandler.java | 75 +++++++++++++++++++ .../css/dark/e4-dark_globalstyle.css | 5 ++ docs/CSS.md | 14 ++++ .../e4/ui/tests/css/swt/ShellTest.java | 37 +++++++++ .../e4/ui/tests/css/swt/ThemeTest.java | 54 +++++++++++++ 9 files changed, 201 insertions(+), 3 deletions(-) create mode 100644 bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/properties/custom/CSSPropertySVGCurrentColorHandler.java diff --git a/bundles/org.eclipse.e4.ui.css.swt.theme/META-INF/MANIFEST.MF b/bundles/org.eclipse.e4.ui.css.swt.theme/META-INF/MANIFEST.MF index 1547907bae8..245709b5aa3 100644 --- a/bundles/org.eclipse.e4.ui.css.swt.theme/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.e4.ui.css.swt.theme/META-INF/MANIFEST.MF @@ -7,7 +7,7 @@ Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.swt;bundle-version="[3.134.0,4.0.0)", - org.eclipse.e4.ui.css.swt;bundle-version="0.13.100", + org.eclipse.e4.ui.css.swt;bundle-version="0.17.200", org.eclipse.e4.ui.css.core;bundle-version="0.12.200", org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)" Bundle-ActivationPolicy: lazy diff --git a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java index dfb1ad2cbc4..38cea1c543b 100644 --- a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java +++ b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java @@ -54,6 +54,7 @@ import org.eclipse.e4.ui.css.core.util.impl.resources.OSGiResourceLocator; import org.eclipse.e4.ui.css.core.util.resources.IResourceLocator; import org.eclipse.e4.ui.css.swt.helpers.EclipsePreferencesHelper; +import org.eclipse.e4.ui.css.swt.properties.custom.CSSPropertySVGCurrentColorHandler; import org.eclipse.e4.ui.css.swt.theme.ITheme; import org.eclipse.e4.ui.css.swt.theme.IThemeEngine; import org.eclipse.osgi.service.datalocation.Location; @@ -498,6 +499,10 @@ public void setTheme(ITheme theme, boolean restore, boolean force) { } } + if (currentTheme != null && !currentTheme.getId().equals(theme.getId())) { + // icons already rasterized keep their color, so only a restart may change it + CSSPropertySVGCurrentColorHandler.freeze(); + } this.currentTheme = theme; for (CSSEngine engine : cssEngines) { engine.reset(); diff --git a/bundles/org.eclipse.e4.ui.css.swt/META-INF/MANIFEST.MF b/bundles/org.eclipse.e4.ui.css.swt/META-INF/MANIFEST.MF index a22edab001c..1981122fb00 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.e4.ui.css.swt/META-INF/MANIFEST.MF @@ -23,14 +23,14 @@ Export-Package: org.eclipse.e4.ui.css.swt;x-friends:="org.eclipse.ui.workbench", org.eclipse.e4.ui.css.swt.properties;x-friends:="org.eclipse.ui.workbench,org.eclipse.ui.views.properties.tabbed,org.eclipse.ui.forms", org.eclipse.e4.ui.css.swt.properties.converters;x-internal:=true, org.eclipse.e4.ui.css.swt.properties.css2;x-internal:=true, - org.eclipse.e4.ui.css.swt.properties.custom;x-friends:="org.eclipse.e4.ui.workbench.renderers.swt", + org.eclipse.e4.ui.css.swt.properties.custom;x-friends:="org.eclipse.e4.ui.workbench.renderers.swt,org.eclipse.e4.ui.css.swt.theme", org.eclipse.e4.ui.css.swt.properties.definition;x-internal:=true, org.eclipse.e4.ui.css.swt.properties.preference;x-internal:=true, org.eclipse.e4.ui.css.swt.resources;x-friends:="org.eclipse.e4.ui.workbench.renderers.swt", org.eclipse.e4.ui.internal.css.swt;x-internal:=true, org.eclipse.e4.ui.internal.css.swt.definition;x-friends:="org.eclipse.ui.workbench" Require-Bundle: org.eclipse.e4.ui.css.core;bundle-version="0.12.200", - org.eclipse.swt;bundle-version="[3.133.0,4.0.0)", + org.eclipse.swt;bundle-version="[3.135.100,4.0.0)", org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)" Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-ActivationPolicy: lazy diff --git a/bundles/org.eclipse.e4.ui.css.swt/plugin.xml b/bundles/org.eclipse.e4.ui.css.swt/plugin.xml index d141f7b6f71..e44e256c4d6 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/plugin.xml +++ b/bundles/org.eclipse.e4.ui.css.swt/plugin.xml @@ -87,6 +87,14 @@ name="background-color"> + + + + - initial API and implementation + *******************************************************************************/ +package org.eclipse.e4.ui.css.swt.properties.custom; + +import org.eclipse.e4.ui.css.core.engine.CSSEngine; +import org.eclipse.e4.ui.css.swt.helpers.CSSSWTColorHelper; +import org.eclipse.e4.ui.css.swt.properties.AbstractCSSPropertySWTHandler; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.internal.image.SVGFileFormat; +import org.eclipse.swt.widgets.Control; +import org.w3c.dom.css.CSSValue; + +/** + * Handler for {@code swt-svg-current-color}, the color SVG images use for + * {@code currentColor}. The color is global and applied only once per session, + * so a theme change takes effect after a restart. An explicit + * {@code swt.svg.currentColor} system property takes precedence. + */ +public class CSSPropertySVGCurrentColorHandler extends AbstractCSSPropertySWTHandler { + + private static volatile boolean frozen; + + @Override + protected void applyCSSProperty(Control control, String property, CSSValue value, String pseudo, CSSEngine engine) + throws Exception { + if (frozen || System.getProperty("swt.svg.currentColor") != null) { //$NON-NLS-1$ + return; + } + // a definition registered later must not lock in the black fallback + if (CSSSWTColorHelper.isUnresolvedColorDefinition(value)) { + return; + } + Color color = CSSSWTColorHelper.getSWTColor(value, control.getDisplay()); + if (color != null) { + synchronized (CSSPropertySVGCurrentColorHandler.class) { + if (!frozen) { + frozen = true; + SVGFileFormat.setCurrentColor(color.getRGB()); + } + } + } + } + + /** + * Keeps the current color for the rest of the session, also when the starting + * theme did not declare one. + */ + public static synchronized void freeze() { + frozen = true; + } + + /** + * Allows the color to be applied again, for tests. + */ + public static synchronized void reset() { + frozen = false; + } + + @Override + protected String retrieveCSSProperty(Control control, String property, String pseudo, CSSEngine engine) + throws Exception { + return null; + } +} diff --git a/bundles/org.eclipse.ui.themes/css/dark/e4-dark_globalstyle.css b/bundles/org.eclipse.ui.themes/css/dark/e4-dark_globalstyle.css index ef58edefa73..e12521fa022 100644 --- a/bundles/org.eclipse.ui.themes/css/dark/e4-dark_globalstyle.css +++ b/bundles/org.eclipse.ui.themes/css/dark/e4-dark_globalstyle.css @@ -314,3 +314,8 @@ TabbedPropertyList { swt-tabBackground-color : '#org-eclipse-ui-workbench-ACTIVE_NOFOCUS_TAB_BG_START'; color : '#org-eclipse-ui-workbench-ACTIVE_NOFOCUS_TAB_SELECTED_TEXT_COLOR'; /* text color in the tab / tab area */ } + +/* Color SVG images use for currentColor, applied once at startup */ +Shell { + swt-svg-current-color: #CCCCCC; +} diff --git a/docs/CSS.md b/docs/CSS.md index 5f3e932dec5..1694ea5409b 100644 --- a/docs/CSS.md +++ b/docs/CSS.md @@ -177,6 +177,20 @@ bare number as a size in points. +### Widget: Shell + +| SWT Method | CSS Property Name | CSS Example | +| --- | --- | --- | +| SVGFileFormat.setCurrentColor(RGB) | swt-svg-current-color | Shell { swt-svg-current-color: #CCCCCC; } (Experimental) | + +`swt-svg-current-color` is experimental and may change or be removed in a future release. +It sets the color that SVG images use for `currentColor`. +It is a single process-wide default, applied once at startup, so a theme switch takes effect after a restart. +It does not follow the foreground of the widget showing the image, so an icon drawn on a selected or otherwise colored background keeps this color. +Images created before the theme is applied, such as the product window icons, keep SWT's default black. + + + ### Widget: Button | SWT Method | CSS Property Name | CSS Example | diff --git a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ShellTest.java b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ShellTest.java index 783173760bc..db911517a49 100644 --- a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ShellTest.java +++ b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ShellTest.java @@ -21,9 +21,11 @@ import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.e4.ui.css.swt.dom.WidgetElement; +import org.eclipse.e4.ui.css.swt.properties.custom.CSSPropertySVGCurrentColorHandler; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.internal.image.SVGFileFormat; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; @@ -67,6 +69,41 @@ void testColor() { assertEquals(BLUE, shellToTest.getForeground().getRGB()); } + @Test + void testSvgCurrentColorAppliedOnce() { + CSSPropertySVGCurrentColorHandler.reset(); + try { + createTestShell("Shell { swt-svg-current-color: '#org-eclipse-unknown-COLOR' }"); + createTestShell("Shell { swt-svg-current-color: #0000FF }"); + assertEquals(BLUE, SVGFileFormat.getCurrentColor()); + + createTestShell("Shell { swt-svg-current-color: #FF0000 }"); + assertEquals(BLUE, SVGFileFormat.getCurrentColor()); + } finally { + CSSPropertySVGCurrentColorHandler.reset(); + SVGFileFormat.setCurrentColor(null); + } + } + + @Test + void testSvgCurrentColorSystemPropertyWins() { + RGB initialColor = SVGFileFormat.getCurrentColor(); + CSSPropertySVGCurrentColorHandler.reset(); + String previous = System.setProperty("swt.svg.currentColor", "#00FF00"); + try { + createTestShell("Shell { swt-svg-current-color: #0000FF }"); + assertEquals(initialColor, SVGFileFormat.getCurrentColor()); + } finally { + if (previous == null) { + System.clearProperty("swt.svg.currentColor"); + } else { + System.setProperty("swt.svg.currentColor", previous); + } + CSSPropertySVGCurrentColorHandler.reset(); + SVGFileFormat.setCurrentColor(null); + } + } + @Test void testFontRegular() { Shell shellToTest = createTestShell("Shell { font: Verdana 16pt }"); diff --git a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java index e661344047f..d7114e581b1 100644 --- a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java +++ b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java @@ -32,12 +32,17 @@ import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.core.runtime.preferences.UserScope; +import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.e4.ui.css.swt.internal.theme.Theme; import org.eclipse.e4.ui.css.swt.internal.theme.ThemeEngine; +import org.eclipse.e4.ui.css.swt.properties.custom.CSSPropertySVGCurrentColorHandler; import org.eclipse.e4.ui.css.swt.theme.ITheme; import org.eclipse.e4.ui.css.swt.theme.IThemeEngine; import org.eclipse.e4.ui.css.swt.theme.IThemeManager; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.internal.image.SVGFileFormat; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -110,6 +115,55 @@ void testThemeChangeNotification() { assertTrue(success[0]); } + @Test + void testSvgCurrentColorFrozenByThemeSwitch() { + IThemeEngine themer = getThemeEngine(Display.getDefault()); + ITheme previousTheme = themer.getActiveTheme(); + RGB initialColor = SVGFileFormat.getCurrentColor(); + CSSPropertySVGCurrentColorHandler.reset(); + Shell shell = new Shell(css.getDisplay()); + try { + // neither theme sets a color, so one applied after the switch must be ignored + themer.setTheme(new Theme("svg.first", "First"), false); + themer.setTheme(new Theme("svg.second", "Second"), false); + CSSEngine engine = css.createEngine("Shell { swt-svg-current-color: #0000FF }"); + engine.applyStyles(shell, true); + + assertEquals(initialColor, SVGFileFormat.getCurrentColor()); + } finally { + shell.dispose(); + if (previousTheme != null) { + themer.setTheme(previousTheme, false); + } + CSSPropertySVGCurrentColorHandler.reset(); + SVGFileFormat.setCurrentColor(null); + } + } + + @Test + void testSvgCurrentColorNotFrozenByThemeReapply() { + ThemeEngine themer = (ThemeEngine) getThemeEngine(Display.getDefault()); + ITheme previousTheme = themer.getActiveTheme(); + Shell shell = new Shell(css.getDisplay()); + try { + Theme theme = new Theme("svg.same", "Same"); + themer.setTheme(theme, false); + CSSPropertySVGCurrentColorHandler.reset(); + themer.setTheme(theme, false, true); + CSSEngine engine = css.createEngine("Shell { swt-svg-current-color: #0000FF }"); + engine.applyStyles(shell, true); + + assertEquals(new RGB(0, 0, 255), SVGFileFormat.getCurrentColor()); + } finally { + shell.dispose(); + if (previousTheme != null) { + themer.setTheme(previousTheme, false); + } + CSSPropertySVGCurrentColorHandler.reset(); + SVGFileFormat.setCurrentColor(null); + } + } + @Test void testInheritedThemeIsReadableFromPreferenceService() { IThemeEngine themer = getThemeEngine(Display.getDefault()); From 5702c8a0bec0c9f70036820834dbd63500e78681 Mon Sep 17 00:00:00 2001 From: Philipp SALZGEBER Date: Wed, 21 Oct 2026 17:23:30 +0200 Subject: [PATCH 34/52] Sort by the undecorated label of styled decorating label providers ViewerComparator.getLabel unwraps a DecoratingLabelProvider (Bug 364735) but sorts by the decorated text of a DecoratingStyledCellLabelProvider, the label provider of every CommonViewer. Decorations are computed in a background job and may change the label while a sort runs, which violates the comparator contract and lets TimSort throw "Comparison method violates its general contract". Fixes #4516 Signed-off-by: Philipp SALZGEBER --- .../jface/viewers/ViewerComparator.java | 12 +- .../jface/tests/viewers/AllViewersTests.java | 2 +- .../ViewerComparatorDecoratedLabelTest.java | 161 ++++++++++++++++++ 3 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/ViewerComparatorDecoratedLabelTest.java diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/ViewerComparator.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/ViewerComparator.java index 81d739c8f69..939b99fa852 100644 --- a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/ViewerComparator.java +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/ViewerComparator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2016 IBM Corporation and others. + * Copyright (c) 2006, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -12,6 +12,7 @@ * IBM Corporation - initial API and implementation * Lars Vogel - Bug 430873 * Andrey Loskutov - Bug 364735 + * Philipp Salzgeber (Bachmann electronic GmbH) - Issue #4516 ******************************************************************************/ package org.eclipse.jface.viewers; @@ -146,7 +147,14 @@ private String getLabel(Viewer viewer, Object e1) { } else { IBaseLabelProvider prov = ((ContentViewer) viewer) .getLabelProvider(); - if (prov instanceof ILabelProvider lprov) { + if (prov instanceof DelegatingStyledCellLabelProvider delegating) { + // Issue #4516: like the DecoratingLabelProvider case below, use + // the styled string provider to avoid the decorations of a + // DecoratingStyledCellLabelProvider, which the Common Navigator + // uses. + StyledString text = delegating.getStyledStringProvider().getStyledText(e1); + name1 = text == null ? null : text.getString(); + } else if (prov instanceof ILabelProvider lprov) { if (lprov instanceof DecoratingLabelProvider dprov) { // Bug 364735: use the real label provider to avoid unstable // sort behavior if the decoration is running while sorting. diff --git a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/AllViewersTests.java b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/AllViewersTests.java index 0b9b8a39c36..3819c2dd2f5 100644 --- a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/AllViewersTests.java +++ b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/AllViewersTests.java @@ -33,7 +33,7 @@ EditingSupportValueMismatchTest.class, StyledStringBuilderTest.class, TreeViewerWithLimitTest.class, TreeViewerWithLimitCompatibilityTest.class, TableViewerWithLimitTest.class, TableViewerWithLimitCompatibilityTest.class, TreeViewerExpansionStateTest.class, - StructuredViewerElementMapTest.class }) + StructuredViewerElementMapTest.class, ViewerComparatorDecoratedLabelTest.class }) public class AllViewersTests { } diff --git a/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/ViewerComparatorDecoratedLabelTest.java b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/ViewerComparatorDecoratedLabelTest.java new file mode 100644 index 00000000000..3b6e7968523 --- /dev/null +++ b/tests/org.eclipse.jface.tests/src/org/eclipse/jface/tests/viewers/ViewerComparatorDecoratedLabelTest.java @@ -0,0 +1,161 @@ +/******************************************************************************* + * Copyright (c) 2026 Bachmann electronic GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Philipp Salzgeber (Bachmann electronic GmbH) - initial API and implementation, Issue #4516 + *******************************************************************************/ +package org.eclipse.jface.tests.viewers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.eclipse.jface.viewers.ContentViewer; +import org.eclipse.jface.viewers.DecoratingLabelProvider; +import org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider; +import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; +import org.eclipse.jface.viewers.IDecorationContext; +import org.eclipse.jface.viewers.ILabelDecorator; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.LabelDecorator; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.StyledString; +import org.eclipse.jface.viewers.ViewerComparator; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Control; +import org.junit.jupiter.api.Test; + +/** + * Decorations are computed in a background job and may change the decorated + * label while a sort runs, so {@link ViewerComparator} must sort by the + * undecorated label (Bug 364735, Issue #4516). + */ +public class ViewerComparatorDecoratedLabelTest { + + /** + * Decorates like a SCM decorator: the element "b" gets a dirty prefix that + * sorts before letters, "a" stays undecorated. + */ + private static final class PrefixDecorator extends LabelDecorator { + @Override + public String decorateText(String text, Object element) { + return "b".equals(element) ? "> " + text + " [branch]" : text; + } + + @Override + public String decorateText(String text, Object element, IDecorationContext context) { + return decorateText(text, element); + } + + @Override + public Image decorateImage(Image image, Object element) { + return image; + } + + @Override + public Image decorateImage(Image image, Object element, IDecorationContext context) { + return image; + } + + @Override + public boolean prepareDecoration(Object element, String originalText, IDecorationContext context) { + return true; + } + + @Override + public void addListener(ILabelProviderListener listener) { + } + + @Override + public void dispose() { + } + + @Override + public boolean isLabelProperty(Object element, String property) { + return false; + } + + @Override + public void removeListener(ILabelProviderListener listener) { + } + } + + private static final class StyledLabelProvider extends LabelProvider implements IStyledLabelProvider { + @Override + public StyledString getStyledText(Object element) { + return new StyledString(String.valueOf(element)); + } + } + + /** + * Shaped like the Common Navigator's label provider: a styled decorating + * provider that is also an {@link ILabelProvider} returning the decorated + * text. + */ + private static final class NavigatorLikeLabelProvider extends DecoratingStyledCellLabelProvider + implements ILabelProvider { + NavigatorLikeLabelProvider(IStyledLabelProvider labelProvider, ILabelDecorator decorator) { + super(labelProvider, decorator, null); + } + + @Override + public String getText(Object element) { + return getStyledText(element).getString(); + } + + @Override + public Image getImage(Object element) { + return null; + } + } + + /** A content viewer without widgets; only its label provider matters here. */ + private static final class LabelProviderViewer extends ContentViewer { + @Override + public Control getControl() { + return null; + } + + @Override + public ISelection getSelection() { + return null; + } + + @Override + public void refresh() { + } + + @Override + public void setSelection(ISelection selection, boolean reveal) { + } + } + + private final ViewerComparator comparator = new ViewerComparator(); + + @Test + public void styledDecorationsAreIgnoredWhenSorting() { + LabelProviderViewer viewer = new LabelProviderViewer(); + viewer.setLabelProvider(new NavigatorLikeLabelProvider(new StyledLabelProvider(), new PrefixDecorator())); + + assertTrue(comparator.compare(viewer, "b", "a") > 0, + "b must sort after a although its decorated label starts with '>'"); + assertEquals(0, comparator.compare(viewer, "a", "a")); + } + + @Test + public void plainDecorationsAreIgnoredWhenSorting() { + LabelProviderViewer viewer = new LabelProviderViewer(); + viewer.setLabelProvider(new DecoratingLabelProvider(new LabelProvider(), new PrefixDecorator())); + + assertTrue(comparator.compare(viewer, "b", "a") > 0, + "b must sort after a although its decorated label starts with '>'"); + } +} From 2bc9e8b348c992037c108e824fec2cb0fe11113b Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Fri, 6 Nov 2026 10:50:53 +0100 Subject: [PATCH 35/52] Recompute indent folding regions when folding is re-enabled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Turning folding off and on again in the Generic Editor left the folding ruler empty until the next edit, because IndentFoldingStrategy only picked up the new, empty annotation model. It now reconciles right away. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../genericeditor/folding/IndentFoldingStrategy.java | 4 ++++ .../eclipse/ui/genericeditor/tests/FoldingTest.java | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/bundles/org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/folding/IndentFoldingStrategy.java b/bundles/org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/folding/IndentFoldingStrategy.java index fcce730427a..d2ded1bfc47 100644 --- a/bundles/org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/folding/IndentFoldingStrategy.java +++ b/bundles/org.eclipse.ui.genericeditor/src/org/eclipse/ui/internal/genericeditor/folding/IndentFoldingStrategy.java @@ -156,6 +156,10 @@ public void projectionDisabled() { public void projectionEnabled() { if (viewer != null) { projectionAnnotationModel = viewer.getProjectionAnnotationModel(); + // the new annotation model starts empty + if (document != null) { + initialReconcile(); + } } } diff --git a/tests/org.eclipse.ui.genericeditor.tests/src/org/eclipse/ui/genericeditor/tests/FoldingTest.java b/tests/org.eclipse.ui.genericeditor.tests/src/org/eclipse/ui/genericeditor/tests/FoldingTest.java index 155870af5ed..2f28ac23fb5 100644 --- a/tests/org.eclipse.ui.genericeditor.tests/src/org/eclipse/ui/genericeditor/tests/FoldingTest.java +++ b/tests/org.eclipse.ui.genericeditor.tests/src/org/eclipse/ui/genericeditor/tests/FoldingTest.java @@ -116,4 +116,15 @@ public void testFoldingCommandsEnabled() throws Exception { Command collapseAllCommand = commandService.getCommand(IFoldingCommandIds.FOLDING_COLLAPSE_ALL); assertTrue(collapseAllCommand.isEnabled() && collapseAllCommand.isHandled()); } + + @Test + public void testFoldingRestoredWhenReenabled() throws Exception { + createAndOpenFile("bar.xml", "\n b"); + assertFoldingAsync(pos(0, 10)); + ProjectionViewer viewer = (ProjectionViewer) editor.getAdapter(ITextViewer.class); + viewer.doOperation(ProjectionViewer.TOGGLE); + viewer.doOperation(ProjectionViewer.TOGGLE); + assertTrue(DisplayHelper.waitForCondition(editor.getSite().getShell().getDisplay(), 5000, + () -> !getAnnotationsFromAnnotationModel().isEmpty())); + } } From e80a3e927cb70bd8ad7c86827b4bad3e053ca89c Mon Sep 17 00:00:00 2001 From: Florian Schwabe Date: Fri, 16 Oct 2026 17:04:53 +0200 Subject: [PATCH 36/52] CodeMinings: Add support for rendering placeholder while resolving #3723 Codemining implementations can now opt-in to rendering placeholder text to prevent editor jumping. The IPlaceholderCodeMining interface must be implemented and getPlaceholderLabel() should return a non-empty string. If no label is set and there is no last resolved mining, the placeholder text will be shown while the resolve() Future is still running. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/3723 --- .../CodeMiningDocumentFooterAnnotation.java | 15 +- .../text/codemining/CodeMiningDrawHelper.java | 139 +++++++++++ .../CodeMiningLineContentAnnotation.java | 43 +--- .../CodeMiningLineHeaderAnnotation.java | 74 ++---- .../text/codemining/CodeMiningManager.java | 58 +++-- .../internal/text/codemining/DrawnMining.java | 22 ++ .../text/codemining/AbstractCodeMining.java | 25 +- .../codemining/DocumentFooterCodeMining.java | 2 +- .../codemining/IPlaceholderCodeMining.java | 70 ++++++ .../text/codemining/LineHeaderCodeMining.java | 2 +- .../CodeMiningLineHeaderAnnotationTest.java | 233 ++++++++++++++++-- .../text/tests/codemining/CodeMiningTest.java | 60 +++++ .../PlaceholderLineHeaderCodeMining.java | 38 +++ 13 files changed, 641 insertions(+), 140 deletions(-) create mode 100644 bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDrawHelper.java create mode 100644 bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/DrawnMining.java create mode 100644 bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/IPlaceholderCodeMining.java create mode 100644 tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/PlaceholderLineHeaderCodeMining.java diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDocumentFooterAnnotation.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDocumentFooterAnnotation.java index 0c866c9d92d..c6b46a52b71 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDocumentFooterAnnotation.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDocumentFooterAnnotation.java @@ -12,7 +12,7 @@ import static org.eclipse.jface.internal.text.codemining.CodeMiningLineHeaderAnnotation.disposeMinings; import static org.eclipse.jface.internal.text.codemining.CodeMiningLineHeaderAnnotation.getMultilineHeight; -import static org.eclipse.jface.internal.text.codemining.CodeMiningLineHeaderAnnotation.hasAtLeastOneResolvedMiningNotEmpty; +import static org.eclipse.jface.internal.text.codemining.CodeMiningLineHeaderAnnotation.hasAtLeastOneDrawableMining; import java.util.ArrayList; import java.util.Collections; @@ -24,7 +24,6 @@ import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Rectangle; import org.eclipse.core.runtime.IProgressMonitor; @@ -49,9 +48,9 @@ public class CodeMiningDocumentFooterAnnotation extends LineFooterAnnotation imp private volatile List fMinings; /** - * List of bounds minings + * List of drawn minings */ - private final List fBounds; + private final List fDrawnMinings; /** * The current progress monitor @@ -82,13 +81,13 @@ public CodeMiningDocumentFooterAnnotation(Position position, ISourceViewer viewe super(position, viewer, onMouseHover, onMouseOut, onMouseMove); fResolvedMinings= null; fMinings= List.of(); - fBounds= new ArrayList<>(); + fDrawnMinings= new ArrayList<>(); } @Override public int getHeight() { List minings= fMinings; - return hasAtLeastOneResolvedMiningNotEmpty(minings, fResolvedMinings) + return hasAtLeastOneDrawableMining(minings, fResolvedMinings) ? getMultilineHeight(null, minings, super.getTextWidget(), super.getHeight()) : 0; } @@ -181,7 +180,7 @@ public void markDeleted(boolean deleted) { @Override public void draw(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) { int singleLineHeight= super.getHeight(); - CodeMiningLineHeaderAnnotation.draw(fMinings, fBounds, singleLineHeight, fResolvedMinings, gc, textWidget, color, x, y, this::redraw); + CodeMiningLineHeaderAnnotation.draw(fMinings, fDrawnMinings, singleLineHeight, fResolvedMinings, gc, textWidget, color, x, y, this::redraw); } @Override @@ -202,7 +201,7 @@ public void redraw() { @Override public Consumer getAction(MouseEvent e) { - ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fResolvedMinings, fBounds, e.x, e.y); + ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fDrawnMinings, e.x, e.y); return mining != null ? mining.getAction() : null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDrawHelper.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDrawHelper.java new file mode 100644 index 00000000000..5442a3f4e76 --- /dev/null +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningDrawHelper.java @@ -0,0 +1,139 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.jface.internal.text.codemining; + +import org.eclipse.jface.text.codemining.ICodeMining; +import org.eclipse.jface.text.codemining.IPlaceholderCodeMining; + +final class CodeMiningDrawHelper { + + private CodeMiningDrawHelper() { + // Utility class + } + + /** + * Returns the codemining to draw. Is either {@code null} or a + * {@linkplain #isDrawableMining(ICodeMining) drawable} mining. + *

+ * If the mining has a {@code null} label and is not resolved, the {@code redrawRunnable} is + * invoked. If the mining is resolved without error, the resolved minings array is updated. + *

+ * The returned mining can be an unresolved mining if it is a placeholder code mining and has a + * non-empty {@linkplain IPlaceholderCodeMining#getPlaceholderLabel() placeholder label}. + * + * @param mining The mining at {@code index} + * @param index The index of the mining + * @param resolvedMinings The array of resolved minings + * @param redrawRunnable The runnable to invoke for redrawing, should be a runnable obtained via + * {@link #once(Runnable)} + * @return The {@linkplain #isDrawableMining(ICodeMining) drawable} code mining to draw, or + * {@code null} if no mining should be drawn. + */ + static ICodeMining chooseMiningToDraw(ICodeMining mining, int index, ICodeMining[] resolvedMinings, Runnable redrawRunnable) { + ICodeMining lastResolvedMining= (resolvedMinings != null && resolvedMinings.length > index) ? resolvedMinings[index] : null; + ICodeMining toDraw= switch (getResolveState(mining)) { + case UNRESOLVED -> { + redrawRunnable.run(); + yield lastResolvedMining; + } + case UNRESOLVED_WITH_PLACEHOLDER -> { + redrawRunnable.run(); + + if (CodeMiningManager.isValidMining(lastResolvedMining)) { + yield lastResolvedMining; + } + + yield mining; + } + case RESOLVED_ERROR -> lastResolvedMining; + case RESOLVED -> { + if (resolvedMinings != null && resolvedMinings.length > index) { + resolvedMinings[index]= mining; + } + yield mining; + } + }; + + if (isDrawableMining(toDraw)) { + return toDraw; + } + + return null; + } + + /** + * Wraps the given Runnable, so that it is invoked at most once. + *

+ * This implementation is not thread-safe. If the runnable is shared by multiple threads, the + * delegated-to runnable can still be invoked multiple times. + * + * @param r The runnable to wrap + * @return The runnable wrapper, delegates to the given Runnable at most once. + */ + static Runnable once(Runnable r) { + return new Runnable() { + + boolean ran= false; + + @Override + public void run() { + if (!ran) { + ran= true; + r.run(); + } + } + }; + } + + /** + * Returns {@code true} if the given mining has a non-empty label or is not resolved and has a + * non-empty placeholder label. Returns {@code false} otherwise. + * + * @param mining the mining to check. + * @return {@code true} if the given mining has a non-empty label or is not resolved and has a + * non-empty placeholder label. {@code false} otherwise + */ + static boolean isDrawableMining(ICodeMining mining) { + if (mining == null) { + return false; + } + + String label= CodeMiningManager.getLabelOrPlaceholder(mining); + return label != null && !label.isEmpty(); + } + + private static ResolveState getResolveState(ICodeMining mining) { + String label= mining.getLabel(); + + if (label == null && mining.isResolved()) { + return ResolveState.RESOLVED_ERROR; + } else if (label != null) { + return ResolveState.RESOLVED; + } + + if (mining instanceof IPlaceholderCodeMining placeholderMining) { + String placeholderLabel= placeholderMining.getPlaceholderLabel(); + + if (placeholderLabel != null && !placeholderLabel.isEmpty()) { + return ResolveState.UNRESOLVED_WITH_PLACEHOLDER; + } + } + + return ResolveState.UNRESOLVED; + } + + private enum ResolveState { + + UNRESOLVED, UNRESOLVED_WITH_PLACEHOLDER, RESOLVED_ERROR, RESOLVED; + + } + +} diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineContentAnnotation.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineContentAnnotation.java index 9759ecee4d8..03928031677 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineContentAnnotation.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineContentAnnotation.java @@ -14,7 +14,6 @@ package org.eclipse.jface.internal.text.codemining; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.function.Consumer; @@ -51,9 +50,9 @@ public class CodeMiningLineContentAnnotation extends LineContentAnnotation imple private volatile List fMinings; /** - * List of bounds minings + * List of drawn minings */ - private final List fBounds; + private final List fDrawnMinings; /** * The current progress monitor @@ -98,7 +97,7 @@ public CodeMiningLineContentAnnotation(Position position, ISourceViewer viewer, super(position, viewer, onMouseHover, onMouseOut, onMouseMove); fResolvedMinings= null; fMinings= List.of(); - fBounds= new ArrayList<>(); + fDrawnMinings= new ArrayList<>(); this.afterPosition= afterPosition; } @@ -121,7 +120,7 @@ public void update(List minings, IProgressMonitor monitor) { } fResolvedMinings= resolvedMinings; fMonitor= monitor; - fMinings= Collections.unmodifiableList(new ArrayList<>(minings)); + fMinings= List.copyOf(minings); CodeMiningLineHeaderAnnotation.disposeMinings(oldMinings); } @@ -143,34 +142,13 @@ protected int drawAndComputeWidth(GC gc, StyledText textWidget, int offset, int int nbDraw= 0; int originalX= x; int separatorWidth= -1; - boolean redrawn= false; - fBounds.clear(); + Runnable redrawRunnable= CodeMiningDrawHelper.once(this::redraw); + fDrawnMinings.clear(); for (int i= 0; i < minings.size(); i++) { - ICodeMining mining= minings.get(i); - // try to get the last resolved mining. - ICodeMining lastResolvedMining= (resolvedMinings != null && resolvedMinings.length > i) ? resolvedMinings[i] : null; - if (mining.getLabel() != null) { - // mining is resolved without error, update the resolved mining list - if (resolvedMinings != null && resolvedMinings.length > i) { - resolvedMinings[i]= mining; - } - } else if (!mining.isResolved()) { - // the mining is not resolved, draw the last resolved mining - mining= lastResolvedMining; - if (!redrawn) { - // redraw the annotation when mining is resolved. - redraw(); - redrawn= true; - } - } else { - // the mining is resolved with error, draw the last resolved mining - mining= lastResolvedMining; - } - if (!CodeMiningManager.isValidMining(mining)) { - // ignore the draw of mining + ICodeMining mining= CodeMiningDrawHelper.chooseMiningToDraw(minings.get(i), i, resolvedMinings, redrawRunnable); + if (mining == null) { continue; } - // draw the mining if (nbDraw > 0) { gc.drawText(SEPARATOR, x, y); if (separatorWidth == -1) { @@ -178,9 +156,8 @@ protected int drawAndComputeWidth(GC gc, StyledText textWidget, int offset, int } x+= separatorWidth; } - @SuppressWarnings("null") Point loc= mining.draw(gc, textWidget, color, x, y); - fBounds.add(new Rectangle(x, y, loc.x, loc.y)); + fDrawnMinings.add(new DrawnMining(new Rectangle(x, y, loc.x, loc.y), mining)); x+= loc.x; nbDraw++; } @@ -205,7 +182,7 @@ public void redraw() { @Override public Consumer getAction(MouseEvent e) { - ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fResolvedMinings, fBounds, e.x, e.y); + ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fDrawnMinings, e.x, e.y); return mining != null ? mining.getAction() : null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineHeaderAnnotation.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineHeaderAnnotation.java index 0b1911cee4d..cf21d69c924 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineHeaderAnnotation.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningLineHeaderAnnotation.java @@ -14,7 +14,6 @@ package org.eclipse.jface.internal.text.codemining; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.regex.Pattern; @@ -52,9 +51,9 @@ public class CodeMiningLineHeaderAnnotation extends LineHeaderAnnotation impleme private volatile List fMinings; /** - * List of bounds minings + * List of drawn minings */ - private final List fBounds; + private final List fDrawnMinings; /** * The current progress monitor @@ -86,7 +85,7 @@ public CodeMiningLineHeaderAnnotation(Position position, ISourceViewer viewer, C super(position, viewer, onMouseHover, onMouseOut, onMouseMove); fResolvedMinings= null; fMinings= List.of(); - fBounds= new ArrayList<>(); + fDrawnMinings= new ArrayList<>(); } @Override @@ -96,7 +95,7 @@ public int getHeight() { public int getHeight(GC gc) { List minings= fMinings; - return hasAtLeastOneResolvedMiningNotEmpty(minings, fResolvedMinings) ? getMultilineHeight(gc, minings, super.getTextWidget(), super.getHeight()) : 0; + return hasAtLeastOneDrawableMining(minings, fResolvedMinings) ? getMultilineHeight(gc, minings, super.getTextWidget(), super.getHeight()) : 0; } private static String firstLine(String label) { @@ -115,7 +114,7 @@ static int getMultilineHeight(GC gc, List minings, StyledText style int sumLineHeight= 0; for (int i= 0; i < minings.size(); i++) { ICodeMining mining= minings.get(i); - String label= mining.getLabel(); + String label= CodeMiningManager.getLabelOrPlaceholder(mining); if (label == null) { continue; } @@ -156,7 +155,7 @@ private static int calculateLineHeight(List minings, GC gc, StyledT sumLineHeight+= styledTextLineHeight + styledText.getLineSpacing(); } else { if (j == splitted.length - 1 && miningIndex + 1 < minings.size()) { // last line, take first line from next mining - String nextLabel= minings.get(miningIndex + 1).getLabel(); + String nextLabel= CodeMiningManager.getLabelOrPlaceholder(minings.get(miningIndex + 1)); if (nextLabel != null) { String firstFromNext= firstLine(nextLabel); line+= firstFromNext; @@ -170,17 +169,16 @@ private static int calculateLineHeight(List minings, GC gc, StyledT } /** - * Returns true if the annotation has at least one resolved mining which have a - * label and false otherwise. + * Returns true if the annotation has at least one mining which has a non-empty + * label (or placeholder label) and false otherwise. * - * @return true if the annotation has at least one resolved mining which have a - * label and false otherwise. + * @return true if the annotation has at least one mining which has a non-empty + * label (or placeholder label) and false otherwise. */ - static boolean hasAtLeastOneResolvedMiningNotEmpty(List minings, ICodeMining[] resolvedMinings) { + static boolean hasAtLeastOneDrawableMining(List minings, ICodeMining[] resolvedMinings) { for (ICodeMining mining : minings) { - String label= mining.getLabel(); - if (label != null && !label.isEmpty()) { - return true; // will have a resolved mining. + if (CodeMiningDrawHelper.isDrawableMining(mining)) { + return true; } } @@ -188,7 +186,7 @@ static boolean hasAtLeastOneResolvedMiningNotEmpty(List minings, IC return false; } for (ICodeMining resolved : resolvedMinings) { - if (CodeMiningManager.isValidMining(resolved)) { + if (CodeMiningDrawHelper.isDrawableMining(resolved)) { return true; } } @@ -213,7 +211,7 @@ public void update(List minings, IProgressMonitor monitor) { } fResolvedMinings= resolvedMinings; fMonitor= monitor; - fMinings= Collections.unmodifiableList(new ArrayList<>(minings)); + fMinings= List.copyOf(minings); disposeMinings(oldMinings); } @@ -235,42 +233,21 @@ static void disposeMinings(List minings) { @Override public void draw(GC gc, StyledText textWidget, int offset, int length, Color color, int x, int y) { int singleLineHeight= super.getHeight(); - draw(fMinings, fBounds, singleLineHeight, fResolvedMinings, gc, textWidget, color, x, y, this::redraw); + draw(fMinings, fDrawnMinings, singleLineHeight, fResolvedMinings, gc, textWidget, color, x, y, this::redraw); } - static void draw(List minings, List fBounds, int singleLineHeight, ICodeMining[] fResolvedMinings, GC gc, StyledText textWidget, Color color, + static void draw(List minings, List fDrawnMinings, int singleLineHeight, ICodeMining[] fResolvedMinings, GC gc, StyledText textWidget, Color color, int x, int y, Runnable redrawRunnable) { int nbDraw= 0; int separatorWidth= -1; - boolean redrawn= false; - fBounds.clear(); + fDrawnMinings.clear(); int lineSpacing= textWidget.getLineSpacing(); + Runnable redrawOnce= CodeMiningDrawHelper.once(redrawRunnable); for (int i= 0; i < minings.size(); i++) { - ICodeMining mining= minings.get(i); - // try to get the last resolved mining. - ICodeMining lastResolvedMining= (fResolvedMinings != null && fResolvedMinings.length > i) ? fResolvedMinings[i] : null; - if (mining.getLabel() != null) { - // mining is resolved without error, update the resolved mining list - if (fResolvedMinings != null && fResolvedMinings.length > i) { - fResolvedMinings[i]= mining; - } - } else if (!mining.isResolved()) { - // the mining is not resolved, draw the last resolved mining - mining= lastResolvedMining; - if (!redrawn) { - // redraw the annotation when mining is resolved. - redrawRunnable.run(); - redrawn= true; - } - } else { - // the mining is resolved with error, draw the last resolved mining - mining= lastResolvedMining; - } - if (!CodeMiningManager.isValidMining(mining)) { - // ignore the draw of mining + ICodeMining mining= CodeMiningDrawHelper.chooseMiningToDraw(minings.get(i), i, fResolvedMinings, redrawOnce); + if (mining == null) { continue; } - // draw the mining if (nbDraw > 0) { gc.drawText(SEPARATOR, x, y); if (separatorWidth == -1) { @@ -278,12 +255,9 @@ static void draw(List minings, List fBounds, int singleL } x+= separatorWidth; } - Point loc= null; - if (mining != null) { - loc= mining.draw(gc, textWidget, color, x, y); - } + Point loc= mining.draw(gc, textWidget, color, x, y); if (loc != null) { - fBounds.add(new Rectangle(x, y, loc.x, loc.y)); + fDrawnMinings.add(new DrawnMining(new Rectangle(x, y, loc.x, loc.y), mining)); x+= loc.x; if (loc.y > singleLineHeight) { y+= loc.y + lineSpacing - singleLineHeight; @@ -311,7 +285,7 @@ public void redraw() { @Override public Consumer getAction(MouseEvent e) { - ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fResolvedMinings, fBounds, e.x, e.y); + ICodeMining mining= CodeMiningManager.getValidCodeMiningAtLocation(fDrawnMinings, e.x, e.y); return mining != null ? mining.getAction() : null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningManager.java index c794c429937..8bd9fe38151 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/CodeMiningManager.java @@ -32,7 +32,6 @@ import org.osgi.framework.Bundle; import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.graphics.Rectangle; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.ILog; @@ -47,6 +46,7 @@ import org.eclipse.jface.text.codemining.DocumentFooterCodeMining; import org.eclipse.jface.text.codemining.ICodeMining; import org.eclipse.jface.text.codemining.ICodeMiningProvider; +import org.eclipse.jface.text.codemining.IPlaceholderCodeMining; import org.eclipse.jface.text.codemining.LineContentCodeMining; import org.eclipse.jface.text.codemining.LineHeaderCodeMining; import org.eclipse.jface.text.source.Annotation; @@ -353,42 +353,46 @@ static boolean isValidMining(ICodeMining mining) { } /** - * Returns the valid code mining at the given location by using the bounds of codemining - * annotations which stores only the valid code mining. + * Return the label of the code mining. If the label is {@code null} and the mining is an + * unresolved {@link IPlaceholderCodeMining}, then the + * {@linkplain IPlaceholderCodeMining#getPlaceholderLabel() placeholder label} is returned. * - * @param minings the list of mining of the codemining annotation. - * @param bounds the bounds of the valid minings of the codemining annotation. - * @param x the x location - * @param y the y location - * @return the valid code mining at the given location by using the bounds of codemining - * annotations which stores only the valid code mining. + * @param mining the mining + * @return The label, or the placeholder if {@code null} and not resolved */ - static ICodeMining getValidCodeMiningAtLocation(ICodeMining[] minings, List bounds, int x, int y) { - for (int i= 0; i < bounds.size(); i++) { - Rectangle bound= bounds.get(i); - if (bound.contains(x, y)) { - return getCodeValidMiningAtIndex(minings, i); - } + static String getLabelOrPlaceholder(ICodeMining mining) { + String label= mining.getLabel(); + + if (label == null && mining instanceof IPlaceholderCodeMining placeHolderMining && !mining.isResolved()) { + return placeHolderMining.getPlaceholderLabel(); } - return null; + + return label; } /** - * Returns the valid code mining at the given index. + * Returns the valid code mining at the given location by using the list of drawn code minings + * and their bounds. * - * @param minings the list of minings - * @param index the index - * @return the valid code mining at the given index. + * @param drawnMinings the list of drawn minings of the codemining annotation. + * @param x the x location + * @param y the y location + * @return the valid code mining at the given location by using the bounds of codemining + * annotations which stores only the valid code mining. */ - private static ICodeMining getCodeValidMiningAtIndex(ICodeMining[] minings, int index) { - int validIndex= 0; - for (ICodeMining mining : minings) { + static ICodeMining getValidCodeMiningAtLocation(List drawnMinings, int x, int y) { + for (DrawnMining drawnMining : drawnMinings) { + if (!drawnMining.bounds().contains(x, y)) { + continue; + } + + ICodeMining mining= drawnMining.mining(); + if (isValidMining(mining)) { - if (validIndex == index) { - return mining; - } - validIndex++; + return mining; } + + return null; } return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/DrawnMining.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/DrawnMining.java new file mode 100644 index 00000000000..65bb0c0621c --- /dev/null +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/codemining/DrawnMining.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.jface.internal.text.codemining; + +import org.eclipse.swt.graphics.Rectangle; + +import org.eclipse.jface.text.codemining.ICodeMining; + +/** + * Tuple holding the bounds and the drawn code mining + */ +record DrawnMining(Rectangle bounds, ICodeMining mining) { + +} diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMining.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMining.java index 3547e2daa6b..29a26224f27 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMining.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMining.java @@ -142,13 +142,36 @@ public void dispose() { */ @Override public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { - String title= getLabel() != null ? getLabel() : "no command"; //$NON-NLS-1$ + String title= getLabelOrPlaceholder(); + + if (title == null) { + title= "no command"; //$NON-NLS-1$ + } + gc.drawString(title, x, y, true); Point result= gc.stringExtent(title); result.y= textWidget.getLineHeight() + textWidget.getLineSpacing(); return result; } + /** + * Returns the label, unless the label is {@code null} and {@code this} is an unresolved + * {@link IPlaceholderCodeMining}, then the {@link IPlaceholderCodeMining#getPlaceholderLabel() + * placeholder} is returned. + * + * @since 3.32 + * @return The label, or the placeholder if {@code null} and not resolved + */ + protected final String getLabelOrPlaceholder() { + String title= getLabel(); + + if (title == null && this instanceof IPlaceholderCodeMining placeHolderMining && !isResolved()) { + return placeHolderMining.getPlaceholderLabel(); + } + + return title; + } + @Override public Consumer getAction() { return action; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/DocumentFooterCodeMining.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/DocumentFooterCodeMining.java index f1c8889f10c..9d56bdf2173 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/DocumentFooterCodeMining.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/DocumentFooterCodeMining.java @@ -34,6 +34,6 @@ public DocumentFooterCodeMining(IDocument document, ICodeMiningProvider provider @Override public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { - return LineHeaderCodeMining.draw(getLabel(), gc, textWidget, x, y, () -> DocumentFooterCodeMining.super.draw(gc, textWidget, color, x, y)); + return LineHeaderCodeMining.draw(getLabelOrPlaceholder(), gc, textWidget, x, y, () -> DocumentFooterCodeMining.super.draw(gc, textWidget, color, x, y)); } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/IPlaceholderCodeMining.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/IPlaceholderCodeMining.java new file mode 100644 index 00000000000..3ac92cfd2fd --- /dev/null +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/IPlaceholderCodeMining.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.jface.text.codemining; + +import java.util.concurrent.CompletableFuture; + +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.jface.text.ITextViewer; + +/** + * A placeholder code mining is a code mining which displays a {@linkplain #getPlaceholderLabel() + * placeholder label} while its actual {@linkplain #getLabel() label} is being computed. + *

+ * A placeholder code mining can be used to prevent editor jumping for code minings with expensive + * {@link #resolve(ITextViewer, IProgressMonitor)} implementations, especially for + * {@linkplain LineHeaderCodeMining}s. + *

+ * Implementations must adhere to the following contract for {@link #getLabel()}: + *

    + *
  • {@link #getLabel()} must return {@code null} until the label is computed. The placeholder is + * only used while {@link #getLabel()} returns {@code null} and the mining is not + * {@linkplain #isResolved() resolved}. If a non-{@code null} label is set before resolving, the + * placeholder is never displayed.
  • + *
  • The label must be set during resolution, i.e. after + * {@link #resolve(ITextViewer, IProgressMonitor)} is invoked and before the future returned by it + * completes.
  • + *
  • If resolution fails or is cancelled, the label should remain {@code null}. The mining is then + * treated as resolved with an error, see {@link ICodeMining#getLabel()}.
  • + *
+ * + * @see ICodeMining + * @since 3.32 + */ +public interface IPlaceholderCodeMining extends ICodeMining { + + /** + * Returns the placeholder label, which is displayed while {@link #getLabel()} returns + * {@code null} and the mining is not yet {@linkplain #isResolved() resolved}. + *

+ * If the placeholder label is {@code null} or empty, no placeholder is displayed. + * + * @return the placeholder label, may be {@code null} or empty. + */ + String getPlaceholderLabel(); + + /** + * Returns the future to resolve the content of the mining. + *

+ * The {@linkplain #getLabel() label} must be computed and set during resolution, i.e. before + * the returned future completes. + *

+ * If the resolution fails or is cancelled, the label should remain {@code null}. + * + * @param viewer {@inheritDoc} + * @param monitor {@inheritDoc} + * @return the future to resolve the content of the mining. + */ + @Override + CompletableFuture resolve(ITextViewer viewer, IProgressMonitor monitor); + +} diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/LineHeaderCodeMining.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/LineHeaderCodeMining.java index 3c6ed2f56e0..18712689c87 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/LineHeaderCodeMining.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/LineHeaderCodeMining.java @@ -83,7 +83,7 @@ public LineHeaderCodeMining(Position position, ICodeMiningProvider provider, Con @Override public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { - return draw(getLabel(), gc, textWidget, x, y, () -> LineHeaderCodeMining.super.draw(gc, textWidget, color, x, y)); + return draw(getLabelOrPlaceholder(), gc, textWidget, x, y, () -> LineHeaderCodeMining.super.draw(gc, textWidget, color, x, y)); } static Point draw(String label, GC gc, StyledText textWidget, int x, int y, Callable superDrawCallable) { diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningLineHeaderAnnotationTest.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningLineHeaderAnnotationTest.java index 18329065f72..bb846d0cb16 100644 --- a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningLineHeaderAnnotationTest.java +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningLineHeaderAnnotationTest.java @@ -11,19 +11,27 @@ package org.eclipse.jface.text.tests.codemining; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; @@ -32,12 +40,19 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; + import org.eclipse.jface.internal.text.codemining.CodeMiningLineHeaderAnnotation; 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.codemining.ICodeMining; +import org.eclipse.jface.text.codemining.ICodeMiningProvider; +import org.eclipse.jface.text.codemining.IPlaceholderCodeMining; import org.eclipse.jface.text.codemining.LineHeaderCodeMining; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.AnnotationPainter; @@ -112,20 +127,25 @@ public String getLabel() { } } - @Test - public void testGetHeightDoesNotReturnZero() throws Exception { + @ValueSource(booleans= { false, true }) + @ParameterizedTest(name= "[{index}] placeHolder: {0}") + public void testGetHeightDoesNotReturnZero(boolean placeholder) throws Exception { var cut= new CodeMiningLineHeaderAnnotation(new Position(0, 0), fViewer); var s= new InlinedAnnotationSupport(); s.install(fViewer, new AnnotationPainter(fViewer, null)); var m= AbstractInlinedAnnotation.class.getDeclaredMethod("setSupport", InlinedAnnotationSupport.class); m.setAccessible(true); m.invoke(cut, s); - cut.update(Arrays.asList(new LineHeaderCodeMining(0, document, null) { - @Override - public String getLabel() { - return "mining"; - } - }), null); + + ICodeMining mining; + + if (placeholder) { + mining= unresolvedPlaceholder("Placeholder"); + } else { + mining= codeMining("mining"); + } + + cut.update(List.of(mining), null); // https: //github.com/eclipse-platform/eclipse.platform.ui/issues/2786 assertNotEquals(0, cut.getHeight()); // getHeight should not return 0, otherwise editor content starts jumping around } @@ -139,10 +159,10 @@ public String getLabel() { * {@link StyledText#getLineHeight()}, so the lines below a multiline code mining were shifted * by a few pixels relative to the regular grid. */ - @Test - public void testTwoLineCodeMiningHeightMatchesTextWidgetLineHeight() throws Exception { - var doc= fViewer.getDocument(); - doc.set("line0\nline1\nline2"); + @ValueSource(booleans= { false, true }) + @ParameterizedTest(name= "[{index}] placeHolder: {0}") + public void testTwoLineCodeMiningHeightMatchesTextWidgetLineHeight(boolean placeholder) throws Exception { + document.set("line0\nline1\nline2"); var textWidget= fViewer.getTextWidget(); // A line spacing != 0 makes a regression in either factor immediately visible. textWidget.setLineSpacing(3); @@ -155,12 +175,14 @@ public void testTwoLineCodeMiningHeightMatchesTextWidgetLineHeight() throws Exce textWidget.setFont(consolasFont); } String codeMiningLabel= "code mining line1\ncode mining line2"; - var mining= new LineHeaderCodeMining(0, doc, null, null) { - @Override - public String getLabel() { - return codeMiningLabel; - } - }; + ICodeMining mining; + + if (placeholder) { + mining= unresolvedPlaceholder(codeMiningLabel); + } else { + mining= codeMining(codeMiningLabel); + } + int normalLineHeight= textWidget.getLineHeight(); int lineSpacing= textWidget.getLineSpacing(); int numMiningLines= codeMiningLabel.split("\n").length; @@ -258,6 +280,141 @@ public void testMultilineHeightWithLineBreaksInLabels() throws Exception { } } + @Test + public void testUnresolvedPlaceholderRequestsRedraw() throws Exception { + AtomicBoolean redrawRequested= new AtomicBoolean(false); + AtomicBoolean resolveRequested= new AtomicBoolean(false); + AtomicReference labelDrawn= new AtomicReference<>(); + + CodeMiningLineHeaderAnnotation annotation= new CodeMiningLineHeaderAnnotation(new Position(0, 0), fViewer) { + @Override + public void redraw() { + redrawRequested.set(true); + super.redraw(); + } + }; + StyledText widget= fViewer.getTextWidget(); + + String placeholder= "Placeholder"; + + ICodeMining mining= new ResolvablePlaceholderMining(0, document, null, placeholder) { + + @Override + public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + labelDrawn.compareAndSet(null, getLabelOrPlaceholder()); + return super.draw(gc, textWidget, color, x, y); + } + + @Override + protected CompletableFuture doResolve(ITextViewer viewer, IProgressMonitor monitor) { + resolveRequested.set(true); + return new CompletableFuture<>(); + } + }; + + annotation.update(List.of(mining), new NullProgressMonitor()); + + GC gc= new GC(widget); + + try { + annotation.draw(gc, widget, 0, 0, null, 0, 0); + } finally { + gc.dispose(); + } + + assertTrue(resolveRequested.get()); + assertTrue(redrawRequested.get()); + assertEquals(placeholder, labelDrawn.get()); + } + + @Test + public void testResolvedPlaceholderDoesNotRequestRedraw() throws Exception { + AtomicBoolean redrawRequested= new AtomicBoolean(false); + AtomicBoolean resolveRequested= new AtomicBoolean(false); + + CodeMiningLineHeaderAnnotation annotation= new CodeMiningLineHeaderAnnotation(new Position(0, 0), fViewer) { + @Override + public void redraw() { + redrawRequested.set(true); + super.redraw(); + } + }; + StyledText widget= fViewer.getTextWidget(); + + String placeholder= "Placeholder"; + + ICodeMining mining= new ResolvablePlaceholderMining(0, document, null, placeholder) { + @Override + protected CompletableFuture doResolve(ITextViewer viewer, IProgressMonitor monitor) { + resolveRequested.set(true); + return CompletableFuture.runAsync(() -> { + setLabel("Resolved"); + }); + } + }; + + mining.resolve(fViewer, new NullProgressMonitor()).get(2, TimeUnit.SECONDS); + resolveRequested.set(false); // Reset after intentional resolve + + annotation.update(List.of(mining), new NullProgressMonitor()); + + GC gc= new GC(widget); + + try { + annotation.draw(gc, widget, 0, 0, null, 0, 0); + + assertFalse(resolveRequested.get()); + assertFalse(redrawRequested.get()); + } finally { + gc.dispose(); + } + } + + @Test + public void testUnresolvedPlaceholderShowsLastResolved() throws Exception { + AtomicReference drawnMining= new AtomicReference<>(); + + ICodeMining resolved= new LineHeaderCodeMining(0, document, null) { + @Override + public String getLabel() { + return "Label"; + } + + @Override + public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + drawnMining.compareAndSet(null, this); + return super.draw(gc, textWidget, color, x, y); + } + }; + + ICodeMining unresolvedPlaceholder= new ResolvablePlaceholderMining(0, document, null, "Placeholder") { + @Override + public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + drawnMining.compareAndSet(null, this); + return super.draw(gc, textWidget, color, x, y); + } + }; + + CodeMiningLineHeaderAnnotation annotation= new CodeMiningLineHeaderAnnotation(new Position(0, 0), fViewer); + annotation.update(List.of(resolved), new NullProgressMonitor()); + annotation.update(List.of(unresolvedPlaceholder), new NullProgressMonitor()); + + StyledText widget= fViewer.getTextWidget(); + GC gc= new GC(widget); + + try { + annotation.draw(gc, widget, 0, 0, null, 0, 0); + + assertEquals(resolved, drawnMining.get()); + } finally { + gc.dispose(); + } + } + + private LineHeaderCodeMining unresolvedPlaceholder(String label) throws BadLocationException { + return new UnresolvedPlaceholderMining(0, document, null, label); + } + private LineHeaderCodeMining codeMining(String label) throws BadLocationException { return new LineHeaderCodeMining(0, document, null) { @Override @@ -274,4 +431,42 @@ private static Font tryCreateConsolasFont(StyledText textWidget, int height) { } return new Font(textWidget.getDisplay(), "Consolas", height, SWT.NORMAL); //$NON-NLS-1$ } + + private static class UnresolvedPlaceholderMining extends LineHeaderCodeMining implements IPlaceholderCodeMining { + + private final String placeholderLabel; + + public UnresolvedPlaceholderMining(int beforeLineNumber, IDocument document, ICodeMiningProvider provider, String label) throws BadLocationException { + super(beforeLineNumber, document, provider); + this.placeholderLabel= label; + } + + @Override + public boolean isResolved() { + return false; + } + + @Override + public String getPlaceholderLabel() { + return placeholderLabel; + } + + } + + private static class ResolvablePlaceholderMining extends LineHeaderCodeMining implements IPlaceholderCodeMining { + + private final String placeholderLabel; + + public ResolvablePlaceholderMining(int beforeLineNumber, IDocument document, ICodeMiningProvider provider, String placeholder) throws BadLocationException { + super(beforeLineNumber, document, provider); + this.placeholderLabel= placeholder; + } + + @Override + public String getPlaceholderLabel() { + return placeholderLabel; + } + + } + } diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java index 3bec2c7a527..93d47efdf31 100644 --- a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java @@ -15,7 +15,9 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -877,6 +879,64 @@ protected boolean condition() { }.waitForCondition(widget.getDisplay(), 1000), "Line header code minigs were used. Expected in-line code minings instead."); } + @Test + public void testLineHeaderCodeMiningPlaceholder() { + String placeholderText= "Placeholder"; + String labelText= "Mining"; + Set drawnLabels= Collections.synchronizedSet(new HashSet<>()); + CompletableFuture resolvedLabel= new CompletableFuture<>(); + + fViewer.setCodeMiningProviders(new ICodeMiningProvider[] { + new AbstractCodeMiningProvider() { + @Override + public CompletableFuture> provideCodeMinings(ITextViewer viewer, IProgressMonitor monitor) { + try { + ICodeMining mining= new PlaceholderLineHeaderCodeMining(0, viewer.getDocument(), this) { + + @Override + public String getPlaceholderLabel() { + return placeholderText; + } + + @Override + protected CompletableFuture doResolve(ITextViewer theViewer, IProgressMonitor theMonitor) { + return resolvedLabel.thenAccept(this::setLabel); + } + + @Override + public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + drawnLabels.add(getLabelOrPlaceholder()); + return super.draw(gc, textWidget, color, x, y); + } + }; + + return CompletableFuture.completedFuture(List.of(mining)); + } catch (BadLocationException e) { + return CompletableFuture.failedFuture(e); + } + } + } + }); + + fViewer.getDocument().set("Document"); + + Assertions.assertTrue(new DisplayHelper() { + @Override + protected boolean condition() { + return drawnLabels.contains(placeholderText); + } + }.waitForCondition(fViewer.getTextWidget().getDisplay(), 1000), "Placeholder label was not rendered"); + + resolvedLabel.complete(labelText); + + Assertions.assertTrue(new DisplayHelper() { + @Override + protected boolean condition() { + return drawnLabels.contains(labelText); + } + }.waitForCondition(fViewer.getTextWidget().getDisplay(), 1000), "Resolved label was not rendered"); + } + private static boolean hasCodeMiningPrintedBelowLine(ITextViewer viewer, int line) throws BadLocationException { StyledText widget= viewer.getTextWidget(); IDocument document= viewer.getDocument(); diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/PlaceholderLineHeaderCodeMining.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/PlaceholderLineHeaderCodeMining.java new file mode 100644 index 00000000000..7f7e3024fa5 --- /dev/null +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/PlaceholderLineHeaderCodeMining.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.jface.text.tests.codemining; + +import java.util.function.Consumer; + +import org.eclipse.swt.events.MouseEvent; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.codemining.ICodeMiningProvider; +import org.eclipse.jface.text.codemining.IPlaceholderCodeMining; +import org.eclipse.jface.text.codemining.LineHeaderCodeMining; + +public abstract class PlaceholderLineHeaderCodeMining extends LineHeaderCodeMining implements IPlaceholderCodeMining { + + public PlaceholderLineHeaderCodeMining(int beforeLineNumber, IDocument document, ICodeMiningProvider provider, Consumer action) throws BadLocationException { + super(beforeLineNumber, document, provider, action); + } + + public PlaceholderLineHeaderCodeMining(int beforeLineNumber, IDocument document, ICodeMiningProvider provider) throws BadLocationException { + super(beforeLineNumber, document, provider); + } + + public PlaceholderLineHeaderCodeMining(Position position, ICodeMiningProvider provider, Consumer action) throws BadLocationException { + super(position, provider, action); + } + +} From 20f95fa01afe4bf99c61f786e6f5ae219f2e2a4c Mon Sep 17 00:00:00 2001 From: Tobias Melcher Date: Fri, 6 Nov 2026 15:14:29 +0100 Subject: [PATCH 37/52] Prevent reentrant part activation cycles causing UI freezes Drop a context-injected activation of a part whose context-injected activation is still unfinished, which breaks the setPart -> activate -> activateBranch -> setPart cycle. Explicit activations are unchanged. After a dropped activation, once no activation is in progress anymore, activate the context's active part if the part service disagrees. Context changes made by listeners of this correction are followed as well, each part at most once. Each dropped activation logs a warning describing the involved parts, their windows and perspectives, and the active context chain. --- .../internal/workbench/PartServiceImpl.java | 168 +++++++- .../tests/application/EPartServiceTest.java | 368 ++++++++++++++++++ 2 files changed, 527 insertions(+), 9 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java b/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java index ee955da4a61..a208f946e14 100644 --- a/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java +++ b/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java @@ -24,7 +24,9 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.IdentityHashMap; import java.util.List; +import java.util.Set; import org.eclipse.core.commands.contexts.ContextManager; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.ISafeRunnable; @@ -38,6 +40,7 @@ import org.eclipse.e4.core.services.log.Logger; import org.eclipse.e4.ui.di.Persist; import org.eclipse.e4.ui.model.application.MApplication; +import org.eclipse.e4.ui.model.application.MApplicationElement; import org.eclipse.e4.ui.model.application.descriptor.basic.MPartDescriptor; import org.eclipse.e4.ui.model.application.ui.MContext; import org.eclipse.e4.ui.model.application.ui.MElementContainer; @@ -188,6 +191,21 @@ private MPart toPart(MStackElement stackElement) { private MPart activePart; + // Only context-injected activations participate in this guard. Explicit client + // requests, including returning to a part from its activation listener, remain valid. + private final Set contextActivations = Collections.newSetFromMap(new IdentityHashMap()); + + // Set when the guard drops a context-injected activation, so the outermost + // context activation can reconcile the active part with the context. + private boolean contextActivationDropped; + + // While reconciling, every context-injected activation is dropped, so the + // correction cannot be redirected into the same cycle again. + private boolean reconcilingWithContext; + + // Number of unfinished activations, explicit or context-injected. + private int activationDepth; + private final ListenerList listeners = new ListenerList<>(); private boolean constructed = false; @@ -209,18 +227,135 @@ private void log(String unidentifiedMessage, String identifiedMessage, String id @Inject void setPart(@Optional @Named(IServiceConstants.ACTIVE_PART) MPart p) { - if (activePart != p) { - if (p != null) { - MPerspective persp = modelService.getPerspectiveFor(p); - boolean inCurrentPerspective = persp == null - || persp == persp.getParent().getSelectedElement(); - if (inCurrentPerspective) { - activate(p, true, true); - } - } else { + if (activePart == p) { + return; + } + if (reconcilingWithContext) { + if (Policy.DEBUG_FOCUS) { + Activator.trace(Policy.DEBUG_FOCUS_FLAG, "Ignored context part activation while reconciling: " + p, //$NON-NLS-1$ + null); + } + return; + } + if (!contextActivations.add(p)) { + contextActivationDropped = true; + reportActivationCycle(p); + return; + } + // only reconcile when no other activation is in progress that could still + // change the active part or the context + boolean outermost = contextActivations.size() == 1 && activationDepth == 0; + try { + activateFromContext(p); + } finally { + contextActivations.remove(p); + } + if (outermost && contextActivationDropped) { + reconcileWithContext(); + } + } + + private void activateFromContext(MPart p) { + if (p != null) { + MPerspective persp = modelService.getPerspectiveFor(p); + boolean inCurrentPerspective = persp == null || persp == persp.getParent().getSelectedElement(); + if (inCurrentPerspective) { activate(p, true, true); } + } else { + activate(p, true, true); + } + } + + /** + * A dropped context activation can leave the active part out of sync with the + * context, e.g. when the tail of an outer activation finishes after a nested + * one. Activates the part the context reports, ignoring further context + * activations meanwhile, so the correction cannot restart the cycle. If a + * listener of the correction moves the context to another part, that part is + * activated as well; each part is activated at most once, which keeps this + * bounded. + */ + private void reconcileWithContext() { + contextActivationDropped = false; + IEclipseContext context = workbenchWindow != null ? workbenchWindow.getContext() : null; + if (context == null) { + return; + } + Set reconciled = Collections.newSetFromMap(new IdentityHashMap<>()); + reconcilingWithContext = true; + try { + MPart contextPart = getContextActivePart(context); + while (contextPart != activePart && reconciled.add(contextPart)) { + if (Policy.DEBUG_FOCUS) { + Activator.trace(Policy.DEBUG_FOCUS_FLAG, "Reconciling active part " + activePart //$NON-NLS-1$ + + " with context part " + contextPart, null); //$NON-NLS-1$ + } + activateFromContext(contextPart); + contextPart = getContextActivePart(context); + } + } finally { + reconcilingWithContext = false; + contextActivationDropped = false; + } + } + + private static MPart getContextActivePart(IEclipseContext context) { + return context.get(IServiceConstants.ACTIVE_PART) instanceof MPart part ? part : null; + } + + private void reportActivationCycle(MPart repeatedPart) { + StringBuilder message = new StringBuilder("Ignored recursive context part activation; active context activations: "); //$NON-NLS-1$ + String separator = ""; //$NON-NLS-1$ + for (MPart part : contextActivations) { + message.append(separator).append(describePart(part)); + separator = ", "; //$NON-NLS-1$ + } + message.append("; repeated part: ").append(describePart(repeatedPart)); //$NON-NLS-1$ + message.append("; active part: ").append(describePart(activePart)); //$NON-NLS-1$ + message.append("; active context chain: ").append(describeActiveContextChain()); //$NON-NLS-1$ + if (Policy.DEBUG_FOCUS) { + Activator.trace(Policy.DEBUG_FOCUS_FLAG, message.toString(), null); + } + logger.warn(new IllegalStateException("Recursive context part activation"), message.toString()); //$NON-NLS-1$ + } + + private String describePart(MPart part) { + if (part == null) { + return "null"; //$NON-NLS-1$ + } + return describeElement(part) + " (window: " + describeElement(modelService.getTopLevelWindowFor(part)) //$NON-NLS-1$ + + ", perspective: " + describeElement(modelService.getPerspectiveFor(part)) + ')'; //$NON-NLS-1$ + } + + private static String describeElement(MApplicationElement element) { + if (element == null) { + return "null"; //$NON-NLS-1$ + } + return element.getElementId() + '@' + Integer.toHexString(System.identityHashCode(element)); + } + + /** + * Describes the contexts from the root to the active leaf, since the stack of + * the dropped activation cannot show computations that already returned. + */ + private String describeActiveContextChain() { + IEclipseContext context = workbenchWindow != null ? workbenchWindow.getContext() : null; + if (context == null) { + return "unknown"; //$NON-NLS-1$ + } + while (context.getParent() != null) { + context = context.getParent(); + } + StringBuilder chain = new StringBuilder(); + for (; context != null; context = context.getActiveChild()) { + if (!chain.isEmpty()) { + chain.append(" > "); //$NON-NLS-1$ + } + Object element = context.getLocal(MApplicationElement.class); + chain.append(element instanceof MApplicationElement e ? describeElement(e) : context.toString()); } + return chain.toString(); } @PostConstruct @@ -696,6 +831,21 @@ public void activate(MPart part, boolean requiresFocus) { } private void activate(MPart part, boolean requiresFocus, boolean activateBranch) { + activationDepth++; + try { + doActivate(part, requiresFocus, activateBranch); + } finally { + activationDepth--; + } + // a listener of this activation may have entered a context activation cycle; + // its nested setPart calls could not reconcile while this activation was running + if (activationDepth == 0 && contextActivations.isEmpty() && contextActivationDropped + && !reconcilingWithContext) { + reconcileWithContext(); + } + } + + private void doActivate(MPart part, boolean requiresFocus, boolean activateBranch) { if (part == null) { if (constructed && activePart != null) { if (Policy.DEBUG_FOCUS) { diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java index bb3254b2ddf..e96f909bf85 100644 --- a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java @@ -19,6 +19,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import java.lang.ref.WeakReference; import java.util.ArrayList; @@ -26,7 +33,10 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.e4.core.contexts.IEclipseContext; +import org.eclipse.e4.core.services.log.Logger; import org.eclipse.e4.ui.di.Focus; import org.eclipse.e4.ui.internal.workbench.PartServiceImpl; import org.eclipse.e4.ui.internal.workbench.PartServiceSaveHandler; @@ -53,9 +63,367 @@ import org.eclipse.e4.ui.workbench.modeling.ISaveHandler.Save; import org.eclipse.emf.common.notify.Notifier; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; public class EPartServiceTest extends UITest { + private record ActivationFixture(MWindow window, EPartService service, MPart partA, MPart partB, MPart partC) { + } + + private ActivationFixture createActivationFixture() { + createApplication("partA", "partB", "partC"); + MWindow window = application.getChildren().get(0); + getEngine().createGui(window); + EPartService service = window.getContext().get(EPartService.class); + MPart a = service.findPart("partA"); + MPart b = service.findPart("partB"); + MPart c = service.findPart("partC"); + getEngine().createGui(b); + getEngine().createGui(c); + service.activate(a); + return new ActivationFixture(window, service, a, b, c); + } + + @Test + public void testListenerActivatesOtherPartThenReturns() { + testListenerReturnsToOriginalPart(false); + } + + @Test + public void testActivate_ContextInjectionCycleIsBoundedAndReported() { + ActivationFixture f = createActivationFixture(); + f.service().activate(f.partC()); + IEclipseContext windowContext = f.window().getContext(); + Logger originalLogger = windowContext.get(Logger.class); + Logger logger = mock(Logger.class); + windowContext.set(Logger.class, logger); + IEclipseContext originalA = f.partA().getContext(); + IEclipseContext originalB = f.partB().getContext(); + IEclipseContext contextA = mock(IEclipseContext.class, delegatesTo(originalA)); + IEclipseContext contextB = mock(IEclipseContext.class, delegatesTo(originalB)); + AtomicInteger branches = new AtomicInteger(); + doAnswer(_ -> { + activateBranchWithIntermediatePart(windowContext, originalA, f.partB(), branches); + return null; + }).when(contextA).activateBranch(); + doAnswer(_ -> { + activateBranchWithIntermediatePart(windowContext, originalB, f.partA(), branches); + return null; + }).when(contextB).activateBranch(); + f.partA().setContext(contextA); + f.partB().setContext(contextB); + try { + f.service().activate(f.partB()); + assertEquals(3, branches.get(), "Repeated injection must stop before the test's safety limit"); + assertEquals(f.partB(), f.service().getActivePart()); + assertEquals(f.partB(), windowContext.get(IServiceConstants.ACTIVE_PART)); + ArgumentCaptor message = ArgumentCaptor.forClass(String.class); + verify(logger, atLeast(1)).warn(any(Throwable.class), message.capture()); + assertTrue(message.getAllValues().stream() + .anyMatch(value -> value.contains("partA") && value.contains("partB"))); + clearInvocations(logger); + f.service().activate(f.partC()); + assertEquals(f.partC(), windowContext.get(IServiceConstants.ACTIVE_PART)); + branches.set(0); + f.service().activate(f.partB()); + assertEquals(3, branches.get()); + assertEquals(f.partB(), f.service().getActivePart()); + assertEquals(f.partB(), windowContext.get(IServiceConstants.ACTIVE_PART)); + verify(logger, atLeast(1)).warn(any(Throwable.class), any(String.class)); + } finally { + f.partA().setContext(originalA); + f.partB().setContext(originalB); + windowContext.remove(IServiceConstants.ACTIVE_PART); + windowContext.remove(Logger.class); + assertEquals(originalLogger, windowContext.get(Logger.class)); + } + } + + private static void activateBranchWithIntermediatePart(IEclipseContext windowContext, IEclipseContext partContext, + MPart intermediatePart, AtomicInteger branches) { + try { + // Limit the unfixed implementation as well, so a regression fails instead of + // overflowing the stack or hanging the UI test harness. + if (branches.incrementAndGet() <= 6) { + windowContext.set(IServiceConstants.ACTIVE_PART, intermediatePart); + } + partContext.activateBranch(); + } finally { + windowContext.remove(IServiceConstants.ACTIVE_PART); + } + } + + @Test + public void testActivateBranch_ContextInjectionCycleKeepsActivePartInSync() { + ActivationFixture f = createActivationFixture(); + f.service().activate(f.partC()); + IEclipseContext windowContext = f.window().getContext(); + Logger logger = mock(Logger.class); + windowContext.set(Logger.class, logger); + IEclipseContext originalA = f.partA().getContext(); + IEclipseContext originalB = f.partB().getContext(); + IEclipseContext contextA = mock(IEclipseContext.class, delegatesTo(originalA)); + IEclipseContext contextB = mock(IEclipseContext.class, delegatesTo(originalB)); + AtomicInteger branches = new AtomicInteger(); + // activating one part's branch passes through the other part's branch first, so + // the context reports the other part as an intermediate ACTIVE_PART + doAnswer(_ -> { + activateBranchThrough(originalB, originalA, branches); + return null; + }).when(contextA).activateBranch(); + doAnswer(_ -> { + activateBranchThrough(originalA, originalB, branches); + return null; + }).when(contextB).activateBranch(); + f.partA().setContext(contextA); + f.partB().setContext(contextB); + List notifications = new ArrayList<>(); + IPartListener listener = new PartListener() { + @Override + public void partActivated(MPart part) { + notifications.add("+" + part.getElementId()); //$NON-NLS-1$ + } + + @Override + public void partDeactivated(MPart part) { + notifications.add("-" + part.getElementId()); //$NON-NLS-1$ + } + }; + f.service().addPartListener(listener); + try { + // enter through the context like ShellActivationListener, so that setPart(partA) + // is the outermost call and the nested activation of partB finishes first + originalA.activateBranch(); + + assertTrue(branches.get() <= 6, "Repeated injection must stop before the test's safety limit"); + ArgumentCaptor message = ArgumentCaptor.forClass(String.class); + verify(logger, atLeast(1)).warn(any(Throwable.class), message.capture()); + // the warning describes the parts' locations and the active context chain, since + // the stack cannot show context computations that already returned + assertTrue(message.getValue().contains("partA") && message.getValue().contains("partB"), message.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ + assertTrue(message.getValue().contains("(window: "), message.getValue()); //$NON-NLS-1$ + assertTrue(message.getValue().contains(", perspective: "), message.getValue()); //$NON-NLS-1$ + assertTrue(message.getValue().contains("; active context chain: "), message.getValue()); //$NON-NLS-1$ + assertEquals(f.partA(), windowContext.get(IServiceConstants.ACTIVE_PART)); + assertEquals(f.partA(), f.service().getActivePart()); + // the previously active part is deactivated first; the nested partB activation + // that was announced is withdrawn again, and partA is announced last + assertEquals("-partC", notifications.get(0), notifications.toString()); //$NON-NLS-1$ + assertTrue(notifications.indexOf("+partB") < notifications.lastIndexOf("-partB"), //$NON-NLS-1$ //$NON-NLS-2$ + notifications.toString()); + assertEquals(List.of("-partB", "+partA"), //$NON-NLS-1$ //$NON-NLS-2$ + notifications.subList(notifications.size() - 2, notifications.size()), notifications.toString()); + } finally { + f.service().removePartListener(listener); + f.partA().setContext(originalA); + f.partB().setContext(originalB); + windowContext.remove(Logger.class); + } + } + + private static void activateBranchThrough(IEclipseContext intermediateContext, IEclipseContext partContext, + AtomicInteger branches) { + // Limit the unfixed implementation as well, so a regression fails instead of + // overflowing the stack or hanging the UI test harness. + if (branches.incrementAndGet() <= 6) { + intermediateContext.activateBranch(); + } + partContext.activateBranch(); + } + + /** + * Makes activating the branch of partA pass through the branch of partB and vice + * versa, so the context reports the other part as an intermediate ACTIVE_PART. + * + * @return restores the original part contexts + */ + private static Runnable installContextBranchCycle(ActivationFixture f, AtomicInteger branches) { + IEclipseContext originalA = f.partA().getContext(); + IEclipseContext originalB = f.partB().getContext(); + IEclipseContext contextA = mock(IEclipseContext.class, delegatesTo(originalA)); + IEclipseContext contextB = mock(IEclipseContext.class, delegatesTo(originalB)); + doAnswer(_ -> { + activateBranchThrough(originalB, originalA, branches); + return null; + }).when(contextA).activateBranch(); + doAnswer(_ -> { + activateBranchThrough(originalA, originalB, branches); + return null; + }).when(contextB).activateBranch(); + f.partA().setContext(contextA); + f.partB().setContext(contextB); + return () -> { + f.partA().setContext(originalA); + f.partB().setContext(originalB); + }; + } + + @Test + public void testActivateBranch_ListenerOfCorrectiveActivationCanSwitchContextBranch() { + ActivationFixture f = createActivationFixture(); + f.service().activate(f.partC()); + IEclipseContext windowContext = f.window().getContext(); + windowContext.set(Logger.class, mock(Logger.class)); + IEclipseContext originalA = f.partA().getContext(); + IEclipseContext contextC = f.partC().getContext(); + AtomicInteger branches = new AtomicInteger(); + Runnable restore = installContextBranchCycle(f, branches); + AtomicBoolean partBDeactivated = new AtomicBoolean(); + AtomicBoolean armed = new AtomicBoolean(true); + IPartListener listener = new PartListener() { + @Override + public void partActivated(MPart part) { + // the corrective activation of partA is the one that follows the + // deactivation of partB; its listener switches to the branch of partC + if (part == f.partA() && partBDeactivated.get() && armed.getAndSet(false)) { + contextC.activateBranch(); + } + } + + @Override + public void partDeactivated(MPart part) { + if (part == f.partB()) { + partBDeactivated.set(true); + } + } + }; + f.service().addPartListener(listener); + try { + originalA.activateBranch(); + + assertTrue(branches.get() <= 6, "Repeated injection must stop before the test's safety limit"); + assertFalse(armed.get(), "The corrective activation must notify partA"); + assertEquals(f.partC(), windowContext.get(IServiceConstants.ACTIVE_PART)); + assertEquals(f.partC(), f.service().getActivePart()); + } finally { + f.service().removePartListener(listener); + restore.run(); + windowContext.remove(Logger.class); + } + } + + @Test + public void testActivate_ListenerEnteringContextInjectionCycleKeepsActivePartInSync() { + ActivationFixture f = createActivationFixture(); + f.service().activate(f.partB()); + IEclipseContext windowContext = f.window().getContext(); + windowContext.set(Logger.class, mock(Logger.class)); + IEclipseContext originalA = f.partA().getContext(); + AtomicInteger branches = new AtomicInteger(); + Runnable restore = installContextBranchCycle(f, branches); + AtomicBoolean armed = new AtomicBoolean(true); + IPartListener listener = new PartListener() { + @Override + public void partActivated(MPart part) { + // a listener of an explicit activation enters the cycle through the context + if (part == f.partC() && armed.getAndSet(false)) { + originalA.activateBranch(); + } + } + }; + f.service().addPartListener(listener); + try { + f.service().activate(f.partC()); + + assertTrue(branches.get() <= 6, "Repeated injection must stop before the test's safety limit"); + assertFalse(armed.get(), "The explicit activation must notify partC"); + assertEquals(f.partA(), windowContext.get(IServiceConstants.ACTIVE_PART)); + assertEquals(f.partA(), f.service().getActivePart()); + } finally { + f.service().removePartListener(listener); + restore.run(); + windowContext.remove(Logger.class); + } + } + + @Test + public void testListenerOpensThenHidesTemporaryPart() { + testListenerReturnsToOriginalPart(true); + } + + @Test + public void testListenerCanActivateDistinctContextBranch() { + ActivationFixture f = createActivationFixture(); + f.service().activate(f.partC()); + AtomicBoolean armed = new AtomicBoolean(true); + PartListener listener = new PartListener() { + @Override + public void partActivated(MPart part) { + super.partActivated(part); + if (part == f.partA() && armed.getAndSet(false)) { + f.partB().getContext().activateBranch(); + } + } + }; + f.service().addPartListener(listener); + try { + f.service().activate(f.partA()); + assertEquals(f.partB(), f.service().getActivePart()); + assertEquals(f.partB(), f.window().getContext().get(IServiceConstants.ACTIVE_PART)); + assertEquals(List.of(f.partA(), f.partB()), listener.getActivatedParts()); + f.service().activate(f.partA()); + assertEquals(f.partA(), f.service().getActivePart()); + } finally { + f.service().removePartListener(listener); + } + } + + @Test + public void testDeactivationListenerObservesPreviousActivePart() { + ActivationFixture f = createActivationFixture(); + AtomicBoolean observedPreviousPart = new AtomicBoolean(); + PartListener listener = new PartListener() { + @Override + public void partDeactivated(MPart part) { + observedPreviousPart.set(f.service().getActivePart() == part); + } + }; + f.service().addPartListener(listener); + try { + f.partA().getContext().deactivate(); + assertTrue(observedPreviousPart.get()); + assertNull(f.service().getActivePart()); + assertNull(f.window().getContext().get(IServiceConstants.ACTIVE_PART)); + } finally { + f.service().removePartListener(listener); + } + } + + private void testListenerReturnsToOriginalPart(boolean hideTemporaryPart) { + ActivationFixture f = createActivationFixture(); + f.service().activate(f.partC()); + AtomicBoolean armed = new AtomicBoolean(true); + AtomicBoolean notifiedBeforeReturn = new AtomicBoolean(); + PartListener listener = new PartListener() { + @Override + public void partActivated(MPart part) { + super.partActivated(part); + if (part == f.partA() && armed.getAndSet(false)) { + f.service().activate(f.partB()); + notifiedBeforeReturn.set(getActivatedParts().contains(f.partB())); + if (hideTemporaryPart) { + f.service().hidePart(f.partB()); + } else { + f.service().activate(f.partA()); + } + } + } + }; + f.service().addPartListener(listener); + try { + f.service().activate(f.partA()); + assertEquals(f.partA(), f.service().getActivePart()); + assertEquals(f.partA(), f.window().getContext().get(IServiceConstants.ACTIVE_PART)); + assertTrue(notifiedBeforeReturn.get(), "Nested listeners must run before activate returns"); + assertEquals(List.of(f.partA(), f.partB(), f.partA()), listener.getActivatedParts()); + if (hideTemporaryPart) { + assertFalse(f.partB().isToBeRendered()); + } + } finally { + f.service().removePartListener(listener); + } + } + @Test public void testFindPart_PartInWindow() { createApplication("partId"); From 4c95ade12dfc426202c78462b0ea3d6552946d14 Mon Sep 17 00:00:00 2001 From: Heiko Klare Date: Mon, 9 Nov 2026 19:47:33 +0100 Subject: [PATCH 38/52] Draw a light border around the split editor area in the macOS theme The black border was introduced when the default Light theme was exchanged. That exchange dropped the CTabFolder.MArea rule from e4_default_mac.css. When the editor area holds several stacks, it is wrapped in a bordered CTabFolder, and CTabRendering paints the unset outer keyline in black. Restore the rule with the current theme colors: the keyline color of the editor stacks for the border and the secondary background for the area. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/4552 Assisted-by: Claude Opus 5.5 --- bundles/org.eclipse.ui.themes/css/e4_default_mac.css | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bundles/org.eclipse.ui.themes/css/e4_default_mac.css b/bundles/org.eclipse.ui.themes/css/e4_default_mac.css index 916ec9463c5..73cf0688169 100644 --- a/bundles/org.eclipse.ui.themes/css/e4_default_mac.css +++ b/bundles/org.eclipse.ui.themes/css/e4_default_mac.css @@ -94,6 +94,15 @@ ColorDefinition#org-eclipse-ui-workbench-INACTIVE_TAB_TEXT_COLOR { background-color: '#org-eclipse-ui-workbench-SECONDARY_BACKGROUND'; } +CTabFolder.MArea { + background-color: '#org-eclipse-ui-workbench-SECONDARY_BACKGROUND'; + swt-selected-tab-fill: '#org-eclipse-ui-workbench-SECONDARY_BACKGROUND'; + swt-unselected-tabs-color: '#org-eclipse-ui-workbench-SECONDARY_BACKGROUND'; + swt-outer-keyline-color: '#org-eclipse-ui-workbench-INACTIVE_TAB_OUTER_KEYLINE_COLOR'; + swt-inner-keyline-color: '#org-eclipse-ui-workbench-INACTIVE_TAB_OUTER_KEYLINE_COLOR'; + swt-tab-outline: '#org-eclipse-ui-workbench-INACTIVE_TAB_OUTLINE_COLOR'; +} + CTabFolder Canvas { background-color: '#org-eclipse-ui-workbench-SECONDARY_BACKGROUND'; } From ec474c407a1807019cb73ec0fdf931a3a62e520e Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Thu, 5 Nov 2026 11:14:36 +0100 Subject: [PATCH 39/52] Ignore focus changes while a part is being activated MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A focus event during tab selection or context activation could start a competing activation. The outer activation then flipped the context back and re-entered through setPart, up to a StackOverflowError on macOS. Context echoes through setPart are ignored meanwhile, and listeners are not told a part was deactivated before it was announced as activated. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../swt/ContributedPartRenderer.java | 8 + .../internal/workbench/PartServiceImpl.java | 62 ++++- .../org/eclipse/e4/ui/tests/UIAllTests.java | 2 + .../tests/application/EPartServiceTest.java | 111 ++++++++ .../workbench/PartActivationFocusTest.java | 252 ++++++++++++++++++ .../tests/workbench/PartOnTopManagerTest.java | 5 +- 6 files changed, 430 insertions(+), 10 deletions(-) create mode 100644 tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartActivationFocusTest.java diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/ContributedPartRenderer.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/ContributedPartRenderer.java index 2bcc6dbff64..f0414cdf634 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/ContributedPartRenderer.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/ContributedPartRenderer.java @@ -21,11 +21,13 @@ import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.core.services.contributions.IContributionFactory; import org.eclipse.e4.core.services.log.Logger; +import org.eclipse.e4.ui.internal.workbench.PartServiceImpl; import org.eclipse.e4.ui.model.application.ui.MUIElement; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.e4.ui.model.application.ui.menu.MMenu; import org.eclipse.e4.ui.model.application.ui.menu.MToolBar; import org.eclipse.e4.ui.workbench.IPresentationEngine; +import org.eclipse.e4.ui.workbench.modeling.EPartService; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.graphics.Point; @@ -58,6 +60,12 @@ public class ContributedPartRenderer extends SWTPartRenderer { // actually bound to a model element MPart part = (MPart) event.widget.getData(OWNING_ME); if (part != null) { + // focus moved by an activation in progress, which sets the focus itself afterwards + IEclipseContext context = getContext(part); + if (context != null && context.get(EPartService.class) instanceof PartServiceImpl ps + && ps.isActivating()) { + return; + } try { partToActivate = part; activate(partToActivate); diff --git a/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java b/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java index ee955da4a61..2be5153db57 100644 --- a/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java +++ b/bundles/org.eclipse.e4.ui.workbench/src/org/eclipse/e4/ui/internal/workbench/PartServiceImpl.java @@ -188,6 +188,19 @@ private MPart toPart(MStackElement stackElement) { private MPart activePart; + /** + * Part whose activation is currently showing its tab and activating its + * context branch; focus changes caused by that must not start a competing + * activation. + */ + private MPart partBeingActivated; + + /** Part made active whose partActivated notification has not been sent yet. */ + private MPart unannouncedPart; + + /** Whether an activation is showing its part or activating its context branch. */ + private boolean showingPart; + private final ListenerList listeners = new ListenerList<>(); private boolean constructed = false; @@ -209,6 +222,10 @@ private void log(String unidentifiedMessage, String identifiedMessage, String id @Inject void setPart(@Optional @Named(IServiceConstants.ACTIVE_PART) MPart p) { + // the activation in progress sets the active part of the context itself + if (showingPart) { + return; + } if (activePart != p) { if (p != null) { MPerspective persp = modelService.getPerspectiveFor(p); @@ -697,7 +714,7 @@ public void activate(MPart part, boolean requiresFocus) { private void activate(MPart part, boolean requiresFocus, boolean activateBranch) { if (part == null) { - if (constructed && activePart != null) { + if (constructed && activePart != null && activePart != unannouncedPart) { if (Policy.DEBUG_FOCUS) { Activator.trace(Policy.DEBUG_FOCUS_FLAG, "Deactivated: " + activePart, null);//$NON-NLS-1$ } @@ -753,9 +770,12 @@ private void activate(MPart part, boolean requiresFocus, boolean activateBranch) } MPart lastActivePart = activePart; + MPart lastUnannounced = unannouncedPart; activePart = part; + unannouncedPart = part; - if (constructed && lastActivePart != null && lastActivePart != activePart) { + if (constructed && lastActivePart != null && lastActivePart != activePart + && lastActivePart != lastUnannounced) { if (Policy.DEBUG_FOCUS) { Activator.trace(Policy.DEBUG_FOCUS_FLAG, "Deactivated: " + lastActivePart, null);//$NON-NLS-1$ } @@ -770,10 +790,28 @@ private void activate(MPart part, boolean requiresFocus, boolean activateBranch) // unwanted bundle activation recordStackActivation(part); - delegateBringToTop(part); - window.getParent().setSelectedElement(window); - - partActivationHistory.activate(part, activateBranch); + MPart outer = partBeingActivated; + boolean outerShowing = showingPart; + // only an activation that sets the focus afterwards may ignore focus changes + partBeingActivated = requiresFocus ? part : null; + showingPart = true; + try { + delegateBringToTop(part); + window.getParent().setSelectedElement(window); + // a nested explicit activation has superseded this one; activating our + // branch now would flip the context back and restart this activation + if (activePart != part) { + return; + } + partActivationHistory.activate(part, activateBranch); + } finally { + partBeingActivated = outer; + showingPart = outerShowing; + } + // the superseding activation has already focused and notified its part + if (activePart != part) { + return; + } if (requiresFocus) { IEclipseContext context = part.getContext(); @@ -786,9 +824,13 @@ private void activate(MPart part, boolean requiresFocus, boolean activateBranch) // store the activation time to sort the parts in MRU order part.getTransientData().put(PART_ACTIVATION_TIME, Long.valueOf(System.currentTimeMillis())); + unannouncedPart = null; firePartActivated(part); UIEvents.publishEvent(UIEvents.UILifeCycle.ACTIVATE, part); } finally { + if (unannouncedPart == part) { + unannouncedPart = null; + } if (contextService != null) { contextService.deferUpdates(false); } @@ -806,6 +848,14 @@ private void delegateBringToTop(MPart part) { createElement(part); } + /** + * Whether an activation is currently showing its part or activating its context + * branch; focus events fired by that must not start a competing activation. + */ + public boolean isActivating() { + return partBeingActivated != null; + } + /** * Records the specified parent part's selected element in the activation history if the parent * is a stack. diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/UIAllTests.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/UIAllTests.java index 9a9ef8c92ac..ce527d3c083 100644 --- a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/UIAllTests.java +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/UIAllTests.java @@ -46,6 +46,7 @@ import org.eclipse.e4.ui.tests.workbench.ModelAssemblerFragmentOrderingTests; import org.eclipse.e4.ui.tests.workbench.ModelAssemblerTests; import org.eclipse.e4.ui.tests.workbench.ModelServiceImplTest; +import org.eclipse.e4.ui.tests.workbench.PartActivationFocusTest; import org.eclipse.e4.ui.tests.workbench.PartFocusTest; import org.eclipse.e4.ui.tests.workbench.PartOnTopManagerTest; import org.eclipse.e4.ui.tests.workbench.PartRenderingEngineTests; @@ -74,6 +75,7 @@ Bug320857Test.class, PartOnTopManagerTest.class, PartRenderingEngineTests.class, + PartActivationFocusTest.class, SashRendererTest.class, MApplicationCommandAccessTest.class, MMenuItemTest.class, diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java index bb3254b2ddf..a0b67a4fc6d 100644 --- a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/application/EPartServiceTest.java @@ -27,6 +27,7 @@ import java.util.Iterator; import java.util.List; import org.eclipse.e4.core.contexts.IEclipseContext; +import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.e4.ui.di.Focus; import org.eclipse.e4.ui.internal.workbench.PartServiceImpl; import org.eclipse.e4.ui.internal.workbench.PartServiceSaveHandler; @@ -45,6 +46,7 @@ import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.e4.ui.tests.model.test.util.TestException; import org.eclipse.e4.ui.tests.workbench.TargetedView; +import org.eclipse.e4.ui.workbench.UIEvents; import org.eclipse.e4.ui.workbench.modeling.EModelService; import org.eclipse.e4.ui.workbench.modeling.EPartService; import org.eclipse.e4.ui.workbench.modeling.EPartService.PartState; @@ -53,6 +55,7 @@ import org.eclipse.e4.ui.workbench.modeling.ISaveHandler.Save; import org.eclipse.emf.common.notify.Notifier; import org.junit.jupiter.api.Test; +import org.osgi.service.event.EventHandler; public class EPartServiceTest extends UITest { @@ -1228,6 +1231,114 @@ public void testActivate_Bug326300() { assertEquals(partB, windowA.getContext().get(EPartService.class).getActivePart()); } + @Test + public void testActivate_RedirectDuringSelectionDoesNotDeactivateUnannouncedPart() { + createApplication("partA", "partB", "partC"); + MWindow window = application.getChildren().get(0); + MPartStack partStack = (MPartStack) window.getChildren().get(0); + MPart partA = (MPart) partStack.getChildren().get(0); + MPart partB = (MPart) partStack.getChildren().get(1); + MPart partC = (MPart) partStack.getChildren().get(2); + getEngine().createGui(window); + + EPartService partService = window.getContext().get(EPartService.class); + partService.activate(partC); + PartListener partListener = new PartListener(); + partService.addPartListener(partListener); + + // selecting partA redirects the activation to partB before partA is announced + IEventBroker broker = window.getContext().get(IEventBroker.class); + EventHandler handler = event -> { + if (event.getProperty(UIEvents.EventTags.NEW_VALUE) == partA) { + partService.activate(partB); + } + }; + broker.subscribe(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT, handler); + try { + partService.activate(partA); + } finally { + broker.unsubscribe(handler); + } + + // listeners were never told that partA was activated, so they must not be + // told that it was deactivated either + assertEquals(List.of(partB), partListener.getActivatedParts()); + assertEquals(List.of(partC), partListener.getDeactivatedParts()); + assertEquals(partB, partService.getActivePart()); + } + + @Test + public void testActivate_DeactivationDuringSelectionSupersedesActivation() { + createApplication("partA", "partB", "partC"); + MWindow window = application.getChildren().get(0); + MPartStack partStack = (MPartStack) window.getChildren().get(0); + MPart partA = (MPart) partStack.getChildren().get(0); + MPart partC = (MPart) partStack.getChildren().get(2); + getEngine().createGui(window); + + EPartService partService = window.getContext().get(EPartService.class); + partService.activate(partC); + PartListener partListener = new PartListener(); + partService.addPartListener(partListener); + + // selecting partA deactivates the context of the previously active part, + // which clears the active part through context injection (setPart(null)) + IEventBroker broker = window.getContext().get(IEventBroker.class); + boolean[] armed = { true }; + EventHandler handler = event -> { + if (armed[0] && event.getProperty(UIEvents.EventTags.NEW_VALUE) == partA) { + armed[0] = false; + partC.getContext().deactivate(); + } + }; + broker.subscribe(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT, handler); + try { + partService.activate(partA); + } finally { + broker.unsubscribe(handler); + } + + // the superseded outer activation must neither announce partA a second time + // nor leave the service and the context disagreeing about the active part + long partAActivations = partListener.getActivatedParts().stream().filter(p -> p == partA).count(); + assertTrue(partAActivations <= 1, "partA activated " + partAActivations + " times"); + assertEquals(window.getContext().get(IServiceConstants.ACTIVE_PART), partService.getActivePart()); + } + + @Test + public void testActivate_ListenerActivatesOtherPartDuringSelection() { + createApplication("partA", "partB", "partC"); + MWindow window = application.getChildren().get(0); + MPartStack partStack = (MPartStack) window.getChildren().get(0); + MPart partA = (MPart) partStack.getChildren().get(0); + MPart partB = (MPart) partStack.getChildren().get(1); + MPart partC = (MPart) partStack.getChildren().get(2); + getEngine().createGui(window); + + EPartService partService = window.getContext().get(EPartService.class); + partService.activate(partC); + PartListener partListener = new PartListener(); + partService.addPartListener(partListener); + + // selecting partA always activates partB: the nested activation wins without recursing + IEventBroker broker = window.getContext().get(IEventBroker.class); + EventHandler handler = event -> { + if (event.getProperty(UIEvents.EventTags.NEW_VALUE) == partA) { + partService.activate(partB); + } + }; + broker.subscribe(UIEvents.ElementContainer.TOPIC_SELECTEDELEMENT, handler); + try { + partService.activate(partA); + } finally { + broker.unsubscribe(handler); + } + + assertEquals(List.of(partB), partListener.getActivatedParts()); + assertEquals(partB, partService.getActivePart()); + assertEquals(partB, window.getContext().get(IServiceConstants.ACTIVE_PART)); + } + @Test public void testActivate_Bug371894() { MWindow window = ems.createModelElement(MWindow.class); diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartActivationFocusTest.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartActivationFocusTest.java new file mode 100644 index 00000000000..ec46111be3e --- /dev/null +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartActivationFocusTest.java @@ -0,0 +1,252 @@ +/******************************************************************************* + * Copyright (c) 2026 vogella GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + *******************************************************************************/ +package org.eclipse.e4.ui.tests.workbench; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import jakarta.annotation.PostConstruct; +import jakarta.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import org.eclipse.e4.core.contexts.IEclipseContext; +import org.eclipse.e4.core.contexts.RunAndTrack; +import org.eclipse.e4.ui.di.Focus; +import org.eclipse.e4.ui.internal.workbench.E4Workbench; +import org.eclipse.e4.ui.internal.workbench.swt.E4Application; +import org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine; +import org.eclipse.e4.ui.model.application.MApplication; +import org.eclipse.e4.ui.model.application.ui.basic.MPart; +import org.eclipse.e4.ui.model.application.ui.basic.MPartSashContainer; +import org.eclipse.e4.ui.model.application.ui.basic.MPartStack; +import org.eclipse.e4.ui.model.application.ui.basic.MWindow; +import org.eclipse.e4.ui.services.IServiceConstants; +import org.eclipse.e4.ui.workbench.IWorkbench; +import org.eclipse.e4.ui.workbench.modeling.EModelService; +import org.eclipse.e4.ui.workbench.modeling.EPartService; +import org.eclipse.e4.ui.workbench.modeling.IPartListener; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.tests.harness.util.DisplayHelper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.osgi.framework.FrameworkUtil; + +/** + * A focus change that lands in another part while a part is being activated + * must not start a competing activation. + */ +public class PartActivationFocusTest { + + private IEclipseContext appContext; + private E4Workbench wb; + private EPartService partService; + private MWindow window; + private MPartStack stack; + private MPart partA; + private MPart partB; + private MPart partC; + private MPart lazyPart; + private final List activated = new ArrayList<>(); + + @BeforeEach + public void setUp() { + appContext = E4Application.createDefaultContext(); + appContext.set(IWorkbench.PRESENTATION_URI_ARG, PartRenderingEngine.engineURI); + EModelService ems = appContext.get(EModelService.class); + + window = ems.createModelElement(MWindow.class); + window.setWidth(600); + window.setHeight(400); + MPartSashContainer sash = ems.createModelElement(MPartSashContainer.class); + sash.setHorizontal(true); + window.getChildren().add(sash); + window.setSelectedElement(sash); + stack = ems.createModelElement(MPartStack.class); + MPartStack otherStack = ems.createModelElement(MPartStack.class); + sash.getChildren().add(stack); + sash.getChildren().add(otherStack); + sash.setSelectedElement(stack); + partA = createPart(ems, stack, "A", TextPart.class); + partB = createPart(ems, stack, "B", TextPart.class); + lazyPart = createPart(ems, stack, "lazy", RefocusingPart.class); + partC = createPart(ems, otherStack, "C", TextPart.class); + + MApplication application = ems.createModelElement(MApplication.class); + application.getChildren().add(window); + application.setContext(appContext); + appContext.set(MApplication.class, application); + + wb = new E4Workbench(application, appContext); + wb.createAndRunUI(window); + partService = window.getContext().get(EPartService.class); + partService.activate(partA); + partService.activate(partC); + partService.activate(partB); + processEvents(); + + Shell shell = (Shell) window.getWidget(); + shell.forceActive(); + DisplayHelper.waitForCondition(shell.getDisplay(), 5000, () -> text(partB).isFocusControl()); + // without focus events no competing activation can happen + assumeTrue(text(partB).isFocusControl(), "focus events are not delivered"); + + partService.addPartListener(new IPartListener() { + @Override + public void partActivated(MPart part) { + activated.add(part.getElementId()); + } + + @Override + public void partBroughtToTop(MPart part) { + } + + @Override + public void partDeactivated(MPart part) { + } + + @Override + public void partHidden(MPart part) { + } + + @Override + public void partVisible(MPart part) { + } + }); + } + + @AfterEach + public void tearDown() { + wb.close(); + appContext.dispose(); + } + + @Test + public void testPartCreationRefocusingPreviousPart() { + partService.activate(lazyPart); + processEvents(); + + assertEquals(List.of("lazy"), activated); + assertEquals(lazyPart, partService.getActivePart()); + assertEquals(lazyPart, window.getContext().get(IServiceConstants.ACTIVE_PART)); + assertEquals(lazyPart, stack.getSelectedElement()); + assertTrue(((RefocusingPart) lazyPart.getObject()).text.isFocusControl()); + } + + @Test + public void testFocusStolenDuringContextActivation() { + stealFocusToPartCWhenPartABecomesActive(); + + partService.activate(partA); + processEvents(); + + assertEquals(List.of("A"), activated); + assertEquals(partA, partService.getActivePart()); + assertEquals(partA, window.getContext().get(IServiceConstants.ACTIVE_PART)); + assertTrue(text(partA).isFocusControl()); + } + + @Test + public void testFocusStolenDuringContextActivationWithoutFocusRequest() { + stealFocusToPartCWhenPartABecomesActive(); + + partService.activate(partA, false); + processEvents(); + + // the activation does not touch the focus, so the part owning the focus is active + assertEquals(partC, partService.getActivePart()); + assertEquals(partC, window.getContext().get(IServiceConstants.ACTIVE_PART)); + assertTrue(text(partC).isFocusControl()); + } + + private void stealFocusToPartCWhenPartABecomesActive() { + boolean[] armed = { true }; + window.getContext().runAndTrack(new RunAndTrack() { + @Override + public boolean changed(IEclipseContext context) { + if (armed[0] && context.get(IServiceConstants.ACTIVE_PART) == partA) { + armed[0] = false; + text(partC).setFocus(); + } + return armed[0]; + } + }); + } + + private MPart createPart(EModelService ems, MPartStack parent, String id, Class contribution) { + MPart part = ems.createModelElement(MPart.class); + part.setElementId(id); + part.setLabel(id); + part.setContributionURI( + "bundleclass://" + FrameworkUtil.getBundle(getClass()).getSymbolicName() + '/' + contribution.getName()); + parent.getChildren().add(part); + return part; + } + + private static Text text(MPart part) { + return ((TextPart) part.getObject()).text; + } + + private void processEvents() { + Display display = Display.getCurrent(); + while (display.readAndDispatch()) { + appContext.processWaiting(); + } + } + + public static class TextPart { + @Inject + Composite parent; + Text text; + + @PostConstruct + void create() { + text = new Text(parent, SWT.SINGLE); + } + + @Focus + void focus() { + text.setFocus(); + } + } + + /** + * Like an editor initialized through WorkbenchWindow.run: disables the + * window's controls while working and then gives the focus back to the + * control that had it, which belongs to the previously active part. + */ + public static class RefocusingPart extends TextPart { + @Override + @PostConstruct + void create() { + super.create(); + Shell shell = parent.getShell(); + Control previousFocus = shell.getDisplay().getFocusControl(); + List disabled = new ArrayList<>(); + for (Control child : shell.getChildren()) { + if (child.isEnabled()) { + child.setEnabled(false); + disabled.add(child); + } + } + disabled.forEach(child -> child.setEnabled(true)); + if (previousFocus != null) { + previousFocus.forceFocus(); + } + } + } +} diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartOnTopManagerTest.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartOnTopManagerTest.java index a02d4a4203f..4e31422c85f 100644 --- a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartOnTopManagerTest.java +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/tests/workbench/PartOnTopManagerTest.java @@ -299,11 +299,8 @@ public void test_PlaceholderOnTopPerspectiveSwitch() { EPartService partService = window.getContext().get(EPartService.class); partService.switchPerspective(secondPerspective); - // TODO this might fail once - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=490780 is fixed - assertTrue(isPartOnTop(sharedPart)); + // which element of the stack is selected here depends on where the focus was assertTrue(isPartOnTop(secondPerspectiveOnTopPart)); - assertFalse(isPartOnTop(secondPart)); secondPerspectivePartStack.setSelectedElement(secondPerspectivePartStackPlaceholder); From 60aa35a79ee435cef140dffa3c7fef7f5f9e6f62 Mon Sep 17 00:00:00 2001 From: Deepika Udayagiri Date: Tue, 27 Oct 2026 11:30:34 +0530 Subject: [PATCH 40/52] Make sorting in FilteredList and TwoPaneElementSelector stable --- .../ui/dialogs/TwoArrayQuickSorter.java | 77 ++++---- .../TwoPaneElementSelectorOrderTest.java | 180 ++++++++++++++++++ .../ui/tests/dialogs/UIAutomatedSuite.java | 5 +- 3 files changed, 221 insertions(+), 41 deletions(-) create mode 100644 tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/TwoPaneElementSelectorOrderTest.java diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/dialogs/TwoArrayQuickSorter.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/dialogs/TwoArrayQuickSorter.java index c73d8402c90..7ba94321573 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/dialogs/TwoArrayQuickSorter.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/dialogs/TwoArrayQuickSorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -17,8 +17,8 @@ import org.eclipse.core.runtime.Assert; /** - * Quick sort to sort key-value pairs. The keys and arrays are specified in - * separate arrays. + * Stable sort to sort key-value pairs. The keys and values are specified in + * separate arrays. Elements with equal keys keep their relative order. * * @since 2.0 */ @@ -64,7 +64,8 @@ public TwoArrayQuickSorter(Comparator comparator) { } /** - * Sorts keys and values in parallel. + * Sorts keys and values in parallel. The sort is stable: values whose keys + * compare as equal keep their relative order. * * @param keys the keys to use for sorting. * @param values the values associated with the keys. @@ -79,47 +80,47 @@ public void sort(Object[] keys, Object[] values) { return; } - internalSort(keys, values, 0, keys.length - 1); + mergeSort(keys, values, new Object[keys.length / 2], new Object[keys.length / 2], 0, keys.length); } - private void internalSort(Object[] keys, Object[] values, int left, int right) { - int original_left = left; - int original_right = right; + /* + * Sorts keys[low, high) and values[low, high). The buffers must hold at least + * half of the elements; only the left run is copied into them when merging. + */ + private void mergeSort(Object[] keys, Object[] values, Object[] keyBuffer, Object[] valueBuffer, int low, + int high) { + if (high - low < 2) { + return; + } - Object mid = keys[(left + right) / 2]; - do { - while (fComparator.compare(keys[left], mid) < 0) { - left++; - } + int mid = (low + high) >>> 1; + mergeSort(keys, values, keyBuffer, valueBuffer, low, mid); + mergeSort(keys, values, keyBuffer, valueBuffer, mid, high); - while (fComparator.compare(mid, keys[right]) < 0) { - right--; - } + if (fComparator.compare(keys[mid - 1], keys[mid]) <= 0) { + return; // already in order + } - if (left <= right) { - swap(keys, left, right); - swap(values, left, right); - left++; - right--; + int leftCount = mid - low; + System.arraycopy(keys, low, keyBuffer, 0, leftCount); + System.arraycopy(values, low, valueBuffer, 0, leftCount); + int left = 0; + int right = mid; + int target = low; + while (left < leftCount && right < high) { + // take from the right run only if strictly smaller, to keep the sort stable + if (fComparator.compare(keys[right], keyBuffer[left]) < 0) { + keys[target] = keys[right]; + values[target++] = values[right++]; + } else { + keys[target] = keyBuffer[left]; + values[target++] = valueBuffer[left++]; } - } while (left <= right); - - if (original_left < right) { - internalSort(keys, values, original_left, right); } - - if (left < original_right) { - internalSort(keys, values, left, original_right); + // what is left of the right run is already in its place + while (left < leftCount) { + keys[target] = keyBuffer[left]; + values[target++] = valueBuffer[left++]; } } - - /* - * Swaps x[a] with x[b]. - */ - private static final void swap(Object x[], int a, int b) { - Object t = x[a]; - x[a] = x[b]; - x[b] = t; - } - } diff --git a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/TwoPaneElementSelectorOrderTest.java b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/TwoPaneElementSelectorOrderTest.java new file mode 100644 index 00000000000..dbb5ef50d08 --- /dev/null +++ b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/TwoPaneElementSelectorOrderTest.java @@ -0,0 +1,180 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.dialogs; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableItem; +import org.eclipse.ui.dialogs.FilteredList; +import org.eclipse.ui.dialogs.TwoPaneElementSelector; +import org.eclipse.ui.tests.harness.util.DisplayHelper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Tests the order of the entries of {@link TwoPaneElementSelector}. The sorting + * of the lists must be stable, so elements that are folded into one entry of + * the upper list keep their order when the comparator of the lower list treats + * all of them as equal. Otherwise, both lists are sorted ignoring the case. + */ +public class TwoPaneElementSelectorOrderTest { + + /** An element with the label of the upper list and the one of the lower list. */ + private record Entry(String label, String qualifier) { + } + + private Shell parent; + + private TwoPaneElementSelector dialog; + + @AfterEach + public void doTearDown() { + if (dialog != null) { + dialog.close(); + dialog = null; + } + if (parent != null) { + parent.dispose(); + parent = null; + } + } + + /** + * Three elements with the same label are folded into one entry of the upper + * list. The lower list must show them in the order in which they were passed to + * the dialog, whatever the position of that group among the other elements is. + */ + @Test + public void testLowerListKeepsOrderOfFoldedElements() { + List others = List.of(new Entry("component.xml", "component.xml"), new Entry("plugin.xml", "plugin.xml"), + new Entry("settings.ini", "settings.ini"), new Entry("settings.xml", "settings.xml")); + List folded = List.of(new Entry("KeyUser.java (3 matches)", "Line 12"), + new Entry("KeyUser.java (3 matches)", "Line 28"), new Entry("KeyUser.java (3 matches)", "Line 29")); + + for (int position = 0; position <= others.size(); position++) { + List entries = new ArrayList<>(others); + entries.addAll(position, folded); + + // The same as the Ctrl+Click dialog of the properties file editor: keep the order + openDialog(entries, (_, _) -> 0, folded.get(0)); + List lowerList = readTable(findTable(dialog.getShell(), false), folded.size()); + + assertEquals(Arrays.asList("Line 12", "Line 28", "Line 29"), lowerList, + "Wrong order of the lower list when the group is at index " + position); + doTearDown(); + } + } + + /** + * Without a comparator for the lower list, both lists are sorted ignoring the + * case, and elements with the same label are folded into one entry. + */ + @Test + public void testListsAreSortedIgnoringCase() { + List others = List.of(new Entry("beta", "b"), new Entry("Alpha", "a"), new Entry("gamma", "g"), + new Entry("alpha2", "a2")); + List folded = List.of(new Entry("delta", "b"), new Entry("delta", "C"), new Entry("delta", "a")); + + for (int position = 0; position <= others.size(); position++) { + List entries = new ArrayList<>(others); + entries.addAll(position, folded); + + openDialog(entries, null, folded.get(0)); + List lowerList = readTable(findTable(dialog.getShell(), false), folded.size()); + List upperList = readTable(findTable(dialog.getShell(), true), 5); + + assertEquals(Arrays.asList("Alpha", "alpha2", "beta", "delta", "gamma"), upperList, + "Wrong order of the upper list when the group is at index " + position); + assertEquals(Arrays.asList("a", "b", "C"), lowerList, + "Wrong order of the lower list when the group is at index " + position); + doTearDown(); + } + } + + /** + * Opens the dialog with the given elements. + * + * @param lowerComparator comparator of the lower list, or null for + * the default + * @param selected the element to select initially + */ + private void openDialog(List entries, Comparator lowerComparator, Entry selected) { + parent = new Shell(Display.getDefault()); + dialog = new TwoPaneElementSelector(parent, new LabelProvider() { + @Override + public String getText(Object element) { + return ((Entry) element).label(); + } + }, new LabelProvider() { + @Override + public String getText(Object element) { + return ((Entry) element).qualifier(); + } + }); + if (lowerComparator != null) { + dialog.setLowerListComparator(lowerComparator); + } + dialog.setElements(entries.toArray()); + // Without an initial selection, the first row of the upper list is selected, and + // this is not the folded group. Select the group, as the user does. + dialog.setInitialSelections(selected); + dialog.setBlockOnOpen(false); + dialog.open(); + } + + /** Waits until the table has the expected number of rows and returns their texts. */ + private static List readTable(Table table, int expectedCount) { + assertNotNull(table, "The list was not found"); + // The lists are filled by a UI job, so wait until the group is selected + DisplayHelper.waitAndAssertCondition(Display.getDefault(), + () -> assertEquals(expectedCount, table.getItemCount(), "The list was not filled")); + + List result = new ArrayList<>(); + for (TableItem item : table.getItems()) { + result.add(item.getText()); + } + return result; + } + + /** + * Returns the table of the upper list, which is part of the {@link FilteredList}, + * or the table of the lower list, which is the only other table. + */ + private static Table findTable(Control control, boolean upper) { + if (control instanceof Table table && (table.getParent() instanceof FilteredList) == upper) { + return table; + } + if (control instanceof Composite composite) { + for (Control child : composite.getChildren()) { + Table found = findTable(child, upper); + if (found != null) { + return found; + } + } + } + return null; + } +} diff --git a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/UIAutomatedSuite.java b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/UIAutomatedSuite.java index 2c21179cf3a..d7d1e7870f1 100644 --- a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/UIAutomatedSuite.java +++ b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/dialogs/UIAutomatedSuite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -15,7 +15,6 @@ package org.eclipse.ui.tests.dialogs; import org.eclipse.ui.tests.compare.UIComparePreferencesAuto; - import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; @@ -25,7 +24,7 @@ DeprecatedUIPreferencesAuto.class, UIMessageDialogsAuto.class, UINewWorkingSetWizardAuto.class, UIEditWorkingSetWizardAuto.class, SearchPatternAuto.class, InfixSearchPatternAuto.class, UIFilteredResourcesSelectionDialogAuto.class, - TreeManagerTest.class, ContainerCheckedTreeViewerTest.class }) + TreeManagerTest.class, ContainerCheckedTreeViewerTest.class, TwoPaneElementSelectorOrderTest.class }) public class UIAutomatedSuite { } From 10992953e5ad597c203da662d78ca920866a0431 Mon Sep 17 00:00:00 2001 From: Heiko Klare Date: Tue, 10 Nov 2026 14:33:01 +0100 Subject: [PATCH 41/52] Place the editor onboarding area in the folder's client area With no editor open, an editor stack shows the perspective's onboarding information in an area that covers the empty folder. That area was placed with fixed offsets that assume one tab height and a thin border, so it covered the frame of tab renderers with a different trim, such as the rounded lower corners of a renderer that draws rounded frames, and it was misplaced for other tab heights. The onboarding area now fills exactly the space the folder leaves for its content, so the folder's tabs and frame stay visible for any tab height and renderer. The container is laid out in the folder's client area, which includes the renderer's trim, and is updated on the resize event the folder sends whenever its client area changes. The ONBOARDING_TOP_SPACING and ONBOARDING_SPACING constants are removed, as nothing uses them anymore and the package is exported to friends only. Assisted-by: Claude Opus 5.5 --- .../renderers/swt/StackRenderer.java | 28 ++++++--------- .../renderers/swt/StackRendererTest.java | 36 +++++++++++++------ 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java index a2411f65a1f..677f79b7770 100644 --- a/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java +++ b/bundles/org.eclipse.e4.ui.workbench.renderers.swt/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRenderer.java @@ -189,17 +189,6 @@ public class StackRenderer extends LazyStackRenderer { // Minimum characters in for stacks inside the shared area private static int MIN_EDITOR_CHARS = 15; - /** - * Top spacing for onboarding composite, needed so that tabfolder borders are - * shown - */ - public static final int ONBOARDING_TOP_SPACING = 30; - /** - * (Left, Right, Bottom) Spacing for onboarding composite, needed so that - * tabfolder borders are shown - */ - public static final int ONBOARDING_SPACING = 2; - /** * The threshold to show the onbarding image. If tabfolder height gets below * this threshold, the image is hidden. @@ -883,7 +872,8 @@ private void createOnboardingControls(CTabFolder tabFolder) { WidgetFactory.label(SWT.NONE).foreground(color).supplyLayoutData(gridDataFactory::create) .data(ID, ONBOARDING_TEXT).create(onboardingComposite); - onBoardingContainer.setLocation(ONBOARDING_SPACING, ONBOARDING_TOP_SPACING); + // CTabFolder sends a resize event whenever its client area changes, also when + // the tab height or the renderer's trim changes Consumer sizeUpdate = e -> setOnboardingControlSize(tabFolder, onBoardingContainer, onboardingComposite, onboardingImage); tabFolder.addControlListener(ControlListener.controlResizedAdapter(sizeUpdate)); @@ -912,13 +902,15 @@ private void setOnboardingControlSize(CTabFolder tabFolder, Composite onBoarding if (!compositeVisible) { onBoarding.setVisible(true); } - Rectangle folderBounds = tabFolder.getBounds(); - int width = folderBounds.width - 2 * ONBOARDING_SPACING; - int height = folderBounds.height - ONBOARDING_TOP_SPACING - ONBOARDING_SPACING; - if (!new Point(width, height).equals(onBoarding.getSize())) { - onBoarding.setSize(width, height); + // The client area leaves out the tabs and the frame the folder's renderer + // draws, so the onboarding area does not cover them + Rectangle clientArea = tabFolder.getClientArea(); + Rectangle bounds = new Rectangle(clientArea.x, clientArea.y, Math.max(0, clientArea.width), + Math.max(0, clientArea.height)); + if (!bounds.equals(onBoarding.getBounds())) { + onBoarding.setBounds(bounds); - boolean showImage = height > ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD; + boolean showImage = bounds.height > ONBOARDING_SHOW_IMAGE_HEIGHT_THRESHOLD; if (imageVisible != showImage || showComposite != compositeVisible) { onBoardingImage.setVisible(showImage); ((GridData) onBoardingImage.getLayoutData()).exclude = !showImage; diff --git a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRendererTest.java b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRendererTest.java index 2a7d7831d50..cb50e6a2f9b 100644 --- a/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRendererTest.java +++ b/tests/org.eclipse.e4.ui.tests/src/org/eclipse/e4/ui/workbench/renderers/swt/StackRendererTest.java @@ -59,6 +59,7 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Widget; +import org.eclipse.ui.tests.harness.util.DisplayHelper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -422,16 +423,33 @@ public void testOnboardingRenderedWithCorrectSizeForEditorStack() { assertEquals(4, tabFolder.getChildren().length); Composite outerOnboardingComposite = (Composite) tabFolder.getChildren()[2]; - Rectangle expected = new Rectangle(StackRenderer.ONBOARDING_SPACING, StackRenderer.ONBOARDING_TOP_SPACING, - tabFolder.getSize().x - 2 * StackRenderer.ONBOARDING_SPACING, - tabFolder.getSize().y - StackRenderer.ONBOARDING_TOP_SPACING - StackRenderer.ONBOARDING_SPACING); - assertEquals(expected, outerOnboardingComposite.getBounds()); + assertEquals(tabFolder.getClientArea(), outerOnboardingComposite.getBounds()); Composite innerOnboardingComposite = (Composite) outerOnboardingComposite.getChildren()[0]; assertEquals(2, innerOnboardingComposite.getChildren().length); assertNull(((Label) innerOnboardingComposite.getChildren()[0]).getImage()); assertEquals("", ((Label) innerOnboardingComposite.getChildren()[1]).getText()); } + @Test + public void testOnboardingFollowsClientAreaOfEditorStack() { + PartStackUtil.makeEditorStack(partStack); + + contextRule.createAndRunWorkbench(window); + + CTabFolder tabFolder = (CTabFolder) partStack.getWidget(); + Composite outerOnboardingComposite = (Composite) tabFolder.getChildren()[2]; + Rectangle clientArea = tabFolder.getClientArea(); + assertEquals(clientArea, outerOnboardingComposite.getBounds()); + + // a higher tab row shrinks the client area without resizing the folder + tabFolder.setTabHeight(tabFolder.getTabHeight() + 20); + DisplayHelper.waitForCondition(tabFolder.getDisplay(), 5000, + () -> !clientArea.equals(tabFolder.getClientArea())); + + assertNotEquals(clientArea, tabFolder.getClientArea()); + assertEquals(tabFolder.getClientArea(), outerOnboardingComposite.getBounds()); + } + @Test public void testOnboardingContentFollowsContainerBackground() { PartStackUtil.makeEditorStack(partStack); @@ -551,17 +569,15 @@ public void testOnboardingIsHiddenWhenEditorOpened() { assertEquals(4, tabFolder.getChildren().length); Composite outerOnboardingComposite = (Composite) tabFolder.getChildren()[2]; - Rectangle expected = new Rectangle(StackRenderer.ONBOARDING_SPACING, StackRenderer.ONBOARDING_TOP_SPACING, - tabFolder.getSize().x - 2 * StackRenderer.ONBOARDING_SPACING, - tabFolder.getSize().y - StackRenderer.ONBOARDING_TOP_SPACING - StackRenderer.ONBOARDING_SPACING); - assertEquals(expected, outerOnboardingComposite.getBounds()); + Rectangle clientArea = tabFolder.getClientArea(); + assertEquals(clientArea, outerOnboardingComposite.getBounds()); MPart part1 = ems.createModelElement(MPart.class); partStack.getChildren().add(part1); partStack.setSelectedElement(part1); - expected = new Rectangle(StackRenderer.ONBOARDING_SPACING, StackRenderer.ONBOARDING_TOP_SPACING, 0, 0); - assertEquals(expected, outerOnboardingComposite.getBounds()); + assertFalse(outerOnboardingComposite.getVisible()); + assertEquals(new Rectangle(clientArea.x, clientArea.y, 0, 0), outerOnboardingComposite.getBounds()); } /** From 8510b6eeb815c94cfad992e957fda7e36090639c Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Fri, 16 Oct 2026 07:04:39 +0200 Subject: [PATCH 42/52] Re-apply CSS colors that only match the inherited color MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CSSSWTColorHelper skipped setting a color when the control already reported it, but getBackground() also reports colors inherited from the parent. After a theme switch reset a control that owned a color, the new color was skipped whenever the parent had the same one, so the control owned no color. Children of a Forms Section then painted the Section's title gradient image. The helper now remembers that a control lost its own color on reset, including a color set before styling such as by FormToolkit.adapt, and then applies the new color even if it equals the inherited one. A reset compares the control's color with the inherited one, so the engine resets ancestors first. Controls that never owned a color keep inheriting, so the Section title label still shows the title bar. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../e4/ui/css/swt/dom/CTabFolderElement.java | 2 +- .../e4/ui/css/swt/dom/ControlElement.java | 5 +- .../e4/ui/css/swt/dom/TableItemElement.java | 5 +- .../ui/css/swt/engine/CSSSWTEngineImpl.java | 27 ++++- .../ui/css/swt/helpers/CSSSWTColorHelper.java | 48 ++++++++- .../e4/ui/tests/css/swt/InheritTest.java | 98 +++++++++++++++++++ 6 files changed, 173 insertions(+), 12 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/CTabFolderElement.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/CTabFolderElement.java index 0f2396c147b..90bc1894849 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/CTabFolderElement.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/CTabFolderElement.java @@ -179,7 +179,7 @@ private void resetChildBackground(Control control) { .getData(BACKGROUND_SET_BY_TAB_RENDERER); if (backgroundSetByRenderer != null) { if (control.getBackground() == backgroundSetByRenderer) { - control.setBackground(null); + CSSSWTColorHelper.setBackground(control, null); } control.setData(BACKGROUND_SET_BY_TAB_RENDERER, null); } diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/ControlElement.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/ControlElement.java index b9bf7e1f716..d4ddfb290b3 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/ControlElement.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/ControlElement.java @@ -17,6 +17,7 @@ import org.eclipse.e4.ui.css.core.dom.CSSStylableElement; import org.eclipse.e4.ui.css.core.engine.CSSEngine; +import org.eclipse.e4.ui.css.swt.helpers.CSSSWTColorHelper; import org.eclipse.e4.ui.css.swt.helpers.CSSSWTCursorHelper; import org.eclipse.e4.ui.css.swt.helpers.CSSSWTFontHelper; import org.eclipse.e4.ui.css.swt.properties.GradientBackgroundListener; @@ -160,8 +161,8 @@ public void reset() { control.setForeground(control.getDisplay().getSystemColor( SWT.COLOR_LINK_FOREGROUND)); } else { - control.setBackground(null); - control.setForeground(null); + CSSSWTColorHelper.setBackground(control, null); + CSSSWTColorHelper.setForeground(control, null); } super.reset(); } diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableItemElement.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableItemElement.java index 3d35e5486cf..6f20450e829 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableItemElement.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/dom/TableItemElement.java @@ -17,6 +17,7 @@ import org.eclipse.e4.ui.css.core.dom.CSSStylableElement; import org.eclipse.e4.ui.css.core.engine.CSSEngine; +import org.eclipse.e4.ui.css.swt.helpers.CSSSWTColorHelper; import org.eclipse.e4.ui.css.swt.helpers.CSSSWTFontHelper; import org.eclipse.e4.ui.css.swt.helpers.CSSSWTImageHelper; import org.eclipse.swt.widgets.Table; @@ -58,8 +59,8 @@ public void reset() { Table parent = tableItem.getParent(); if (!parent.isDisposed()) { - parent.setForeground(null); - parent.setBackground(null); + CSSSWTColorHelper.setForeground(parent, null); + CSSSWTColorHelper.setBackground(parent, null); CSSSWTFontHelper.restoreDefaultFont(parent); } diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/engine/CSSSWTEngineImpl.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/engine/CSSSWTEngineImpl.java index 7adcce44634..881dea5d7dd 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/engine/CSSSWTEngineImpl.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/engine/CSSSWTEngineImpl.java @@ -14,6 +14,11 @@ *******************************************************************************/ package org.eclipse.e4.ui.css.swt.engine; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.RegistryFactory; import org.eclipse.e4.ui.css.core.dom.CSSStylableElement; @@ -34,6 +39,8 @@ import org.eclipse.e4.ui.css.swt.resources.SWTResourcesRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Widget; @@ -118,18 +125,32 @@ protected boolean isStylable(Widget widget) { @Override public void reset() { + // ancestors first, since a control's reset compares its color with the inherited one + Map> elementsByDepth = new TreeMap<>(); for (CSSElementContext elementContext : getElementsContext().values()) { Element element = elementContext.getElement(); - if (element instanceof WidgetElement - && isApplicableToReset((WidgetElement) element)) { - ((WidgetElement) element).reset(); + if (element instanceof WidgetElement widgetElement && isApplicableToReset(widgetElement)) { + elementsByDepth.computeIfAbsent(depth(widgetElement), d -> new ArrayList<>()).add(widgetElement); } } + elementsByDepth.values().forEach(elements -> elements.forEach(WidgetElement::reset)); getResourcesRegistry().dispose(); super.reset(); } + /** Items depend on their parent control and go after all controls. */ + private static int depth(WidgetElement element) { + if (!(element.getNativeWidget() instanceof Control control)) { + return Integer.MAX_VALUE; + } + int depth = 0; + for (Composite parent = control.getParent(); parent != null; parent = parent.getParent()) { + depth++; + } + return depth; + } + private boolean isApplicableToReset(WidgetElement element) { if (element.getNativeWidget() instanceof Widget) { return !((Widget) element.getNativeWidget()).isDisposed(); diff --git a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/helpers/CSSSWTColorHelper.java b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/helpers/CSSSWTColorHelper.java index 859589df519..e32dc020a6c 100644 --- a/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/helpers/CSSSWTColorHelper.java +++ b/bundles/org.eclipse.e4.ui.css.swt/src/org/eclipse/e4/ui/css/swt/helpers/CSSSWTColorHelper.java @@ -33,6 +33,7 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.RGBA; import org.eclipse.swt.widgets.Control; @@ -47,6 +48,14 @@ import org.w3c.dom.css.CSSValue; public class CSSSWTColorHelper { + + private static final String APPLIED_BACKGROUND = "org.eclipse.e4.ui.css.swt.appliedBackground"; //$NON-NLS-1$ + + private static final String APPLIED_FOREGROUND = "org.eclipse.e4.ui.css.swt.appliedForeground"; //$NON-NLS-1$ + + /** Recorded when a control that had its own color is reset. */ + private static final Object NOT_OWNED = new Object(); + public static final String COLOR_DEFINITION_MARKER = "#"; private static final Pattern HEX_COLOR_VALUE_PATTERN = Pattern.compile("#[a-fA-F0-9]{6}"); @@ -337,20 +346,51 @@ private static RGBA findColorByDefinition(String name) { return null; } - /** Helper function to avoid setting colors unnecessarily */ + /** + * Sets the color unless the control already has it. A control reset after + * having a CSS color gets it even when it equals the default one. + */ public static void setForeground(Control control, Color newColor) { - if (!Objects.equals(control.getForeground(), newColor)) { + Object applied = control.getData(APPLIED_FOREGROUND); + if (newColor == null) { + control.setForeground(null); + if (applied != null) { + control.setData(APPLIED_FOREGROUND, NOT_OWNED); + } + } else if (needsColor(applied, control.getForeground(), newColor)) { control.setForeground(newColor); + control.setData(APPLIED_FOREGROUND, newColor); } } - /** Helper function to avoid setting colors unnecessarily */ + /** + * Sets the color unless the control already has it. A control that loses its + * own color on reset gets the next one even when it equals the inherited one. + */ public static void setBackground(Control control, Color newColor) { - if (!Objects.equals(control.getBackground(), newColor)) { + Object applied = control.getData(APPLIED_BACKGROUND); + if (newColor == null) { + Color color = control.getBackground(); + Image image = control.getBackgroundImage(); + control.setBackground(null); + // the color may predate CSS, e.g. from FormToolkit.adapt, and SWT cannot tell + if (applied != null || !Objects.equals(color, control.getBackground()) + || image != control.getBackgroundImage()) { + control.setData(APPLIED_BACKGROUND, NOT_OWNED); + } + } else if (needsColor(applied, control.getBackground(), newColor)) { control.setBackground(newColor); + control.setData(APPLIED_BACKGROUND, newColor); } } + /** + * The current color may be inherited. A control that never had its own color + * keeps inheriting it, since its parent may paint an image behind it. + */ + private static boolean needsColor(Object applied, Color current, Color newColor) { + return (applied != null && !applied.equals(newColor)) || !newColor.equals(current); + } /** Helper function to avoid setting colors unnecessarily */ public static void setSelectionForeground(CTabFolder folder, Color newColor) { diff --git a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/InheritTest.java b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/InheritTest.java index 0b6e1b8073a..e5cb8283795 100644 --- a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/InheritTest.java +++ b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/InheritTest.java @@ -15,13 +15,19 @@ package org.eclipse.e4.ui.tests.css.swt; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; +import java.io.StringReader; import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; @@ -94,6 +100,92 @@ void testBackgroundInheritsAlsoExplicitlySetColors() assertEquals(RED, labelToTest.getBackground().getRGB()); } + /** + * A reset widget that had its own color gets it back even when it equals the + * parent's, otherwise it shows the parent's background image. + */ + @Test + void testBackgroundReappliedAfterResetWhenEqualToParent() throws IOException { + Shell shell = new Shell(css.getDisplay(), SWT.SHELL_TRIM); + Composite composite = new Composite(shell, SWT.NONE); + composite.setBackgroundMode(SWT.INHERIT_FORCE); + Label label = new Label(composite, SWT.NONE); + CSSEngine engine = css.createEngine("Composite { background-color: #FF0000; } Label { background-color: #0000FF; }"); + engine.applyStyles(shell, true); + + // several resets, so the record survives more than one + restyle(engine, shell, "Composite, Label { background-color: #FF0000; }"); + restyle(engine, shell, "Composite { background-color: #FF0000; } Label { background-color: #0000FF; }"); + restyle(engine, shell, "Composite, Label { background-color: #FF0000; }"); + + Image image = new Image(css.getDisplay(), 4, 4); + try { + composite.setBackgroundImage(image); + assertNull(label.getBackgroundImage()); + } finally { + image.dispose(); + } + } + + /** + * A widget that never owned a color keeps inheriting the parent's, so it still + * shows the parent's background image. + */ + @Test + void testBackgroundEqualToParentIsInherited() { + Shell shell = new Shell(css.getDisplay(), SWT.SHELL_TRIM); + Composite composite = new Composite(shell, SWT.NONE); + composite.setBackgroundMode(SWT.INHERIT_FORCE); + Label label = new Label(composite, SWT.NONE); + CSSEngine engine = css.createEngine("Composite, Label { background-color: #FF0000; }"); + engine.applyStyles(shell, true); + + Image image = new Image(css.getDisplay(), 4, 4); + try { + composite.setBackgroundImage(image); + assertEquals(image, label.getBackgroundImage()); + } finally { + image.dispose(); + } + } + + /** + * A child composite with a color set before styling that the first theme matches + * loses it on reset, and needs the next theme's color. + */ + @Test + void testBackgroundSetBeforeStylingReappliedWhenThemeMatchesIt() throws IOException { + assertBackgroundSetBeforeStylingReapplied(false); + } + + /** As above for a child no rule of the first theme applies to. */ + @Test + void testBackgroundSetBeforeStylingReappliedWithoutRule() throws IOException { + assertBackgroundSetBeforeStylingReapplied(true); + } + + private void assertBackgroundSetBeforeStylingReapplied(boolean labelChild) throws IOException { + Shell shell = new Shell(css.getDisplay(), SWT.SHELL_TRIM); + Composite composite = new Composite(shell, SWT.NONE); + composite.setBackgroundMode(SWT.INHERIT_DEFAULT); + Color white = new Color(255, 255, 255); + composite.setBackground(white); + Control child = labelChild ? new Label(composite, SWT.NONE) : new Composite(composite, SWT.NONE); + child.setBackground(white); + CSSEngine engine = css.createEngine("Composite { background-color: #FFFFFF; }"); + engine.applyStyles(shell, true); + + restyle(engine, shell, "Composite, Label { background-color: #2F2F2F; }"); + + Image image = new Image(css.getDisplay(), 4, 4); + try { + composite.setBackgroundImage(image); + assertNull(child.getBackgroundImage()); + } finally { + image.dispose(); + } + } + /** * Create a test label on a red canvas. Then apply given styles. * @@ -125,4 +217,10 @@ private Label createTestLabel(String styleSheet, engine.applyStyles(shell, true); return labelToTest; } + + private static void restyle(CSSEngine engine, Shell shell, String styleSheet) throws IOException { + engine.reset(); + engine.parseStyleSheet(new StringReader(styleSheet)); + engine.applyStyles(shell, true); + } } From 25e7c3dbaf9ce2e5b1ba8cf37342c9797556663a Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Thu, 15 Oct 2026 00:04:19 +0200 Subject: [PATCH 43/52] Add quick selection mode to the e4 FilteredTree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The workbench FilteredTree can select the first match while the user types, which the Show View dialog relies on, but the e4 FilteredTree had no such mode. Add setQuickSelectionMode() to the e4 variant and enable it in the e4 Show View dialog. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../META-INF/MANIFEST.MF | 2 +- .../ui/dialogs/filteredtree/FilteredTree.java | 70 +++++++++----- .../META-INF/MANIFEST.MF | 2 +- .../swt/internal/copy/ShowViewDialog.java | 1 + .../org/eclipse/ui/tests/UiTestSuite.java | 2 + .../filteredtree/E4FilteredTreeTests.java | 94 +++++++++++++++++++ .../org.eclipse.ui.tests/META-INF/MANIFEST.MF | 2 +- 7 files changed, 149 insertions(+), 24 deletions(-) create mode 100644 tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/filteredtree/E4FilteredTreeTests.java diff --git a/bundles/org.eclipse.e4.ui.dialogs/META-INF/MANIFEST.MF b/bundles/org.eclipse.e4.ui.dialogs/META-INF/MANIFEST.MF index 0c6a7fee4cb..2a446188388 100644 --- a/bundles/org.eclipse.e4.ui.dialogs/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.e4.ui.dialogs/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.e4.ui.dialogs -Bundle-Version: 1.7.300.qualifier +Bundle-Version: 1.8.0.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Vendor: %providerName Bundle-Localization: plugin diff --git a/bundles/org.eclipse.e4.ui.dialogs/src/org/eclipse/e4/ui/dialogs/filteredtree/FilteredTree.java b/bundles/org.eclipse.e4.ui.dialogs/src/org/eclipse/e4/ui/dialogs/filteredtree/FilteredTree.java index 322092e5550..0941b11592a 100644 --- a/bundles/org.eclipse.e4.ui.dialogs/src/org/eclipse/e4/ui/dialogs/filteredtree/FilteredTree.java +++ b/bundles/org.eclipse.e4.ui.dialogs/src/org/eclipse/e4/ui/dialogs/filteredtree/FilteredTree.java @@ -68,6 +68,8 @@ public class FilteredTree extends AbstractFilteredViewerComposite private Composite treeComposite; + private boolean quickSelectionMode = false; + /** * Maximum time spent expanding the tree after the filter text has been * updated (this is only used if we were able to at least expand the visible @@ -281,6 +283,9 @@ && recursiveExpand(items, monitor, stopTime, new int[] { numVisibleItems })) { if (items.length > 0 && getViewer().getTree().getSelectionCount() == 0) { treeViewer.getTree().setTopItem(items[0]); } + if (quickSelectionMode) { + updateTreeSelection(false); + } redrawFalseControl.setRedraw(true); } return Status.OK_STATUS; @@ -444,33 +449,56 @@ public void keyPressed(KeyEvent e) { // enter key set focus to tree filterText.addTraverseListener(e -> { + if (quickSelectionMode) { + return; + } if (e.detail == SWT.TRAVERSE_RETURN) { e.doit = false; - if (getViewer().getTree().getItemCount() == 0) { - return; - } - // if the initial filter text hasn't changed, do not try - // to match - boolean hasFocus = getViewer().getTree().setFocus(); - boolean textChanged = !getInitialText().equals(filterText.getText().trim()); - if (hasFocus && textChanged && filterText.getText().trim().length() > 0) { - Tree tree = getViewer().getTree(); - TreeItem item; - if (tree.getSelectionCount() > 0) { - item = getFirstMatchingItem(tree.getSelection()); - } else { - item = getFirstMatchingItem(tree.getItems()); - } - if (item != null) { - tree.setSelection(new TreeItem[] { item }); - ISelection sel = getViewer().getSelection(); - getViewer().setSelection(sel, true); - } - } + updateTreeSelection(true); } }); } + private void updateTreeSelection(boolean setFocus) { + Tree tree = getViewer().getTree(); + if (tree.getItemCount() == 0) { + return; + } + // if the initial filter text hasn't changed, do not try + // to match + boolean hasFocus = setFocus ? tree.setFocus() : true; + boolean textChanged = !getInitialText().equals(filterText.getText().trim()); + if (hasFocus && textChanged && filterText.getText().trim().length() > 0) { + TreeItem item; + if (tree.getSelectionCount() > 0) { + item = getFirstMatchingItem(tree.getSelection()); + } else { + item = getFirstMatchingItem(tree.getItems()); + } + if (item != null) { + tree.setSelection(new TreeItem[] { item }); + ISelection sel = getViewer().getSelection(); + getViewer().setSelection(sel, true); + } + } + } + + /** + * Sets whether this filtered tree is used to make quick selections. In this + * mode the first match in the tree is automatically selected while filtering + * and the 'Enter' key is not used to move the focus to the tree. + *

+ * By default, this is set to false. + *

+ * + * @param enabled true if this filtered tree is used to make quick + * selections, false otherwise + * @since 1.8 + */ + public void setQuickSelectionMode(boolean enabled) { + this.quickSelectionMode = enabled; + } + @Override protected Text doCreateFilterText(Composite parent) { return new Text(parent, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.ICON_CANCEL | SWT.ICON_SEARCH); diff --git a/bundles/org.eclipse.e4.ui.workbench.swt/META-INF/MANIFEST.MF b/bundles/org.eclipse.e4.ui.workbench.swt/META-INF/MANIFEST.MF index c21c53df8ad..c63b834bb1f 100644 --- a/bundles/org.eclipse.e4.ui.workbench.swt/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.e4.ui.workbench.swt/META-INF/MANIFEST.MF @@ -10,7 +10,7 @@ Require-Bundle: org.eclipse.e4.ui.workbench;bundle-version="0.10.0", org.eclipse.e4.core.services;bundle-version="1.0.0", org.eclipse.e4.ui.services;bundle-version="0.1.0", org.eclipse.jface;bundle-version="[3.41.0,4.0.0)", - org.eclipse.e4.ui.dialogs;bundle-version="1.1.600", + org.eclipse.e4.ui.dialogs;bundle-version="1.8.0", org.eclipse.core.databinding;bundle-version="[1.2.0,2.0.0)", org.eclipse.jface.databinding;bundle-version="[1.3.0,2.0.0)", org.eclipse.e4.ui.css.core;bundle-version="0.12.200", diff --git a/bundles/org.eclipse.e4.ui.workbench.swt/src/org/eclipse/e4/ui/workbench/swt/internal/copy/ShowViewDialog.java b/bundles/org.eclipse.e4.ui.workbench.swt/src/org/eclipse/e4/ui/workbench/swt/internal/copy/ShowViewDialog.java index 41a099ed5dd..733e0d6148b 100644 --- a/bundles/org.eclipse.e4.ui.workbench.swt/src/org/eclipse/e4/ui/workbench/swt/internal/copy/ShowViewDialog.java +++ b/bundles/org.eclipse.e4.ui.workbench.swt/src/org/eclipse/e4/ui/workbench/swt/internal/copy/ShowViewDialog.java @@ -188,6 +188,7 @@ private void createFilteredTreeViewer(Composite parent) { filter.setIncludeLeadingWildcard(true); int styleBits = SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER; filteredTree = new FilteredTree(parent, styleBits, filter); + filteredTree.setQuickSelectionMode(true); filteredTree.setBackground(parent.getDisplay().getSystemColor( SWT.COLOR_WIDGET_BACKGROUND)); diff --git a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/UiTestSuite.java b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/UiTestSuite.java index bd43617a3d0..ca10d65d3c4 100644 --- a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/UiTestSuite.java +++ b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/UiTestSuite.java @@ -34,6 +34,7 @@ import org.eclipse.ui.tests.dynamicplugins.DynamicPluginsTestSuite; import org.eclipse.ui.tests.encoding.EncodingTestSuite; import org.eclipse.ui.tests.fieldassist.FieldAssistTestSuite; +import org.eclipse.ui.tests.filteredtree.E4FilteredTreeTests; import org.eclipse.ui.tests.filteredtree.FilteredTableTests; import org.eclipse.ui.tests.filteredtree.FilteredTreeTests; import org.eclipse.ui.tests.filteredtree.PatternFilterTest; @@ -90,6 +91,7 @@ ConcurrencyTestSuite.class, FilteredTableTests.class, FilteredTreeTests.class, + E4FilteredTreeTests.class, PatternFilterTest.class, StatusHandlingTestSuite.class, MenusTestSuite.class, diff --git a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/filteredtree/E4FilteredTreeTests.java b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/filteredtree/E4FilteredTreeTests.java new file mode 100644 index 00000000000..212086baea0 --- /dev/null +++ b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/filteredtree/E4FilteredTreeTests.java @@ -0,0 +1,94 @@ +/******************************************************************************* + * Copyright (c) 2026 vogella GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Lars Vogel - initial API and implementation + ******************************************************************************/ + +package org.eclipse.ui.tests.filteredtree; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.eclipse.e4.ui.dialogs.filteredtree.FilteredTree; +import org.eclipse.e4.ui.dialogs.filteredtree.PatternFilter; +import org.eclipse.jface.tests.viewers.TestElement; +import org.eclipse.jface.tests.viewers.TestModelContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.tests.harness.util.DisplayHelper; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class E4FilteredTreeTests { + private Shell shell; + private FilteredTree filteredTree; + private TestElement root; + + @Before + public void setUp() { + shell = new Shell(); + shell.setLayout(new FillLayout()); + filteredTree = new FilteredTree(shell, SWT.SINGLE | SWT.BORDER, new PatternFilter(), 0); + root = TestElement.createModel(3, 10); + TreeViewer viewer = filteredTree.getViewer(); + viewer.setContentProvider(new TestModelContentProvider()); + viewer.setLabelProvider(new LabelProvider()); + viewer.setInput(root); + shell.setSize(400, 500); + } + + @After + public void tearDown() { + shell.dispose(); + } + + @Test + public void testQuickSelectionModeSelectsFirstMatch() { + filteredTree.setQuickSelectionMode(true); + TestElement leaf = root.getChildAt(4).getChildAt(2).getChildAt(7); + + applyFilter(leaf.toString()); + + assertEquals(leaf, filteredTree.getViewer().getStructuredSelection().getFirstElement()); + } + + @Test + public void testNoSelectionWithoutQuickSelectionMode() { + TestElement leaf = root.getChildAt(4).getChildAt(2).getChildAt(7); + + applyFilter(leaf.toString()); + + assertTrue(filteredTree.getViewer().getStructuredSelection().isEmpty()); + } + + @Test + public void testQuickSelectionModeWithoutMatchSelectsNothing() { + filteredTree.setQuickSelectionMode(true); + TreeViewer viewer = filteredTree.getViewer(); + + filteredTree.getFilterControl().setText("no such element"); + assertTrue("Filter was not applied", DisplayHelper.waitForCondition(shell.getDisplay(), 5000, + () -> viewer.getTree().getItemCount() == 0)); + + assertTrue(viewer.getStructuredSelection().isEmpty()); + } + + private void applyFilter(String text) { + TreeViewer viewer = filteredTree.getViewer(); + filteredTree.getFilterControl().setText(text); + assertTrue("Filter was not applied", DisplayHelper.waitForCondition(shell.getDisplay(), 5000, + () -> viewer.getTree().getItemCount() == 1)); + } +} diff --git a/tests/org.eclipse.ui.tests/META-INF/MANIFEST.MF b/tests/org.eclipse.ui.tests/META-INF/MANIFEST.MF index 087ee22ddee..7e6cbaecc53 100644 --- a/tests/org.eclipse.ui.tests/META-INF/MANIFEST.MF +++ b/tests/org.eclipse.ui.tests/META-INF/MANIFEST.MF @@ -30,7 +30,7 @@ Require-Bundle: org.eclipse.core.resources;bundle-version="3.14.0", org.eclipse.e4.core.di, org.eclipse.e4.ui.workbench.swt;bundle-version="0.9.1", org.eclipse.e4.ui.di;bundle-version="0.9.0", - org.eclipse.e4.ui.dialogs;bundle-version="1.6.0", + org.eclipse.e4.ui.dialogs;bundle-version="1.8.0", org.eclipse.e4.ui.css.swt.theme;bundle-version="0.9.0", org.eclipse.e4.ui.bindings;bundle-version="0.9.0", org.eclipse.e4.ui.css.swt;bundle-version="0.9.1", From 4bd8b48d10801c75afbd6e3aa6fbb5272143c338 Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Tue, 10 Nov 2026 22:52:58 +0100 Subject: [PATCH 44/52] Set the dark theme preference before resetting widget colors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ThemeEngine reset the widgets before telling the Display about the new theme. On GTK a null color resolves to the current system color, so controls without a rule in the new theme kept the colors of the old one, for example dark buttons and tables in Forms editors after switching from Dark to Light. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../css/swt/internal/theme/ThemeEngine.java | 5 +-- .../e4/ui/tests/css/swt/ThemeTest.java | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java index dfb1ad2cbc4..8c291d8b06e 100644 --- a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java +++ b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java @@ -487,6 +487,9 @@ public void setTheme(ITheme theme, boolean restore) { public void setTheme(ITheme theme, boolean restore, boolean force) { Assert.isNotNull(theme, "The theme must not be null"); + // on GTK a reset resolves null colors against the system colors, which must match the new theme + display.setDarkThemePreferred(theme.isDark()); + if (this.currentTheme != theme || force) { if (currentTheme != null) { for (IResourceLocator l : getResourceLocators(currentTheme @@ -551,8 +554,6 @@ public void setTheme(ITheme theme, boolean restore, boolean force) { } publishEffectiveThemeId(); - display.setDarkThemePreferred(theme.isDark()); - sendThemeChangeEvent(restore); for (CSSEngine engine : cssEngines) { diff --git a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java index e661344047f..dd31c66abc8 100644 --- a/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java +++ b/tests/org.eclipse.e4.ui.tests.css.swt/src/org/eclipse/e4/ui/tests/css/swt/ThemeTest.java @@ -19,6 +19,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; import java.util.ArrayList; import java.util.Dictionary; @@ -29,9 +32,11 @@ import org.eclipse.core.runtime.ILogListener; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.ConfigurationScope; +import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.core.runtime.preferences.UserScope; +import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.e4.ui.css.swt.internal.theme.Theme; import org.eclipse.e4.ui.css.swt.internal.theme.ThemeEngine; import org.eclipse.e4.ui.css.swt.theme.ITheme; @@ -42,6 +47,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.InOrder; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; @@ -226,6 +232,33 @@ private static ITheme findTheme(List themes, String id) { .orElseThrow(() -> new AssertionError("Theme not registered: " + id)); } + @Test + void testDarkPreferenceIsSetBeforeReset() { + String themeId = "order.test"; + String darkKey = "themeIsDark." + themeId; + Display display = mock(Display.class); + CSSEngine cssEngine = mock(CSSEngine.class, RETURNS_DEEP_STUBS); + ThemeEngine themer = new ThemeEngine(display); + themer.addCSSEngine(cssEngine); + IEclipsePreferences defaults = DefaultScope.INSTANCE.getNode(ThemeEngine.THEME_PLUGIN_ID); + String previousId = defaults.get(THEMEID_KEY, null); + String previousDark = defaults.get(darkKey, null); + + try { + themer.setTheme(new Theme(themeId, "Order", true), false); + themer.setTheme(new Theme(themeId, "Order", false), false); + } finally { + putOrRemove(defaults, THEMEID_KEY, previousId); + putOrRemove(defaults, darkKey, previousDark); + } + + InOrder order = inOrder(display, cssEngine); + order.verify(display).setDarkThemePreferred(true); + order.verify(cssEngine).reset(); + order.verify(display).setDarkThemePreferred(false); + order.verify(cssEngine).reset(); + } + private IThemeEngine getThemeEngine(Display display) { IThemeManager manager = context.getService(themeManagerReference); assertNotNull(manager, "Theme manager service not available"); From e13570bd70f5c430cf11bef43a7c79ac9077e4f5 Mon Sep 17 00:00:00 2001 From: Neha Burnwal Date: Mon, 26 Oct 2026 13:35:02 +0530 Subject: [PATCH 45/52] Show theme controls dynamically on the Appearance preference page The "Enable theming" checkbox did nothing when toggled: the theme controls were only built if theming was enabled at startup and were never hidden. After re-enabling theming, no theme could be chosen until a second restart. Always create the theme controls and show or hide them with the checkbox. When theming is enabled without an engine, store the selected theme under the "themeid" key that ThemeEngine restores at startup, so one restart is enough. Cancel now also undoes a live Colors and Fonts change in that case. Fixes: https://github.com/eclipse-platform/eclipse.platform.ui/issues/4502 https://github.com/eclipse-platform/eclipse.platform.ui/issues/4503 --- .../css/swt/internal/theme/ThemeEngine.java | 151 +++---------- .../e4/ui/css/swt/theme/ThemeDefinition.java | 160 ++++++++++++++ .../internal/dialogs/ViewsPreferencePage.java | 205 ++++++++++++++---- 3 files changed, 353 insertions(+), 163 deletions(-) create mode 100644 bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/theme/ThemeDefinition.java diff --git a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java index dfb1ad2cbc4..019b51e0216 100644 --- a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java +++ b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/internal/theme/ThemeEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2023 Tom Schindl and others. + * Copyright (c) 2010, 2026 Tom Schindl and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -56,6 +56,7 @@ import org.eclipse.e4.ui.css.swt.helpers.EclipsePreferencesHelper; import org.eclipse.e4.ui.css.swt.theme.ITheme; import org.eclipse.e4.ui.css.swt.theme.IThemeEngine; +import org.eclipse.e4.ui.css.swt.theme.ThemeDefinition; import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.swt.widgets.Display; import org.osgi.framework.Bundle; @@ -128,76 +129,40 @@ public ThemeEngine(Display display) { } File[] modifiedFiles = modDir.listFiles(); - String currentOS = Platform.getOS(); - boolean e4_dark_mac_found = false; - for (IExtension e : extPoint.getExtensions()) { - for (IConfigurationElement ce : getPlatformMatches(e.getConfigurationElements())) { - if (ce.getName().equals("theme")) { - try { - String id = ce.getAttribute("id"); - String os = ce.getAttribute("os"); - String version = ce.getAttribute("os_version"); - - /* - * Code to support e4 dark theme on Mac 10.13 and older. For e4 dark theme on - * Mac, register the theme with matching OS version if specified. - */ - if (E4_DARK_THEME_ID.equals(id) && Platform.OS_MACOSX.equals(currentOS) && os != null - && os.equals(currentOS)) { - // If e4 dark theme on Mac was already registered, don't try to match or - // register again. - if (e4_dark_mac_found) { - continue; - } - if (version != null && !isOsVersionMatch(version)) { - continue; - } else { - e4_dark_mac_found = true; - version = ""; - } - } - - if (version == null) { - version = ""; - } - - final String themeBaseId = id + version; - String themeId = themeBaseId; - String label = ce.getAttribute("label"); - boolean dark = isDarkTheme(ce); - String originalCSSFile; - String basestylesheeturi = originalCSSFile = ce.getAttribute("basestylesheeturi"); - if (!basestylesheeturi.startsWith("platform:/plugin/")) { - basestylesheeturi = "platform:/plugin/" + ce.getContributor().getName() + "/" - + basestylesheeturi; - } - registerTheme(themeId, label, basestylesheeturi, version, dark); - - //check for modified files - if (modifiedFiles != null) { - int slash = originalCSSFile.lastIndexOf('/'); - if (slash != -1) { - originalCSSFile = originalCSSFile.substring(slash + 1); - for (File modifiedFile : modifiedFiles) { - String modifiedFileName = modifiedFile.getName(); - if (modifiedFileName.contains(".css") && modifiedFileName.equals(originalCSSFile)) { //$NON-NLS-1$ - ArrayList styleSheets = new ArrayList<>(); - styleSheets.add(modifiedFile.toURI().toString()); - modifiedStylesheets.put(themeId, styleSheets); - } - } + for (ThemeDefinition definition : ThemeDefinition.readAll()) { + try { + String themeId = definition.id(); + String originalCSSFile = definition.stylesheet(); + String basestylesheeturi = originalCSSFile; + if (!basestylesheeturi.startsWith("platform:/plugin/")) { + basestylesheeturi = "platform:/plugin/" + definition.contributor() + "/" + basestylesheeturi; + } + registerTheme(themeId, definition.label(), basestylesheeturi, definition.osVersion(), + definition.dark()); + + //check for modified files + if (modifiedFiles != null) { + int slash = originalCSSFile.lastIndexOf('/'); + if (slash != -1) { + originalCSSFile = originalCSSFile.substring(slash + 1); + for (File modifiedFile : modifiedFiles) { + String modifiedFileName = modifiedFile.getName(); + if (modifiedFileName.contains(".css") && modifiedFileName.equals(originalCSSFile)) { //$NON-NLS-1$ + ArrayList styleSheets = new ArrayList<>(); + styleSheets.add(modifiedFile.toURI().toString()); + modifiedStylesheets.put(themeId, styleSheets); } } - } catch (IllegalArgumentException e1) { - ThemeEngineManager.logError(e1.getMessage(), e1); } } + } catch (IllegalArgumentException e1) { + ThemeEngineManager.logError(e1.getMessage(), e1); } } for (IExtension e : extPoint.getExtensions()) { - for (IConfigurationElement ce : getPlatformMatches(e.getConfigurationElements())) { + for (IConfigurationElement ce : ThemeDefinition.getPlatformMatches(e.getConfigurationElements())) { if (ce.getName().equals("stylesheet")) { IConfigurationElement[] cces = ce.getChildren("themeid"); if (cces.length == 0) { @@ -243,39 +208,6 @@ public ThemeEngine(Display display) { } - /** - * Themes declare their appearance with the {@code isDarkTheme} attribute. Themes - * contributed before that attribute existed are classified by their id, which is - * the convention the platform relied on so far. - */ - private static boolean isDarkTheme(IConfigurationElement themeElement) { - String dark = themeElement.getAttribute("isDarkTheme"); - if (dark != null) { - return Boolean.parseBoolean(dark); - } - String id = themeElement.getAttribute("id"); - return id != null && id.contains("dark"); //$NON-NLS-1$ - } - - private boolean isOsVersionMatch(String osVersionList) { - boolean found = false; - String osVersion = System.getProperty("os.version"); - if (osVersion != null) { - if (osVersionList != null) { - String[] osVersions = osVersionList.split(","); //$NON-NLS-1$ - for (String osVersionFromTheme : osVersions) { - if (osVersionFromTheme != null) { - if (osVersion.contains(osVersionFromTheme)) { - found = true; - break; - } - } - } - } - } - return found; - } - @Override public synchronized ITheme registerTheme(String id, String label, String basestylesheetURI) throws IllegalArgumentException { @@ -401,31 +333,6 @@ private List getResourceLocators(String id) { return list; } - /** - * Get all elements that have os/ws attributes that best match the current - * platform. - * - * @param elements the elements to check - * @return the best matches, if any - */ - private IConfigurationElement[] getPlatformMatches(IConfigurationElement[] elements) { - Bundle bundle = FrameworkUtil.getBundle(ThemeEngine.class); - String osname = bundle.getBundleContext().getProperty("osgi.os"); - // TODO: Need to differentiate win32 versions - String wsname = bundle.getBundleContext().getProperty("osgi.ws"); - ArrayList matchingElements = new ArrayList<>(); - for (IConfigurationElement element : elements) { - String elementOs = element.getAttribute("os"); - String elementWs = element.getAttribute("ws"); - if (osname != null && (elementOs == null || elementOs.contains(osname))) { - matchingElements.add(element); - } else if (wsname != null && wsname.equalsIgnoreCase(elementWs)) { - matchingElements.add(element); - } - } - return matchingElements.toArray(new IConfigurationElement[matchingElements.size()]); - } - @Override public void setTheme(String themeId, boolean restore) { if (applyTheme(themeId, restore)) { @@ -434,12 +341,12 @@ public void setTheme(String themeId, boolean restore) { // In OS high-contrast mode keep the native OS colors instead of forcing a theme if (display != null && display.getHighContrast()) { ILog.of(ThemeEngine.class) - .warn("Theme '" + themeId + "' not found; using OS high contrast colors."); //$NON-NLS-1$ //$NON-NLS-2$ + .warn("Theme '" + themeId + "' not found; using OS high contrast colors."); //$NON-NLS-1$ //$NON-NLS-2$ return; } if (!E4_DEFAULT_THEME_ID.equals(themeId) && applyTheme(E4_DEFAULT_THEME_ID, restore)) { ILog.of(ThemeEngine.class) - .warn("Theme '" + themeId + "' not found; falling back to default theme."); //$NON-NLS-1$ //$NON-NLS-2$ + .warn("Theme '" + themeId + "' not found; falling back to default theme."); //$NON-NLS-1$ //$NON-NLS-2$ return; } ILog.of(ThemeEngine.class).warn("Theme '" + themeId + "' not found."); //$NON-NLS-1$ //$NON-NLS-2$ diff --git a/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/theme/ThemeDefinition.java b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/theme/ThemeDefinition.java new file mode 100644 index 00000000000..2367bbfbf75 --- /dev/null +++ b/bundles/org.eclipse.e4.ui.css.swt.theme/src/org/eclipse/e4/ui/css/swt/theme/ThemeDefinition.java @@ -0,0 +1,160 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.e4.ui.css.swt.theme; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.RegistryFactory; +import org.eclipse.e4.ui.css.swt.internal.theme.ThemeEngine; +import org.osgi.framework.Bundle; +import org.osgi.framework.FrameworkUtil; + +/** + * A theme as declared by a theme element of the + * org.eclipse.e4.ui.css.swt.theme extension point, resolved for + * the current platform. This is what the theme engine registers, and it can + * also be read when there is no theme engine. + * + * @param id the id the theme is registered with, including the OS + * version if the theme declares one + * @param label the label + * @param osVersion the OS version the theme declares, or the empty string + * @param dark whether the theme is dark + * @param stylesheet the basestylesheeturi as declared + * @param contributor the name of the contributing bundle + */ +public record ThemeDefinition(String id, String label, String osVersion, boolean dark, String stylesheet, + String contributor) implements ITheme { + + @Override + public String getId() { + return id; + } + + @Override + public String getLabel() { + return label; + } + + @Override + public boolean isDark() { + return dark; + } + + /** + * Reads the themes contributed for the current platform, in the order of the + * extension registry. A theme id contributed more than once is returned more + * than once. + * + * @return the themes + */ + public static List readAll() { + List result = new ArrayList<>(); + IExtensionPoint extPoint = RegistryFactory.getRegistry().getExtensionPoint(ThemeEngine.THEME_PLUGIN_ID); + String currentOS = Platform.getOS(); + boolean e4DarkMacFound = false; + for (IExtension extension : extPoint.getExtensions()) { + for (IConfigurationElement ce : getPlatformMatches(extension.getConfigurationElements())) { + if (!ce.getName().equals("theme")) { //$NON-NLS-1$ + continue; + } + String id = ce.getAttribute("id"); //$NON-NLS-1$ + String os = ce.getAttribute("os"); //$NON-NLS-1$ + String version = ce.getAttribute("os_version"); //$NON-NLS-1$ + + /* + * Code to support e4 dark theme on Mac 10.13 and older. For e4 dark theme on + * Mac, register the theme with matching OS version if specified. + */ + if (ThemeEngine.E4_DARK_THEME_ID.equals(id) && Platform.OS_MACOSX.equals(currentOS) && os != null + && os.equals(currentOS)) { + // If e4 dark theme on Mac was already registered, don't try to match or + // register again. + if (e4DarkMacFound) { + continue; + } + if (version != null && !isOsVersionMatch(version)) { + continue; + } + e4DarkMacFound = true; + version = ""; //$NON-NLS-1$ + } + + if (version == null) { + version = ""; //$NON-NLS-1$ + } + result.add(new ThemeDefinition(id + version, ce.getAttribute("label"), version, isDarkTheme(ce), //$NON-NLS-1$ + ce.getAttribute("basestylesheeturi"), ce.getContributor().getName())); //$NON-NLS-1$ + } + } + return result; + } + + /** + * Get all elements that have os/ws attributes that best match the current + * platform. + * + * @param elements the elements to check + * @return the best matches, if any + */ + public static IConfigurationElement[] getPlatformMatches(IConfigurationElement[] elements) { + Bundle bundle = FrameworkUtil.getBundle(ThemeDefinition.class); + String osname = bundle.getBundleContext().getProperty("osgi.os"); //$NON-NLS-1$ + // TODO: Need to differentiate win32 versions + String wsname = bundle.getBundleContext().getProperty("osgi.ws"); //$NON-NLS-1$ + ArrayList matchingElements = new ArrayList<>(); + for (IConfigurationElement element : elements) { + String elementOs = element.getAttribute("os"); //$NON-NLS-1$ + String elementWs = element.getAttribute("ws"); //$NON-NLS-1$ + if (osname != null && (elementOs == null || elementOs.contains(osname))) { + matchingElements.add(element); + } else if (wsname != null && wsname.equalsIgnoreCase(elementWs)) { + matchingElements.add(element); + } + } + return matchingElements.toArray(new IConfigurationElement[matchingElements.size()]); + } + + /** + * Themes declare their appearance with the {@code isDarkTheme} attribute. Themes + * contributed before that attribute existed are classified by their id, which is + * the convention the platform relied on so far. + */ + private static boolean isDarkTheme(IConfigurationElement themeElement) { + String dark = themeElement.getAttribute("isDarkTheme"); //$NON-NLS-1$ + if (dark != null) { + return Boolean.parseBoolean(dark); + } + String id = themeElement.getAttribute("id"); //$NON-NLS-1$ + return id != null && id.contains("dark"); //$NON-NLS-1$ + } + + private static boolean isOsVersionMatch(String osVersionList) { + String osVersion = System.getProperty("os.version"); //$NON-NLS-1$ + if (osVersion == null) { + return false; + } + for (String osVersionFromTheme : osVersionList.split(",")) { //$NON-NLS-1$ + if (osVersion.contains(osVersionFromTheme)) { + return true; + } + } + return false; + } +} diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java index cd61235dfd7..a3d643d1f68 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/dialogs/ViewsPreferencePage.java @@ -47,6 +47,7 @@ import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.ui.css.swt.theme.ITheme; import org.eclipse.e4.ui.css.swt.theme.IThemeEngine; +import org.eclipse.e4.ui.css.swt.theme.ThemeDefinition; import org.eclipse.e4.ui.internal.workbench.swt.E4Application; import org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine; import org.eclipse.e4.ui.model.application.MApplication; @@ -103,8 +104,23 @@ public class ViewsPreferencePage extends PreferencePage implements IWorkbenchPre private static final String E4_THEME_EXTENSION_POINT = "org.eclipse.e4.ui.css.swt.theme"; //$NON-NLS-1$ + /** + * Key under which the theme engine remembers the selected theme, in the + * preference node named like the extension point. + */ + private static final String THEMEID_KEY = "themeid"; //$NON-NLS-1$ + /** The workbench theme engine; may be {@code null} if no engine */ private IThemeEngine engine; + /** + * Whether there is no theme engine because theming was switched off in the + * preferences, as opposed to the engine being missing for another reason, like + * -cssTheme none. Only in the first case can ticking the checkbox + * enable theming after a restart. + */ + private boolean themingOffByPreference; + private List availableThemes; + private final List themeDependentControls = new ArrayList<>(); private ComboViewer themeIdCombo; private ControlDecoration themeComboDecorator; private ITheme currentTheme; @@ -135,27 +151,22 @@ protected Control createContents(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); highContrastMode = parent.getDisplay().getHighContrast(); - // Deactivate theming in high contrast mode + themingOffByPreference = engine == null && !InstanceScope.INSTANCE + .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT) + .getBoolean(PartRenderingEngine.ENABLED_THEME_KEY, true); + // Deactivate theming in high contrast mode. Without an engine there is + // nothing to switch on either, unless theming was switched off by the user. themingEnabled = createCheckButton(comp, WorkbenchMessages.ThemingEnabled, isThemingPossible()); - themingEnabled.setEnabled(!highContrastMode); - - // if started with "-cssTheme none" or if high contrast mode is active, - // CSS settings should be disabled but other appearance settings should be *not* - // disabled - if (!isThemingPossible()) { - GridLayout layout = new GridLayout(1, false); - layout.horizontalSpacing = 10; - comp.setLayout(layout); - createThemeIndependentComposits(comp); - createRescaleAtRuntimeCheckButton(comp); - return comp; - } + themingEnabled.setEnabled(!highContrastMode && (engine != null || themingOffByPreference)); GridLayout layout = new GridLayout(2, false); layout.horizontalSpacing = 10; comp.setLayout(layout); - new Label(comp, SWT.NONE).setText(WorkbenchMessages.ViewsPreferencePage_Theme); + int firstThemeControl = comp.getChildren().length; + Label themeLabel = new Label(comp, SWT.NONE); + themeLabel.setText(WorkbenchMessages.ViewsPreferencePage_Theme); + themeLabel.setLayoutData(new GridData()); Composite themeComposite = new Composite(comp, SWT.NONE); GridLayout themeLayout = new GridLayout(2, false); @@ -167,11 +178,15 @@ protected Control createContents(Composite parent) { themeIdCombo = new ComboViewer(themeComposite, SWT.READ_ONLY); themeIdCombo.setLabelProvider(createTextProvider(element -> ((ITheme) element).getLabel())); themeIdCombo.setContentProvider(ArrayContentProvider.getInstance()); - themeIdCombo.setInput(engine.getThemes()); + // Without an engine (theming was disabled at startup) the themes still have + // to be offered, so that one can be chosen while enabling theming again + availableThemes = engine != null ? engine.getThemes() : readRegisteredThemes(); + themeIdCombo.setInput(availableThemes); themeIdCombo.getControl().setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - this.currentTheme = engine.getActiveTheme(); - if (this.currentTheme != null) { - themeIdCombo.setSelection(new StructuredSelection(currentTheme)); + this.currentTheme = engine != null ? engine.getActiveTheme() : null; + ITheme initialTheme = currentTheme != null ? currentTheme : findInitialTheme(); + if (initialTheme != null) { + themeIdCombo.setSelection(new StructuredSelection(initialTheme)); } themeComboDecorator = new ControlDecoration(themeIdCombo.getCombo(), SWT.TOP | SWT.LEFT); @@ -195,28 +210,92 @@ protected Control createContents(Composite parent) { currentColorsAndFontsTheme = getCurrentColorsAndFontsTheme(); createColorsAndFontsThemeCombo(comp); + collectControls(comp, firstThemeControl, themeDependentControls); createThemeIndependentComposits(comp); // Theme dependent controls for Tab icons and titles in view areas + int firstTabControl = comp.getChildren().length; createShowFullTextForViewTabs(comp); createHideIconsForViewTabs(comp); createDependency(showFullTextForViewTabs, hideIconsForViewTabs); + collectControls(comp, firstTabControl, themeDependentControls); createRescaleAtRuntimeCheckButton(comp); - if (currentTheme != null) { - String colorsAndFontsThemeId = getColorAndFontThemeIdByThemeId(currentTheme.getId()); + if (initialTheme != null) { + String colorsAndFontsThemeId = getColorAndFontThemeIdByThemeId(initialTheme.getId()); if (colorsAndFontsThemeId != null && !currentColorsAndFontsTheme.getId().equals(colorsAndFontsThemeId)) { colorsAndFontsThemeId = currentColorsAndFontsTheme.getId(); } selectColorsAndFontsTheme(colorsAndFontsThemeId); } + setThemeControlsVisible(themingEnabled.getSelection()); + themingEnabled.addSelectionListener(widgetSelectedAdapter(e -> { + setThemeControlsVisible(themingEnabled.getSelection()); + comp.requestLayout(); + })); + Dialog.applyDialogFont(comp); return comp; } + /** Adds the children of {@code composite} created since {@code fromIndex}. */ + private static void collectControls(Composite composite, int fromIndex, List target) { + Control[] children = composite.getChildren(); + for (int i = fromIndex; i < children.length; i++) { + target.add(children[i]); + } + } + + /** + * Shows or hides the theme dependent controls. Hidden controls are also + * excluded from the layout, so that they leave no gap. + */ + private void setThemeControlsVisible(boolean visible) { + for (Control control : themeDependentControls) { + ((GridData) control.getLayoutData()).exclude = !visible; + control.setVisible(visible); + } + } + + /** + * Reads the themes for the case that there is no theme engine. These are the + * ones the engine registers, so the offered ids are the ones it will know + * after the next start. The engine refuses to register an id twice, so a + * repeated id is dropped here as well. + */ + private static List readRegisteredThemes() { + List result = new ArrayList<>(); + for (ThemeDefinition definition : ThemeDefinition.readAll()) { + if (result.stream().noneMatch(theme -> theme.getId().equals(definition.getId()))) { + result.add(definition); + } + } + return result; + } + + /** + * Chooses the theme to preselect when there is no active theme: the one + * remembered for the next start, the theme the workbench was configured to + * start with (which already reflects the product default), or else the first + * theme. + */ + private ITheme findInitialTheme() { + String preferredId = Platform.getPreferencesService().getString(E4_THEME_EXTENSION_POINT, THEMEID_KEY, null, + null); + if (preferredId == null) { + preferredId = defaultTheme; + } + for (ITheme theme : availableThemes) { + if (theme.getId().equals(preferredId)) { + return theme; + } + } + return availableThemes.isEmpty() ? null : availableThemes.get(0); + } + /** * @return true if there is a theme engine set (i.e. if the * workbench started with the checkbox "enable theming" set to @@ -360,7 +439,7 @@ private void openManageDefaultThemeDialog() { String currentDefaultLabel = null; if (currentDefaultId != null) { - for (ITheme t : engine.getThemes()) { + for (ITheme t : availableThemes) { if (t.getId().equals(currentDefaultId)) { currentDefaultLabel = t.getLabel(); break; @@ -448,10 +527,28 @@ public void init(IWorkbench workbench) { public boolean performOk() { IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); - if (isThemingPossible()) { + // Theming is being switched on although the workbench runs without a theme + // engine, so the engine cannot apply the selection now + boolean enablingTheming = themingOffByPreference && themingEnabled.isEnabled() + && themingEnabled.getSelection(); + // Theming is being switched off, so no theme dependent change may stay + boolean disablingTheming = themingEnabled.isEnabled() && !themingEnabled.getSelection(); + if (disablingTheming) { + setColorsAndFontsTheme(currentColorsAndFontsTheme); + selectColorsAndFontsTheme(currentColorsAndFontsTheme.getId()); + } + boolean applyThemeSettings = (isThemingPossible() && !disablingTheming) || enablingTheming; + if (applyThemeSettings) { ITheme theme = getSelectedTheme(); if (theme != null) { - engine.setTheme(getSelectedTheme(), true); + if (isThemingPossible()) { + engine.setTheme(theme, true); + } else { + storeThemeForNextStart(theme); + } + } + if (enablingTheming) { + setColorsAndFontsTheme(getSelectedColorsAndFontsTheme()); } prefs.putBoolean(CTabRendering.HIDE_ICONS_FOR_VIEW_TABS, hideIconsForViewTabs.getSelection()); prefs.putBoolean(CTabRendering.SHOW_FULL_TEXT_FOR_VIEW_TABS, showFullTextForViewTabs.getSelection()); @@ -500,7 +597,7 @@ public boolean performOk() { String restartDialogMessage = null; ITheme changedTheme = null; - if (isThemingPossible()) { + if (isThemingPossible() && !disablingTheming) { ITheme theme = getSelectedTheme(); boolean themeChanged = theme != null && !theme.equals(currentTheme); changedTheme = themeChanged ? theme : null; @@ -515,19 +612,20 @@ public boolean performOk() { currentTheme = theme; } + if (appearanceChanged || colorsAndFontsThemeChanged) { + showRestartDialog = true; + restartDialogTitle = WorkbenchMessages.ThemeChangeWarningTitle; + restartDialogMessage = WorkbenchMessages.ThemeChangeWarningText; + } + } + if (applyThemeSettings) { + // Remember what is applied now, so that Cancel after Apply keeps it ColorsAndFontsTheme colorsAndFontsTheme = getSelectedColorsAndFontsTheme(); if (colorsAndFontsTheme != null) { currentColorsAndFontsTheme = colorsAndFontsTheme; } - themeComboDecorator.hide(); colorFontsDecorator.hide(); - - if (appearanceChanged || colorsAndFontsThemeChanged) { - showRestartDialog = true; - restartDialogTitle = WorkbenchMessages.ThemeChangeWarningTitle; - restartDialogMessage = WorkbenchMessages.ThemeChangeWarningText; - } } if (themingEnabledChanged) { showRestartDialog = true; @@ -547,6 +645,21 @@ public boolean performOk() { return super.performOk(); } + /** + * Remembers the theme for the next start in the same place and under the same + * key the theme engine uses, so that it restores the selected theme when it is + * created after the restart. + */ + private void storeThemeForNextStart(ITheme theme) { + IEclipsePreferences themePrefs = InstanceScope.INSTANCE.getNode(E4_THEME_EXTENSION_POINT); + themePrefs.put(THEMEID_KEY, theme.getId()); + try { + themePrefs.flush(); + } catch (BackingStoreException e) { + WorkbenchPlugin.log("Failed to store the selected theme", e); //$NON-NLS-1$ + } + } + private void showRestartDialog(String title, String warningText, ITheme theme) { boolean[] useAsDefault = { true }; MessageDialog dialog = new MessageDialog(null, title, null, warningText, MessageDialog.NONE, 2, @@ -585,12 +698,17 @@ private void setColorsAndFontsTheme(ColorsAndFontsTheme theme) { protected void performDefaults() { IEclipsePreferences defaultPrefs = DefaultScope.INSTANCE .getNode(CTabRendering.PREF_QUALIFIER_ECLIPSE_E4_UI_WORKBENCH_RENDERERS_SWT); - if (isThemingPossible()) { - setColorsAndFontsTheme(currentColorsAndFontsTheme); + if (isThemingPossible() || themingOffByPreference) { + if (isThemingPossible()) { + setColorsAndFontsTheme(currentColorsAndFontsTheme); - engine.setTheme(defaultTheme, true); - if (engine.getActiveTheme() != null) { - themeIdCombo.setSelection(new StructuredSelection(engine.getActiveTheme())); + engine.setTheme(defaultTheme, true); + if (engine.getActiveTheme() != null) { + themeIdCombo.setSelection(new StructuredSelection(engine.getActiveTheme())); + } + } else { + availableThemes.stream().filter(theme -> theme.getId().equals(defaultTheme)).findFirst() + .ifPresent(theme -> themeIdCombo.setSelection(new StructuredSelection(theme))); } hideIconsForViewTabs.setSelection(defaultPrefs.getBoolean(CTabRendering.HIDE_ICONS_FOR_VIEW_TABS, CTabRendering.HIDE_ICONS_FOR_VIEW_TABS_DEFAULT)); @@ -615,9 +733,9 @@ protected void performDefaults() { @Override public boolean performCancel() { - if (isThemingPossible()) { - setColorsAndFontsTheme(currentColorsAndFontsTheme); + setColorsAndFontsTheme(currentColorsAndFontsTheme); + if (isThemingPossible()) { if (currentTheme != null && !currentTheme.equals(engine.getActiveTheme())) { engine.setTheme(currentTheme, false); } @@ -627,7 +745,9 @@ public boolean performCancel() { } private void createColorsAndFontsThemeCombo(Composite composite) { - new Label(composite, SWT.NONE).setText(WorkbenchMessages.ViewsPreference_currentTheme); + Label label = new Label(composite, SWT.NONE); + label.setText(WorkbenchMessages.ViewsPreference_currentTheme); + label.setLayoutData(new GridData()); colorsAndFontsThemeCombo = new ComboViewer(composite, SWT.READ_ONLY); colorsAndFontsThemeCombo.getControl().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); colorsAndFontsThemeCombo.setLabelProvider(new LabelProvider() { @@ -651,7 +771,10 @@ public String getText(Object element) { } else { colorFontsDecorator.hide(); } - setColorsAndFontsTheme(colorsAndFontsTheme); + // Without an engine the change is applied by performOk(), if theming is enabled + if (isThemingPossible()) { + setColorsAndFontsTheme(colorsAndFontsTheme); + } }); } From 2cc8469d9e82dfeb6cd787b76317863954129f84 Mon Sep 17 00:00:00 2001 From: Luise Ravnskjaer <13628062+ravnskjaer@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:27:23 +0100 Subject: [PATCH 46/52] Return views outside of perspectives from getViewReferences() IWorkbenchPage.getViewReferences() returned an empty array as soon as no perspective was open, even when a view outside of any perspective (e.g. the intro view) was still visible on the page. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/2978 --- .../eclipse/ui/internal/WorkbenchPage.java | 36 +++++++++---------- .../ui/tests/api/IWorkbenchPageTest.java | 29 +++++++++++++++ 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPage.java b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPage.java index f3cbefc2faf..aebf7116da0 100644 --- a/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPage.java +++ b/bundles/org.eclipse.ui.workbench/eclipseui/org/eclipse/ui/internal/WorkbenchPage.java @@ -2506,28 +2506,24 @@ public IViewReference[] getViewReferences() { } private IViewReference[] getViewReferences(boolean allPerspectives) { - MPerspective perspective = getCurrentPerspective(); - if (perspective != null) { - int scope = allPerspectives ? WINDOW_SCOPE : EModelService.PRESENTATION; - Set parts = new HashSet<>(); - List placeholders = modelService.findElements(window, null, MPlaceholder.class, null, scope); - parts.addAll(placeholders); - parts.addAll(modelService.findElements(window, null, MPart.class, null, scope)); - List visibleReferences = new ArrayList<>(); - for (ViewReference reference : viewReferences) { - MPart model = reference.getModel(); - // The part may be linked in either directly or via a - // placeholder. In the latter case we can look - // at the part's curSharedRef since we're only considering - // parts visible in the current perspective - if (parts.contains(model) && !shouldNotRenderPart(model)) { - // only rendered placeholders are valid view references - visibleReferences.add(reference); - } + int scope = allPerspectives ? WINDOW_SCOPE : EModelService.PRESENTATION; + Set parts = new HashSet<>(); + List placeholders = modelService.findElements(window, null, MPlaceholder.class, null, scope); + parts.addAll(placeholders); + parts.addAll(modelService.findElements(window, null, MPart.class, null, scope)); + List visibleReferences = new ArrayList<>(); + for (ViewReference reference : viewReferences) { + MPart model = reference.getModel(); + // The part may be linked in either directly or via a + // placeholder. In the latter case we can look + // at the part's curSharedRef since we're only considering + // parts visible in the current perspective + if (parts.contains(model) && !shouldNotRenderPart(model)) { + // only rendered placeholders are valid view references + visibleReferences.add(reference); } - return visibleReferences.toArray(new IViewReference[visibleReferences.size()]); } - return new IViewReference[0]; + return visibleReferences.toArray(new IViewReference[visibleReferences.size()]); } /** diff --git a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/api/IWorkbenchPageTest.java b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/api/IWorkbenchPageTest.java index 463c80ff388..802bb96483d 100644 --- a/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/api/IWorkbenchPageTest.java +++ b/tests/org.eclipse.ui.tests/Eclipse UI Tests/org/eclipse/ui/tests/api/IWorkbenchPageTest.java @@ -81,9 +81,12 @@ import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.internal.Workbench; import org.eclipse.ui.internal.WorkbenchPage; import org.eclipse.ui.internal.WorkbenchPlugin; import org.eclipse.ui.internal.WorkbenchWindow; +import org.eclipse.ui.internal.intro.IIntroConstants; +import org.eclipse.ui.internal.intro.IntroDescriptor; import org.eclipse.ui.internal.registry.IActionSetDescriptor; import org.eclipse.ui.internal.registry.PerspectiveDescriptor; import org.eclipse.ui.internal.util.Util; @@ -2563,6 +2566,32 @@ public void testCloseAllPerspectivesDoesNotPromptBug272070() } } + /** + * Tests that views outside of any perspective (e.g. the intro view) are still + * returned by getViewReferences() after all perspectives are closed. See + * https://github.com/eclipse-platform/eclipse.platform.ui/issues/2978 + */ + @Test + public void testGetViewReferencesWithoutPerspective() throws PartInitException { + Workbench workbench = Workbench.getInstance(); + IntroDescriptor oldIntroDescriptor = workbench.getIntroDescriptor(); + workbench.setIntroDescriptor( + (IntroDescriptor) WorkbenchPlugin.getDefault().getIntroRegistry().getIntro("org.eclipse.ui.testintro")); + try { + IViewPart intro = fActivePage.showView(IIntroConstants.INTRO_VIEW_ID); + assertTrue(fActivePage.isPartVisible(intro)); + assertTrue(hasView(intro)); + + fActivePage.closeAllPerspectives(false, false); + + assertEquals(0, fActivePage.getOpenPerspectives().length); + assertTrue(fActivePage.isPartVisible(intro)); + assertTrue(hasView(intro)); + } finally { + workbench.setIntroDescriptor(oldIntroDescriptor); + } + } + /** * Tests that relative view is correctly shown if visible parameter specified. * See bug 538199 - perspectiveExtension: visible="false" not honored when From 116da67863891439f8af5cf82636bae7b892fba9 Mon Sep 17 00:00:00 2001 From: Elsa Zacharia Date: Wed, 23 Sep 2026 11:00:08 +0530 Subject: [PATCH 47/52] Add bookmark feature for resources in eclipse explorers This commit introduces a feature to bookmark a resource by applying a configurable theme foreground color to resources in the explorer and highlight them.These highlighted resources also has entries in the Eclipse Marker's view with Resource, Path, Location, and Type columns. --- bundles/org.eclipse.ui.ide/plugin.properties | 1 + bundles/org.eclipse.ui.ide/plugin.xml | 14 +- .../icons/full/ovr16/bkmrk_ovr.svg | 11 + .../plugin.properties | 10 + .../plugin.xml | 100 ++++++++ .../resources/ResourceBookmarkDecorator.java | 204 ++++++++++++++++ .../resources/ResourceBookmarks.java | 42 ++++ .../resources/actions/SetMarkerOperation.java | 69 ++++++ .../actions/ToggleBookmarkHandler.java | 77 ++++++ .../META-INF/MANIFEST.MF | 1 + .../tests/navigator/BookmarkTestSupport.java | 96 ++++++++ .../tests/navigator/NavigatorTestSuite.java | 4 +- .../ResourceBookmarkDecoratorTest.java | 163 +++++++++++++ .../navigator/SetMarkerOperationTest.java | 228 ++++++++++++++++++ .../navigator/ToggleBookmarkHandlerTest.java | 151 ++++++++++++ 15 files changed, 1168 insertions(+), 3 deletions(-) create mode 100644 bundles/org.eclipse.ui.navigator.resources/icons/full/ovr16/bkmrk_ovr.svg create mode 100644 bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/ResourceBookmarkDecorator.java create mode 100644 bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/ResourceBookmarks.java create mode 100644 bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/SetMarkerOperation.java create mode 100644 bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ToggleBookmarkHandler.java create mode 100644 tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/BookmarkTestSupport.java create mode 100644 tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ResourceBookmarkDecoratorTest.java create mode 100644 tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/SetMarkerOperationTest.java create mode 100644 tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ToggleBookmarkHandlerTest.java diff --git a/bundles/org.eclipse.ui.ide/plugin.properties b/bundles/org.eclipse.ui.ide/plugin.properties index c48a4dc3fc2..4a769aa5963 100644 --- a/bundles/org.eclipse.ui.ide/plugin.properties +++ b/bundles/org.eclipse.ui.ide/plugin.properties @@ -273,6 +273,7 @@ markerGrouping.warnings = Warnings markerGrouping.infos = Infos markerGrouping.type = Type markerGrouping.other = Other Markers +markerTypeCategory.bookmark = Bookmark menu.toggleCoolbar.tooltip = Toggle toolbar visibility menu.toggleStatusBar.tooltip = Toggle the visibility of the status bar on the bottom diff --git a/bundles/org.eclipse.ui.ide/plugin.xml b/bundles/org.eclipse.ui.ide/plugin.xml index 02c99caee6f..864742037dd 100644 --- a/bundles/org.eclipse.ui.ide/plugin.xml +++ b/bundles/org.eclipse.ui.ide/plugin.xml @@ -1593,6 +1593,7 @@ name="%Field.Description"> + visible="true"> + + + + + + + diff --git a/bundles/org.eclipse.ui.navigator.resources/icons/full/ovr16/bkmrk_ovr.svg b/bundles/org.eclipse.ui.navigator.resources/icons/full/ovr16/bkmrk_ovr.svg new file mode 100644 index 00000000000..9c8f1e76d67 --- /dev/null +++ b/bundles/org.eclipse.ui.navigator.resources/icons/full/ovr16/bkmrk_ovr.svg @@ -0,0 +1,11 @@ + + + + diff --git a/bundles/org.eclipse.ui.navigator.resources/plugin.properties b/bundles/org.eclipse.ui.navigator.resources/plugin.properties index c9a28e903b3..9e84787f2d5 100644 --- a/bundles/org.eclipse.ui.navigator.resources/plugin.properties +++ b/bundles/org.eclipse.ui.navigator.resources/plugin.properties @@ -43,3 +43,13 @@ nestedProjects.filters.HideTopLevelProjectIfNested.name=Nested Projects: hide to nestedProjects.filters.HideTopLevelProjectIfNested.description=When a project is shown as nested under its container, hide the view of the project as immediate child of workspace or working set nestedProjects.radioStateName=Nested Project view - Radio State +decorator.bookmark.name=Bookmark Resource +decorator.bookmark.description=Bookmarks resources using a dedicated font color. +command.toggleBookmark.name=Toggle Bookmark +command.toggleBookmark.label=Toggle &Bookmark + +colorDefinition.bookmarkColor.label=Bookmarked Resource Font Color +colorDefinition.bookmarkColor.description=The foreground color used to bookmark resources in different explorers. + +marker.bookmark.name=Bookmark + diff --git a/bundles/org.eclipse.ui.navigator.resources/plugin.xml b/bundles/org.eclipse.ui.navigator.resources/plugin.xml index 7eec1464661..1434963cdcb 100644 --- a/bundles/org.eclipse.ui.navigator.resources/plugin.xml +++ b/bundles/org.eclipse.ui.navigator.resources/plugin.xml @@ -25,6 +25,9 @@ name="group.open" separator="true"/> + @@ -566,6 +569,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %decorator.bookmark.description + + + + + + + %colorDefinition.bookmarkColor.description + + + + + + + listeners = new CopyOnWriteArraySet<>(); + + private final org.eclipse.jface.util.IPropertyChangeListener themeListener = event -> { + String prop = event.getProperty(); + if (HIGHLIGHT_COLOR_ID.equals(prop) || IThemeManager.CHANGE_CURRENT_THEME.equals(prop) + || TREE_TABLE_FONT_ID.equals(prop)) { + IDecoratorManager dm = PlatformUI.getWorkbench().getDecoratorManager(); + dm.update(ID); + } + }; + + private final IResourceChangeListener resourceChangeListener = event -> { + IResourceDelta delta = event.getDelta(); + if (delta == null) { + return; + } + List changed = new ArrayList<>(); + try { + delta.accept(d -> { + IMarkerDelta[] markerDeltas = d.getMarkerDeltas(); + for (IMarkerDelta markerDelta : markerDeltas) { + if (markerDelta.isSubtypeOf(IMarker.BOOKMARK)) { + IResource res = d.getResource(); + if (res != null) { + changed.add(res); + // for explorers such as the Package Explorers + Object javaElement = Platform.getAdapterManager().loadAdapter(res, + JAVA_ELEMENT_CLASS); + if (javaElement != null) { + changed.add(javaElement); + } + } + break; + } + } + return true; + }); + } catch (CoreException e) { + WorkbenchNavigatorPlugin.log("Error processing marker delta for highlight decorator", e.getStatus()); //$NON-NLS-1$ + } + + if (!changed.isEmpty()) { + fireLabelProviderChanged(changed.toArray(new Object[0])); + } + }; + + public ResourceBookmarkDecorator() { + PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(themeListener); + ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener, + IResourceChangeEvent.POST_CHANGE); + } + + @Override + public void decorate(Object element, IDecoration decoration) { + IResource resource = Adapters.adapt(element, IResource.class); + if (resource == null || !resource.isAccessible()) { + return; + } + + boolean hasBookmark = hasBookmarkMarker(resource); + boolean isHighlighted = ResourceBookmarks.isBookmarked(resource); + if (hasBookmark || isHighlighted) { + extracted(decoration); + } + + if (isHighlighted) { + Display display = PlatformUI.isWorkbenchRunning() ? PlatformUI.getWorkbench().getDisplay() : null; + if (display != null && !display.isDisposed()) { + final Color[] colorHolder = new Color[1]; + + Runnable fetcher = () -> { + if (!display.isDisposed()) { + decoration.setFont(JFaceResources.getFontRegistry().getBold(TREE_TABLE_FONT_ID)); + colorHolder[0] = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme() + .getColorRegistry().get(HIGHLIGHT_COLOR_ID); + } + }; + + if (Thread.currentThread() == display.getThread()) { + fetcher.run(); + } else { + display.syncExec(fetcher); + } + + if (colorHolder[0] != null) { + decoration.setForegroundColor(colorHolder[0]); + } + } + } + } + + /** + * @param decoration + */ + private void extracted(IDecoration decoration) { + ImageDescriptor overlay = ResourceLocator + .imageDescriptorFromBundle(WorkbenchNavigatorPlugin.class, "icons/full/ovr16/bkmrk_ovr.svg") //$NON-NLS-1$ + .orElse(null); + if (overlay != null) { + decoration.addOverlay(overlay, IDecoration.TOP_RIGHT); + } + } + + private static boolean hasBookmarkMarker(IResource resource) { + try { + return resource.findMarkers(IMarker.BOOKMARK, true, IResource.DEPTH_ZERO).length > 0; + } catch (CoreException e) { + return false; + } + } + + @Override + public void addListener(ILabelProviderListener listener) { + if (listener != null) { + listeners.add(listener); + } + } + + @Override + public void removeListener(ILabelProviderListener listener) { + if (listener != null) { + listeners.remove(listener); + } + } + + private void fireLabelProviderChanged(Object[] elements) { + LabelProviderChangedEvent event = new LabelProviderChangedEvent(this, elements); + for (ILabelProviderListener listener : listeners) { + listener.labelProviderChanged(event); + } + } + + @Override + public void dispose() { + ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener); + if (PlatformUI.isWorkbenchRunning()) { + PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(themeListener); + } + listeners.clear(); + } + + @Override + public boolean isLabelProperty(Object element, String property) { + return true; + } +} diff --git a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/ResourceBookmarks.java b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/ResourceBookmarks.java new file mode 100644 index 00000000000..c0060364295 --- /dev/null +++ b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/ResourceBookmarks.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.navigator.resources; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; + +public final class ResourceBookmarks { + + /** + * Marker type of the bookmark markers. + */ + public static final String MARKER_TYPE = "org.eclipse.ui.navigator.resources.highlightMarker"; //$NON-NLS-1$ + + private ResourceBookmarks() { + } + + /** + * Checks whether the given resource currently carries a bookmark marker or not. + */ + public static boolean isBookmarked(IResource resource) { + if (resource == null || !resource.isAccessible()) { + return false; + } + try { + return resource.findMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO).length > 0; + } catch (CoreException e) { + return false; + } + } +} diff --git a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/SetMarkerOperation.java b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/SetMarkerOperation.java new file mode 100644 index 00000000000..a58025fce2e --- /dev/null +++ b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/SetMarkerOperation.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.navigator.resources.actions; + +import java.util.List; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.ISchedulingRule; +import org.eclipse.core.runtime.jobs.MultiRule; +import org.eclipse.ui.internal.navigator.resources.ResourceBookmarks; + +/** + * Add or remove markers to resources. + */ +public final class SetMarkerOperation implements IWorkspaceRunnable { + + private final List toAdd; + + private final List toRemove; + + public SetMarkerOperation(List toAdd, List toRemove) { + this.toAdd = toAdd; + this.toRemove = toRemove; + } + + public boolean isEmpty() { + return toAdd.isEmpty() && toRemove.isEmpty(); + } + + public ISchedulingRule getRule() { + ISchedulingRule rule = null; + for (List resources : List.of(toAdd, toRemove)) { + for (IResource resource : resources) { + rule = MultiRule.combine(rule, resource.getWorkspace().getRuleFactory().markerRule(resource)); + } + } + return rule; + } + + @Override + public void run(IProgressMonitor monitor) throws CoreException { + for (IResource resource : toRemove) { + for (IMarker marker : resource.findMarkers(ResourceBookmarks.MARKER_TYPE, false, IResource.DEPTH_ZERO)) { + marker.delete(); + } + } + for (IResource resource : toAdd) { + if (resource.findMarkers(ResourceBookmarks.MARKER_TYPE, false, IResource.DEPTH_ZERO).length == 0) { + IMarker marker = resource.createMarker(ResourceBookmarks.MARKER_TYPE); + marker.setAttribute(IMarker.MESSAGE, resource.getName()); + } + } + } +} diff --git a/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ToggleBookmarkHandler.java b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ToggleBookmarkHandler.java new file mode 100644 index 00000000000..1aff750aa6e --- /dev/null +++ b/bundles/org.eclipse.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ToggleBookmarkHandler.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.navigator.resources.actions; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Adapters; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.handlers.HandlerUtil; +import org.eclipse.ui.internal.navigator.resources.ResourceBookmarks; +import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin; + +/** + * Handler to enable toggle markers on selected resources. + */ +public class ToggleBookmarkHandler extends AbstractHandler { + + @Override + public Object execute(ExecutionEvent event) { + ISelection selection = HandlerUtil.getActiveMenuSelection(event); + if (selection == null) { + selection = HandlerUtil.getCurrentSelection(event); + } + if (!(selection instanceof IStructuredSelection structuredSelection)) { + return null; + } + + List toAdd = new ArrayList<>(); + List toRemove = new ArrayList<>(); + for (Object obj : structuredSelection.toList()) { + IResource resource = Adapters.adapt(obj, IResource.class); + if (resource == null || !resource.isAccessible()) { + continue; + } + if (ResourceBookmarks.isBookmarked(resource)) { + toRemove.add(resource); + } else { + toAdd.add(resource); + } + } + + SetMarkerOperation operation = new SetMarkerOperation(toAdd, toRemove); + if (!operation.isEmpty()) { + run(operation); + } + return null; + } + + private void run(SetMarkerOperation operation) { + try { + ResourcesPlugin.getWorkspace().run(operation, operation.getRule(), IWorkspace.AVOID_UPDATE, + new NullProgressMonitor()); + } catch (CoreException e) { + WorkbenchNavigatorPlugin.log("Failed to toggle bookmark marker", e.getStatus()); //$NON-NLS-1$ + } + } +} diff --git a/tests/org.eclipse.ui.tests.navigator/META-INF/MANIFEST.MF b/tests/org.eclipse.ui.tests.navigator/META-INF/MANIFEST.MF index 5eeceb2adcb..210ee4da70d 100644 --- a/tests/org.eclipse.ui.tests.navigator/META-INF/MANIFEST.MF +++ b/tests/org.eclipse.ui.tests.navigator/META-INF/MANIFEST.MF @@ -5,6 +5,7 @@ Bundle-SymbolicName: org.eclipse.ui.tests.navigator;singleton:=true Bundle-Version: 3.8.500.qualifier Bundle-Localization: plugin Require-Bundle: org.eclipse.core.resources, + org.eclipse.core.expressions, org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", org.eclipse.ui.navigator;bundle-version="3.8.0", org.eclipse.ui, diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/BookmarkTestSupport.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/BookmarkTestSupport.java new file mode 100644 index 00000000000..d337e24b2f3 --- /dev/null +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/BookmarkTestSupport.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.navigator; + +import java.io.ByteArrayInputStream; +import java.util.Collections; + +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.expressions.EvaluationContext; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.ISources; +import org.eclipse.ui.internal.navigator.resources.ResourceBookmarks; +import org.eclipse.ui.internal.navigator.resources.actions.ToggleBookmarkHandler; + +/** + * Shared helpers of the bookmark toggle tests. + */ +final class BookmarkTestSupport { + + private BookmarkTestSupport() { + } + + static IProject createProject(String prefix) throws CoreException { + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(prefix + System.nanoTime()); + project.create(null); + project.open(null); + return project; + } + + static IFolder createFolder(IProject project, String name) throws CoreException { + IFolder folder = project.getFolder(name); + folder.create(true, true, null); + return folder; + } + + static IFile createFile(IProject project, String name) throws CoreException { + IFile file = project.getFile(name); + file.create(new ByteArrayInputStream(new byte[0]), true, null); + return file; + } + + static void deleteProjects(IProject... projects) throws CoreException { + for (IProject project : projects) { + if (project != null && project.exists()) { + project.delete(true, true, null); + } + } + } + + /** + * Creates an event whose context holds the given selections. A + * null selection leaves the variable undefined. + */ + static ExecutionEvent event(ISelection menuSelection, ISelection currentSelection) { + EvaluationContext context = new EvaluationContext(null, new Object()); + if (menuSelection != null) { + context.addVariable(ISources.ACTIVE_MENU_SELECTION_NAME, menuSelection); + } + if (currentSelection != null) { + context.addVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME, currentSelection); + } + return new ExecutionEvent(null, Collections.emptyMap(), null, context); + } + + /** Executes the handler on the given elements as the active menu selection. */ + static Object toggle(Object... elements) { + return execute(event(new StructuredSelection(elements), null)); + } + + static Object execute(ExecutionEvent event) { + return new ToggleBookmarkHandler().execute(event); + } + + /** Number of bookmark markers of the toggle command on the resource. */ + static int bookmarkCount(IResource resource) throws CoreException { + return resource.findMarkers(ResourceBookmarks.MARKER_TYPE, false, IResource.DEPTH_ZERO).length; + } +} diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/NavigatorTestSuite.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/NavigatorTestSuite.java index fe0e346ae1c..9db48ca968e 100644 --- a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/NavigatorTestSuite.java +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/NavigatorTestSuite.java @@ -26,9 +26,8 @@ import org.eclipse.ui.tests.navigator.resources.NestedResourcesTests; import org.eclipse.ui.tests.navigator.resources.PathComparatorTest; import org.eclipse.ui.tests.navigator.resources.ResourceMgmtActionProviderTests; - -import org.junit.platform.suite.api.Suite; import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; @Suite @SelectClasses({ InitialActivationTest.class, ActionProviderTest.class, ExtensionsTest.class, FilterTest.class, @@ -40,6 +39,7 @@ NestedResourcesTests.class, PathComparatorTest.class, FoldersAsProjectsContributionTest.class, GoBackForwardsTest.class, CopyPasteActionTest.class, CloseUnrelatedProjectsActionTest.class, + ResourceBookmarkDecoratorTest.class, ToggleBookmarkHandlerTest.class, SetMarkerOperationTest.class, // DnDTest.class, // DnDTest.testSetDragOperation() fails }) public final class NavigatorTestSuite { diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ResourceBookmarkDecoratorTest.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ResourceBookmarkDecoratorTest.java new file mode 100644 index 00000000000..e24445b40b5 --- /dev/null +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ResourceBookmarkDecoratorTest.java @@ -0,0 +1,163 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.navigator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Adapters; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.resource.ColorRegistry; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.ui.IDecoratorManager; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.internal.decorators.DecoratorManager; +import org.eclipse.ui.internal.navigator.resources.ResourceBookmarkDecorator; +import org.eclipse.ui.internal.navigator.resources.ResourceBookmarks; +import org.eclipse.ui.tests.harness.util.DisplayHelper; +import org.eclipse.ui.tests.navigator.util.TestWorkspace; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Verifies that adding and removing the bookmark marker updates an existing + * navigator item through the resource change listener of + * {@link ResourceBookmarkDecorator}, without any manual viewer refresh. + */ +public class ResourceBookmarkDecoratorTest extends NavigatorTestBase { + + private static final long TIMEOUT = 10000; + + /** Distinct from the default foreground, which would make the test vacuous. */ + private static final RGB BOOKMARK_RGB = new RGB(12, 200, 34); + + private boolean decoratorWasEnabled; + private RGB originalBookmarkRgb; + private IProject p1Project; + + public ResourceBookmarkDecoratorTest() { + _navigatorInstanceId = "org.eclipse.ui.tests.navigator.OverrideTestView"; + } + + @Override + @BeforeEach + public void setUp() throws CoreException { + super.setUp(); + + _contentService.bindExtensions(new String[] { COMMON_NAVIGATOR_RESOURCE_EXT }, true); + _contentService.getActivationService().activateExtensions(new String[] { COMMON_NAVIGATOR_RESOURCE_EXT }, true); + + IDecoratorManager manager = PlatformUI.getWorkbench().getDecoratorManager(); + decoratorWasEnabled = manager.getEnabled(ResourceBookmarkDecorator.ID); + manager.setEnabled(ResourceBookmarkDecorator.ID, true); + + ColorRegistry colors = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry(); + originalBookmarkRgb = colors.getRGB(ResourceBookmarkDecorator.HIGHLIGHT_COLOR_ID); + colors.put(ResourceBookmarkDecorator.HIGHLIGHT_COLOR_ID, BOOKMARK_RGB); + + p1Project = ResourcesPlugin.getWorkspace().getRoot().getProject(TestWorkspace.P1_PROJECT_NAME); + assertFalse(ResourceBookmarks.isBookmarked(p1Project), "project must not be bookmarked initially"); + + waitForDecorationUpdate(); + } + + @AfterEach + public void restoreDecoratorState() throws CoreException { + PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry() + .put(ResourceBookmarkDecorator.HIGHLIGHT_COLOR_ID, originalBookmarkRgb); + PlatformUI.getWorkbench().getDecoratorManager().setEnabled(ResourceBookmarkDecorator.ID, decoratorWasEnabled); + } + + @Test + public void testBookmarkMarkerAddsAndRemovesDecoration() throws Exception { + TreeItem item = findItem(p1Project); + assertNotNull(item, "no tree item for " + p1Project); + Image plainImage = item.getImage(0); + assertNotEquals(boldFont(), item.getFont(0), "item must not be bold initially"); + assertNotEquals(BOOKMARK_RGB, foreground(item), "item must not have the bookmark color initially"); + + IMarker marker = p1Project.createMarker(ResourceBookmarks.MARKER_TYPE); + assertTrue(ResourceBookmarks.isBookmarked(p1Project)); + waitForBookmarkDecoration(true); + + item = findItem(p1Project); + assertNotNull(item, "no tree item for " + p1Project); + assertNotEquals(plainImage, item.getImage(0), "bookmark overlay missing"); + assertEquals(boldFont(), item.getFont(0), "bold font missing"); + assertEquals(BOOKMARK_RGB, foreground(item), "bookmark foreground color missing"); + + marker.delete(); + assertFalse(ResourceBookmarks.isBookmarked(p1Project)); + waitForBookmarkDecoration(false); + + item = findItem(p1Project); + assertNotNull(item, "no tree item for " + p1Project); + assertEquals(plainImage, item.getImage(0), "bookmark overlay not removed"); + assertNotEquals(boldFont(), item.getFont(0), "bold font not removed"); + assertNotEquals(BOOKMARK_RGB, foreground(item), "bookmark foreground color not removed"); + } + + /** + * Waits until the bold font of the item matches the expected state and the + * decoration jobs, including the update job that applies the results to the + * viewer, have finished. The update job runs in the UI thread, so the event + * loop has to keep spinning instead of joining the job family. + */ + private void waitForBookmarkDecoration(boolean decorated) { + DisplayHelper.waitForCondition(Display.getCurrent(), TIMEOUT, () -> { + TreeItem item = findItem(p1Project); + return item != null && boldFont().equals(item.getFont(0)) == decorated; + }); + waitForDecorationUpdate(); + } + + private static void waitForDecorationUpdate() { + boolean idle = DisplayHelper.waitForCondition(Display.getCurrent(), TIMEOUT, + () -> Job.getJobManager().find(DecoratorManager.FAMILY_DECORATE).length == 0); + assertTrue(idle, "decoration did not finish within " + TIMEOUT + "ms"); + } + + private TreeItem findItem(IResource resource) { + for (TreeItem item : _viewer.getTree().getItems()) { + if (resource.equals(Adapters.adapt(item.getData(), IResource.class))) { + return item; + } + } + return null; + } + + private static Font boldFont() { + return JFaceResources.getFontRegistry().getBold(ResourceBookmarkDecorator.TREE_TABLE_FONT_ID); + } + + private static RGB foreground(TreeItem item) { + Color color = item.getForeground(0); + return color == null ? null : color.getRGB(); + } +} diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/SetMarkerOperationTest.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/SetMarkerOperationTest.java new file mode 100644 index 00000000000..06be62ce8fb --- /dev/null +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/SetMarkerOperationTest.java @@ -0,0 +1,228 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.navigator; + +import static org.eclipse.ui.tests.navigator.BookmarkTestSupport.bookmarkCount; +import static org.eclipse.ui.tests.navigator.BookmarkTestSupport.toggle; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.jobs.ISchedulingRule; +import org.eclipse.ui.internal.navigator.resources.ResourceBookmarks; +import org.eclipse.ui.internal.navigator.resources.actions.SetMarkerOperation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests {@link SetMarkerOperation}, both directly and through the marker + * changes that the toggle command applies with it. + */ +public class SetMarkerOperationTest { + + private IProject project; + private IProject otherProject; + private IFolder folder; + private IFile file; + private IFile otherFile; + + @BeforeEach + public void setUp() throws CoreException { + project = BookmarkTestSupport.createProject("SetMarkerOperationTest_"); + otherProject = BookmarkTestSupport.createProject("SetMarkerOperationTest_other_"); + folder = BookmarkTestSupport.createFolder(project, "folder"); + file = BookmarkTestSupport.createFile(project, "a.txt"); + otherFile = BookmarkTestSupport.createFile(project, "b.txt"); + } + + @AfterEach + public void tearDown() throws CoreException { + BookmarkTestSupport.deleteProjects(project, otherProject); + } + + @Test + public void testAddedMarkerHasTypeAndMessageOfResourceName() throws Exception { + toggle(file); + + IMarker[] markers = file.findMarkers(ResourceBookmarks.MARKER_TYPE, false, IResource.DEPTH_ZERO); + assertEquals(1, markers.length); + assertEquals(file.getName(), markers[0].getAttribute(IMarker.MESSAGE)); + } + + @Test + public void testMarkersAreAddedToFilesFoldersAndProjects() throws Exception { + toggle(file, folder, project); + + assertEquals(1, bookmarkCount(file)); + assertEquals(1, bookmarkCount(folder)); + assertEquals(1, bookmarkCount(project)); + } + + @Test + public void testRemoveDeletesAllMarkersOfTheResource() throws Exception { + file.createMarker(ResourceBookmarks.MARKER_TYPE); + file.createMarker(ResourceBookmarks.MARKER_TYPE); + assertEquals(2, bookmarkCount(file)); + + toggle(file); + + assertEquals(0, bookmarkCount(file)); + } + + @Test + public void testRepeatedToggleDoesNotAccumulateMarkers() throws Exception { + for (int i = 0; i < 4; i++) { + toggle(file); + assertEquals((i + 1) % 2, bookmarkCount(file), "after toggle " + (i + 1)); + } + } + + @Test + public void testMixedSelectionAddsAndRemovesInOneRun() throws Exception { + otherFile.createMarker(ResourceBookmarks.MARKER_TYPE); + + toggle(file, otherFile); + + assertEquals(1, bookmarkCount(file)); + assertEquals(0, bookmarkCount(otherFile)); + } + + @Test + public void testResourcesOutsideTheSelectionAreUntouched() throws Exception { + otherFile.createMarker(ResourceBookmarks.MARKER_TYPE); + + toggle(file); + + assertEquals(1, bookmarkCount(file)); + assertEquals(1, bookmarkCount(otherFile)); + assertEquals(0, bookmarkCount(folder)); + assertEquals(0, bookmarkCount(project)); + } + + @Test + public void testSelectionAcrossProjects() throws Exception { + IFile fileInOtherProject = BookmarkTestSupport.createFile(otherProject, "c.txt"); + fileInOtherProject.createMarker(ResourceBookmarks.MARKER_TYPE); + + toggle(file, fileInOtherProject, otherProject); + + assertEquals(1, bookmarkCount(file)); + assertEquals(0, bookmarkCount(fileInOtherProject)); + assertEquals(1, bookmarkCount(otherProject)); + } + + @Test + public void testOtherMarkerTypesAreKept() throws Exception { + file.createMarker(IMarker.BOOKMARK); + file.createMarker(IMarker.PROBLEM); + + toggle(file); + assertEquals(1, bookmarkCount(file)); + assertEquals(1, file.findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_ZERO).length); + assertEquals(1, file.findMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO).length); + + toggle(file); + assertEquals(0, bookmarkCount(file)); + assertEquals(1, file.findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_ZERO).length); + assertEquals(1, file.findMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO).length); + } + + @Test + public void testChildMarkersAreNotAffectedByTogglingTheParent() throws Exception { + file.createMarker(ResourceBookmarks.MARKER_TYPE); + + toggle(project); + + assertEquals(1, bookmarkCount(project)); + assertEquals(1, bookmarkCount(file)); + } + + @Test + public void testDirectRunDoesNotAddSecondMarkerToBookmarkedResource() throws Exception { + file.createMarker(ResourceBookmarks.MARKER_TYPE); + + new SetMarkerOperation(List.of(file), List.of()).run(null); + + assertEquals(1, bookmarkCount(file)); + } + + @Test + public void testDirectRunAddsMarkerWithMessage() throws Exception { + new SetMarkerOperation(List.of(file), List.of()).run(null); + + IMarker[] markers = file.findMarkers(ResourceBookmarks.MARKER_TYPE, false, IResource.DEPTH_ZERO); + assertEquals(1, markers.length); + assertEquals(file.getName(), markers[0].getAttribute(IMarker.MESSAGE)); + } + + @Test + public void testDirectRunRemovesMarkersOfResourceWithoutMarkers() throws Exception { + new SetMarkerOperation(List.of(), List.of(file)).run(null); + + assertEquals(0, bookmarkCount(file)); + } + + @Test + public void testResourceInBothListsEndsUpWithOneMarker() throws Exception { + // removals run before additions + file.createMarker(ResourceBookmarks.MARKER_TYPE); + otherFile.createMarker(ResourceBookmarks.MARKER_TYPE); + otherFile.createMarker(ResourceBookmarks.MARKER_TYPE); + + new SetMarkerOperation(List.of(file, otherFile), List.of(file, otherFile)).run(null); + + assertEquals(1, bookmarkCount(file)); + assertEquals(1, bookmarkCount(otherFile)); + } + + @Test + public void testIsEmpty() { + assertTrue(new SetMarkerOperation(List.of(), List.of()).isEmpty()); + assertFalse(new SetMarkerOperation(List.of(file), List.of()).isEmpty()); + assertFalse(new SetMarkerOperation(List.of(), List.of(file)).isEmpty()); + assertFalse(new SetMarkerOperation(List.of(file), List.of(otherFile)).isEmpty()); + } + + @Test + public void testRuleOfEmptyOperationIsNull() { + assertNull(new SetMarkerOperation(List.of(), List.of()).getRule()); + } + + @Test + public void testRuleCoversMarkerRulesOfAllResources() { + IFile fileInOtherProject = otherProject.getFile("c.txt"); + SetMarkerOperation operation = new SetMarkerOperation(List.of(file), List.of(fileInOtherProject)); + + ISchedulingRule rule = operation.getRule(); + + for (IResource resource : List.of(file, fileInOtherProject)) { + ISchedulingRule markerRule = resource.getWorkspace().getRuleFactory().markerRule(resource); + if (markerRule != null) { + assertNotNull(rule, "rule missing for " + resource); + assertTrue(rule.contains(markerRule), "rule does not cover " + resource); + } + } + } +} diff --git a/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ToggleBookmarkHandlerTest.java b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ToggleBookmarkHandlerTest.java new file mode 100644 index 00000000000..b6b64c49310 --- /dev/null +++ b/tests/org.eclipse.ui.tests.navigator/src/org/eclipse/ui/tests/navigator/ToggleBookmarkHandlerTest.java @@ -0,0 +1,151 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.navigator; + +import static org.eclipse.ui.tests.navigator.BookmarkTestSupport.bookmarkCount; +import static org.eclipse.ui.tests.navigator.BookmarkTestSupport.event; +import static org.eclipse.ui.tests.navigator.BookmarkTestSupport.execute; +import static org.eclipse.ui.tests.navigator.BookmarkTestSupport.toggle; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.ui.internal.navigator.resources.actions.ToggleBookmarkHandler; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests how {@link ToggleBookmarkHandler} reads the selection of the execution + * event and which elements it acts on. + */ +public class ToggleBookmarkHandlerTest { + + private IProject project; + private IFile file; + private IFile otherFile; + + @BeforeEach + public void setUp() throws CoreException { + project = BookmarkTestSupport.createProject("ToggleBookmarkHandlerTest_"); + file = BookmarkTestSupport.createFile(project, "a.txt"); + otherFile = BookmarkTestSupport.createFile(project, "b.txt"); + } + + @AfterEach + public void tearDown() throws CoreException { + BookmarkTestSupport.deleteProjects(project); + } + + @Test + public void testMenuSelectionIsToggled() throws Exception { + toggle(file); + + assertEquals(1, bookmarkCount(file)); + assertEquals(0, bookmarkCount(otherFile)); + } + + @Test + public void testExecuteReturnsNull() { + assertNull(toggle(file)); + } + + @Test + public void testFallsBackToCurrentSelectionWithoutMenuSelection() throws Exception { + execute(event(null, new StructuredSelection(file))); + + assertEquals(1, bookmarkCount(file)); + } + + @Test + public void testMenuSelectionWinsOverCurrentSelection() throws Exception { + execute(event(new StructuredSelection(file), new StructuredSelection(otherFile))); + + assertEquals(1, bookmarkCount(file)); + assertEquals(0, bookmarkCount(otherFile)); + } + + @Test + public void testNoSelectionDoesNothing() throws Exception { + assertNull(execute(event(null, null))); + + assertEquals(0, bookmarkCount(file)); + assertEquals(0, bookmarkCount(project)); + } + + @Test + public void testEmptySelectionDoesNothing() throws Exception { + toggle(); + + assertEquals(0, bookmarkCount(file)); + } + + @Test + public void testNonStructuredMenuSelectionIsNotReplacedByCurrentSelection() throws Exception { + ISelection nonStructured = () -> false; + + execute(event(nonStructured, new StructuredSelection(file))); + + assertEquals(0, bookmarkCount(file)); + } + + @Test + public void testNonResourceElementsAreIgnored() throws Exception { + toggle(new Object(), "text", file); + + assertEquals(1, bookmarkCount(file)); + } + + @Test + public void testElementAdaptingToResourceIsToggled() throws Exception { + IAdaptable adaptable = new IAdaptable() { + @Override + public T getAdapter(Class adapter) { + return adapter == IResource.class ? adapter.cast(file) : null; + } + }; + + toggle(adaptable); + + assertEquals(1, bookmarkCount(file)); + } + + @Test + public void testResourceOfClosedProjectIsSkipped() throws Exception { + project.close(null); + + toggle(file, project); + + project.open(null); + assertEquals(0, bookmarkCount(file)); + assertEquals(0, bookmarkCount(project)); + } + + @Test + public void testDeletedResourceIsSkippedAndOthersAreStillToggled() throws Exception { + file.delete(true, null); + + toggle(file, otherFile); + + assertFalse(file.exists()); + assertEquals(1, bookmarkCount(otherFile)); + } +} From 6205f1b680d921af9656a636e5909752eccb64fd Mon Sep 17 00:00:00 2001 From: Federico Jeanne Date: Thu, 12 Nov 2026 16:25:36 +0100 Subject: [PATCH 48/52] Do not block the UI thread on the workspace lock when opening a match Opening a search match in an editor that is not a text editor (for example the plug-in manifest editor) froze the UI for as long as another thread held the workspace lock, up to several tens of seconds during startup. The search selected the match through a temporary marker and created, changed and deleted that marker on the UI thread. Each of these steps waited for the workspace lock, so a slow resource change listener, such as the Java model update after a classpath change, blocked the UI up to three times per click. Opening a match no longer waits for the workspace lock. Editors that provide a text editor through an adapter, like many multi-page and wrapper editors, select the match directly, without a marker. In multi-page editors this selects in the active text page. All other editors open at once and show the selection as soon as the workspace allows it. When the user opens several matches in a row, only the latest one is selected, and nothing is selected in an editor that was closed or shows another input meanwhile. A failure to create the marker is now logged instead of shown in a dialog. The marker is created in one workspace operation by a background job, and the editor reveals it asynchronously in the UI thread. The jobs share one scheduling rule, so pending requests that are superseded are cancelled before they touch the workspace. Contributes to: https://github.com/eclipse-pde/eclipse.pde/issues/1715 Assisted-by: Claude Opus 5.5 --- .../search/internal/ui/SearchMessages.java | 2 + .../internal/ui/SearchMessages.properties | 2 + .../search/internal/ui/text/EditorOpener.java | 218 ++++++++++-- tests/org.eclipse.search.tests/plugin.xml | 17 + .../search/tests/GotoMarkerOnlyEditor.java | 98 ++++++ .../search/tests/TextEditorWrapper.java | 70 ++++ .../tests/filesearch/AllFileSearchTests.java | 1 + .../tests/filesearch/EditorOpenerTest.java | 316 ++++++++++++++++++ 8 files changed, 702 insertions(+), 22 deletions(-) create mode 100644 tests/org.eclipse.search.tests/src/org/eclipse/search/tests/GotoMarkerOnlyEditor.java create mode 100644 tests/org.eclipse.search.tests/src/org/eclipse/search/tests/TextEditorWrapper.java create mode 100644 tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/EditorOpenerTest.java diff --git a/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.java b/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.java index 8862ace200e..3d9d6f90624 100644 --- a/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.java +++ b/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.java @@ -229,4 +229,6 @@ private SearchMessages() { public static String FileSearchQuery_pluralPatternWithFileExt; public static String DragAdapter_title; public static String DragAdapter_checkDeleteMessage; + public static String EditorOpener_selectMatch_jobName; + public static String EditorOpener_deleteMarker_jobName; } diff --git a/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.properties b/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.properties index 5d4cb8b3daa..a075e540b27 100644 --- a/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.properties +++ b/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchMessages.properties @@ -264,3 +264,5 @@ RemovePotentialMatchesAction_dialog_message= The current search result does not OpenWithMenu_label= Open Wit&h +EditorOpener_selectMatch_jobName=Selecting search match +EditorOpener_deleteMarker_jobName=Deleting search marker diff --git a/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java b/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java index 33306db9c86..467025cb19c 100644 --- a/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java +++ b/bundles/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,9 +13,18 @@ *******************************************************************************/ package org.eclipse.search.internal.ui.text; -import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.eclipse.swt.widgets.Display; + +import org.eclipse.core.runtime.Adapters; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.ISchedulingRule; +import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; @@ -35,20 +44,57 @@ import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.search.internal.ui.SearchMessages; +import org.eclipse.search.internal.ui.SearchPlugin; import org.eclipse.search.ui.NewSearchUI; public class EditorOpener { + /** + * Family of the background jobs that create and delete the temporary search + * markers. It lets tests wait for these jobs. + */ + public static final Object MARKER_JOB_FAMILY = new Object(); + + /** + * Lets the marker requests run one after the other, so that at most one of them + * waits for the workspace lock. Static, because openers can be created per + * call. + */ + private static final ISchedulingRule MARKER_RULE = new ISchedulingRule() { + @Override + public boolean contains(ISchedulingRule rule) { + return rule == this; + } + + @Override + public boolean isConflicting(ISchedulingRule rule) { + return rule == this; + } + }; + private IEditorReference fReusedEditor; + /** + * The latest request that goes through a temporary marker, shared by all + * openers so that only the latest click counts; only accessed in the UI thread. + */ + private static MarkerRequest fgMarkerRequest; + public IEditorPart open(IWorkbenchPage wbPage, IFile file, boolean activate) throws PartInitException { + cancelMarkerRequest(); if (NewSearchUI.reuseEditor()) { return showWithReuse(file, wbPage, getEditorID(file), activate); } return showWithoutReuse(file, wbPage, getEditorID(file), activate); } + /** + * Opens the file and selects the given range. For editors that neither are nor + * adapt to {@link ITextEditor}, the range is selected asynchronously through a + * temporary marker, so that the UI thread does not wait for the workspace lock. + */ public IEditorPart openAndSelect(IWorkbenchPage wbPage, IFile file, int offset, int length, boolean activate) throws PartInitException { + cancelMarkerRequest(); String editorId= null; IEditorDescriptor desc = IDE.getEditorDescriptor(file, true, true); if (desc == null || !desc.isInternal()) { @@ -64,10 +110,14 @@ public IEditorPart openAndSelect(IWorkbenchPage wbPage, IFile file, int offset, editor= showWithoutReuse(file, wbPage, editorId, activate); } - if (editor instanceof ITextEditor textEditor) { + if (editor == null) { + return null; + } + ITextEditor textEditor = Adapters.adapt(editor, ITextEditor.class); + if (textEditor != null) { textEditor.selectAndReveal(offset, length); - } else if (editor != null) { - showWithMarker(editor, file, offset, length); + } else { + showWithMarker(wbPage, editor, file, offset, length); } return editor; } @@ -128,26 +178,150 @@ private IEditorPart showWithReuse(IFile file, IWorkbenchPage page, String editor return editor; } - private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException { - IMarker marker= null; - try { - marker= file.createMarker(NewSearchUI.SEARCH_MARKER); - HashMap attributes= new HashMap<>(4); - attributes.put(IMarker.CHAR_START, Integer.valueOf(offset)); - attributes.put(IMarker.CHAR_END, Integer.valueOf(offset + length)); - marker.setAttributes(attributes); - IDE.gotoMarker(editor, marker); - } catch (CoreException e) { - throw new PartInitException(SearchMessages.FileSearchPage_error_marker, e); - } finally { - if (marker != null) { - try { - marker.delete(); - } catch (CoreException e) { - // ignore + private void showWithMarker(IWorkbenchPage page, IEditorPart editor, IFile file, int offset, int length) { + MarkerRequest request = new MarkerRequest(page, editor, file, offset, length); + fgMarkerRequest = request; + request.schedule(); + } + + private static void cancelMarkerRequest() { + if (fgMarkerRequest != null) { + fgMarkerRequest.cancel(); + fgMarkerRequest = null; + } + } + + /** + * Creates the temporary marker in the background, reveals it in the editor in + * the UI thread and deletes it in the background again. + */ + private final class MarkerRequest extends Job { + + private final Display fDisplay; + private final IWorkbenchPage fPage; + private final IEditorPart fEditor; + private final IEditorInput fInput; + private final IFile fFile; + private final int fOffset; + private final int fLength; + + MarkerRequest(IWorkbenchPage page, IEditorPart editor, IFile file, int offset, int length) { + super(SearchMessages.EditorOpener_selectMatch_jobName); + fDisplay = Display.getCurrent(); + fPage = page; + fEditor = editor; + fInput = editor.getEditorInput(); + fFile = file; + fOffset = offset; + fLength = length; + setSystem(true); + setRule(MARKER_RULE); + } + + @Override + public boolean belongsTo(Object family) { + return family == MARKER_JOB_FAMILY; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + if (monitor.isCanceled()) { + clearIfLatest(); + return Status.CANCEL_STATUS; + } + IMarker marker; + try { + marker = fFile.createMarker(NewSearchUI.SEARCH_MARKER, Map.of(IMarker.CHAR_START, + Integer.valueOf(fOffset), IMarker.CHAR_END, Integer.valueOf(fOffset + fLength))); + } catch (CoreException e) { + SearchPlugin.log( + new Status(IStatus.ERROR, SearchPlugin.getID(), SearchMessages.FileSearchPage_error_marker, e)); + clearIfLatest(); + return Status.OK_STATUS; + } + if (monitor.isCanceled() || fDisplay == null || fDisplay.isDisposed()) { + deleteMarkerNow(marker); + clearIfLatest(); + return Status.CANCEL_STATUS; + } + try { + fDisplay.asyncExec(() -> { + boolean latest = isLatestRequest(); + if (latest) { + fgMarkerRequest = null; + } + try { + if (latest && isEditorStillShowingInput()) { + IDE.gotoMarker(fEditor, marker); + } + } finally { + deleteMarker(marker); + } + }); + } catch (RuntimeException e) { + // display disposed in the meantime + deleteMarkerNow(marker); + } + return Status.OK_STATUS; + } + + /** Clears the latest request in the UI thread if it still is this one. */ + private void clearIfLatest() { + if (fDisplay == null || fDisplay.isDisposed()) { + return; + } + try { + fDisplay.asyncExec(() -> { + if (isLatestRequest()) { + fgMarkerRequest = null; + } + }); + } catch (RuntimeException e) { + // display disposed in the meantime + } + } + + private boolean isLatestRequest() { + return fgMarkerRequest == this; + } + + private boolean isEditorStillShowingInput() { + return isOpen() && Objects.equals(fInput, fEditor.getEditorInput()); + } + + private boolean isOpen() { + for (IEditorReference reference : fPage.getEditorReferences()) { + if (reference.getEditor(false) == fEditor) { + return true; } } + return false; + } + } + + private static void deleteMarkerNow(IMarker marker) { + try { + marker.delete(); + } catch (CoreException e) { + // the resource is gone already } } + private static void deleteMarker(IMarker marker) { + Job deleteJob = new Job(SearchMessages.EditorOpener_deleteMarker_jobName) { + @Override + protected IStatus run(IProgressMonitor monitor) { + deleteMarkerNow(marker); + return Status.OK_STATUS; + } + + @Override + public boolean belongsTo(Object family) { + return family == MARKER_JOB_FAMILY; + } + }; + deleteJob.setSystem(true); + deleteJob.schedule(); + } + } diff --git a/tests/org.eclipse.search.tests/plugin.xml b/tests/org.eclipse.search.tests/plugin.xml index 7d0e1049c98..aa8b4550409 100644 --- a/tests/org.eclipse.search.tests/plugin.xml +++ b/tests/org.eclipse.search.tests/plugin.xml @@ -9,5 +9,22 @@ label="Test Search Engine"> + + + + + + diff --git a/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/GotoMarkerOnlyEditor.java b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/GotoMarkerOnlyEditor.java new file mode 100644 index 00000000000..75719492b65 --- /dev/null +++ b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/GotoMarkerOnlyEditor.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Vector Informatik GmbH - initial API and implementation + *******************************************************************************/ +package org.eclipse.search.tests; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; + +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IMarker; + +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorSite; +import org.eclipse.ui.ide.IGotoMarker; +import org.eclipse.ui.part.EditorPart; + +/** + * Test editor that is not an {@code ITextEditor} and only adapts to {@link IGotoMarker}. It records + * every {@code gotoMarker} call. + */ +public class GotoMarkerOnlyEditor extends EditorPart { + + public static final String ID= "org.eclipse.search.tests.GotoMarkerOnlyEditor"; //$NON-NLS-1$ + + /** + * One {@code gotoMarker} call: the marker range and whether the marker existed at call time. + */ + public record GotoCall(int charStart, int charEnd, boolean markerExisted) { + } + + private final List fCalls= new CopyOnWriteArrayList<>(); + + private final IGotoMarker fGotoMarker= marker -> fCalls.add(new GotoCall(marker.getAttribute(IMarker.CHAR_START, -1), + marker.getAttribute(IMarker.CHAR_END, -1), marker.exists())); + + public List getGotoCalls() { + return fCalls; + } + + @Override + public void init(IEditorSite site, IEditorInput input) { + setSite(site); + setInput(input); + } + + @Override + public void createPartControl(Composite parent) { + new Label(parent, SWT.NONE).setText(getEditorInput().getName()); + } + + @Override + public T getAdapter(Class adapter) { + if (adapter == IGotoMarker.class) { + return adapter.cast(fGotoMarker); + } + return super.getAdapter(adapter); + } + + @Override + public void setFocus() { + // nothing to focus + } + + @Override + public void doSave(IProgressMonitor monitor) { + // never dirty + } + + @Override + public void doSaveAs() { + // not allowed + } + + @Override + public boolean isDirty() { + return false; + } + + @Override + public boolean isSaveAsAllowed() { + return false; + } +} diff --git a/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/TextEditorWrapper.java b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/TextEditorWrapper.java new file mode 100644 index 00000000000..868aff8f95a --- /dev/null +++ b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/TextEditorWrapper.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Vector Informatik GmbH - initial API and implementation + *******************************************************************************/ +package org.eclipse.search.tests; + +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.part.MultiPageEditorPart; + +import org.eclipse.ui.texteditor.ITextEditor; + +import org.eclipse.ui.editors.text.TextEditor; + +/** + * Test editor that is not an {@link ITextEditor} itself, but wraps one and adapts to it. + */ +public class TextEditorWrapper extends MultiPageEditorPart { + + public static final String ID= "org.eclipse.search.tests.TextEditorWrapper"; //$NON-NLS-1$ + + private TextEditor fTextEditor; + + public ITextEditor getTextEditor() { + return fTextEditor; + } + + @Override + protected void createPages() { + fTextEditor= new TextEditor(); + try { + addPage(fTextEditor, getEditorInput()); + } catch (PartInitException e) { + throw new IllegalStateException(e); + } + } + + @Override + public T getAdapter(Class adapter) { + if (adapter == ITextEditor.class && fTextEditor != null) { + return adapter.cast(fTextEditor); + } + return super.getAdapter(adapter); + } + + @Override + public void doSave(IProgressMonitor monitor) { + fTextEditor.doSave(monitor); + } + + @Override + public void doSaveAs() { + // not allowed + } + + @Override + public boolean isSaveAsAllowed() { + return false; + } +} diff --git a/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AllFileSearchTests.java b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AllFileSearchTests.java index 6996a831ea2..531e0eb440c 100644 --- a/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AllFileSearchTests.java +++ b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AllFileSearchTests.java @@ -34,6 +34,7 @@ SortingTest.class, TextSearchResultTest.class, RestrictedFilesSearchTest.class, + EditorOpenerTest.class, }) public class AllFileSearchTests { } diff --git a/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/EditorOpenerTest.java b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/EditorOpenerTest.java new file mode 100644 index 00000000000..1470123fe42 --- /dev/null +++ b/tests/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/EditorOpenerTest.java @@ -0,0 +1,316 @@ +/******************************************************************************* + * Copyright (c) 2026 Vector Informatik GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Vector Informatik GmbH - initial API and implementation + *******************************************************************************/ +package org.eclipse.search.tests.filesearch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.eclipse.swt.widgets.Display; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.ILogListener; +import org.eclipse.core.runtime.ICoreRunnable; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.jobs.Job; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jface.text.ITextSelection; + +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; + +import org.eclipse.search.internal.ui.text.EditorOpener; +import org.eclipse.search.tests.GotoMarkerOnlyEditor; +import org.eclipse.search.tests.GotoMarkerOnlyEditor.GotoCall; +import org.eclipse.search.tests.ResourceHelper; +import org.eclipse.search.tests.SearchTestUtil; +import org.eclipse.search.tests.TextEditorWrapper; +import org.eclipse.search.ui.NewSearchUI; + +/** + * Tests that {@link EditorOpener} does not block the UI thread while another thread holds the + * workspace lock. + */ +public class EditorOpenerTest { + + private static final String PROJECT_NAME= "EditorOpenerTest"; //$NON-NLS-1$ + + private static final long MAX_UI_WAIT_MS= 3000; + + private static final long LOCK_RELEASE_MS= 10_000; + + private static final long JOB_TIMEOUT_MS= 20_000; + + private IWorkbenchPage fPage; + + private IProject fProject; + + private IFile fTrigger; + + private final List fLoggedSearchErrors= new CopyOnWriteArrayList<>(); + + private final ILogListener fLogListener= (status, _) -> { + if (status.getSeverity() == IStatus.ERROR && NewSearchUI.PLUGIN_ID.equals(status.getPlugin())) { + fLoggedSearchErrors.add(status); + } + }; + + @BeforeEach + public void setUp() throws Exception { + SearchTestUtil.ensureWelcomePageClosed(); + fPage= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + fProject= ResourceHelper.createProject(PROJECT_NAME); + fTrigger= createFile("trigger.txt"); //$NON-NLS-1$ + Platform.addLogListener(fLogListener); + } + + @AfterEach + public void tearDown() throws Exception { + Platform.removeLogListener(fLogListener); + fPage.closeAllEditors(false); + waitForMarkerJobs(); + ResourceHelper.deleteProject(PROJECT_NAME); + } + + @Test + public void openMatchDoesNotWaitForWorkspaceLock() throws Exception { + IFile file= createFile("match.gotomarker"); //$NON-NLS-1$ + EditorOpener opener= new EditorOpener(); + + IEditorPart editor; + try (WorkspaceLockHolder _= new WorkspaceLockHolder(fTrigger)) { + long start= System.nanoTime(); + editor= opener.openAndSelect(fPage, file, 0, 1, true); + assertUiThreadDidNotWait(start); + } + + GotoMarkerOnlyEditor gotoEditor= assertInstanceOf(GotoMarkerOnlyEditor.class, editor); + waitForMarkerJobs(); + assertEquals(List.of(new GotoCall(0, 1, true)), gotoEditor.getGotoCalls()); + assertNoSearchMarkerLeft(file); + } + + @Test + public void wrappedTextEditorSelectsWithoutMarker() throws Exception { + IFile file= createFile("match.wrappedtext"); //$NON-NLS-1$ + EditorOpener opener= new EditorOpener(); + + IEditorPart editor; + try (WorkspaceLockHolder _= new WorkspaceLockHolder(fTrigger)) { + long start= System.nanoTime(); + editor= opener.openAndSelect(fPage, file, 2, 3, true); + assertUiThreadDidNotWait(start); + assertEquals(0, Job.getJobManager().find(EditorOpener.MARKER_JOB_FAMILY).length, "no marker job expected"); //$NON-NLS-1$ + } + + TextEditorWrapper wrapper= assertInstanceOf(TextEditorWrapper.class, editor); + ITextSelection selection= (ITextSelection) wrapper.getTextEditor().getSelectionProvider().getSelection(); + assertEquals(2, selection.getOffset()); + assertEquals(3, selection.getLength()); + assertNoSearchMarkerLeft(file); + } + + @Test + public void onlyLatestClickMovesCaret() throws Exception { + IFile file= createFile("match.gotomarker"); //$NON-NLS-1$ + EditorOpener opener= new EditorOpener(); + + IEditorPart editor; + try (WorkspaceLockHolder _= new WorkspaceLockHolder(fTrigger)) { + long start= System.nanoTime(); + opener.openAndSelect(fPage, file, 0, 1, true); + editor= opener.openAndSelect(fPage, file, 5, 2, true); + assertUiThreadDidNotWait(start); + } + + GotoMarkerOnlyEditor gotoEditor= assertInstanceOf(GotoMarkerOnlyEditor.class, editor); + waitForMarkerJobs(); + assertEquals(List.of(new GotoCall(5, 7, true)), gotoEditor.getGotoCalls()); + assertNoSearchMarkerLeft(file); + } + + @Test + public void editorClosedBeforeMarkerIsReady() throws Exception { + IFile file= createFile("match.gotomarker"); //$NON-NLS-1$ + EditorOpener opener= new EditorOpener(); + + IEditorPart editor; + try (WorkspaceLockHolder _= new WorkspaceLockHolder(fTrigger)) { + long start= System.nanoTime(); + editor= opener.openAndSelect(fPage, file, 0, 1, true); + assertUiThreadDidNotWait(start); + assertTrue(fPage.closeEditor(editor, false)); + } + + GotoMarkerOnlyEditor gotoEditor= assertInstanceOf(GotoMarkerOnlyEditor.class, editor); + waitForMarkerJobs(); + assertEquals(List.of(), gotoEditor.getGotoCalls()); + assertNoSearchMarkerLeft(file); + assertEquals(List.of(), fLoggedSearchErrors); + } + + @Test + public void textEditorClickCancelsPendingMarker() throws Exception { + IFile markerFile= createFile("match.gotomarker"); //$NON-NLS-1$ + IFile textFile= createFile("match.wrappedtext"); //$NON-NLS-1$ + EditorOpener opener= new EditorOpener(); + + IEditorPart markerEditor; + IEditorPart textEditor; + try (WorkspaceLockHolder _= new WorkspaceLockHolder(fTrigger)) { + long start= System.nanoTime(); + markerEditor= opener.openAndSelect(fPage, markerFile, 0, 1, true); + textEditor= opener.openAndSelect(fPage, textFile, 2, 3, true); + assertUiThreadDidNotWait(start); + } + + waitForMarkerJobs(); + GotoMarkerOnlyEditor gotoEditor= assertInstanceOf(GotoMarkerOnlyEditor.class, markerEditor); + assertEquals(List.of(), gotoEditor.getGotoCalls()); + assertNoSearchMarkerLeft(markerFile); + TextEditorWrapper wrapper= assertInstanceOf(TextEditorWrapper.class, textEditor); + ITextSelection selection= (ITextSelection) wrapper.getTextEditor().getSelectionProvider().getSelection(); + assertEquals(2, selection.getOffset()); + assertEquals(3, selection.getLength()); + } + + private IFile createFile(String name) throws CoreException { + IFile file= fProject.getFile(name); + file.create(new ByteArrayInputStream("0123456789".getBytes(StandardCharsets.UTF_8)), true, null); //$NON-NLS-1$ + return file; + } + + private static void assertUiThreadDidNotWait(long startNanos) { + long ms= TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue(ms < MAX_UI_WAIT_MS, "UI thread waited " + ms + " ms for the workspace lock"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private static void assertNoSearchMarkerLeft(IFile file) throws CoreException { + assertEquals(0, file.findMarkers(NewSearchUI.SEARCH_MARKER, true, IResource.DEPTH_ZERO).length, + "search markers left on " + file); //$NON-NLS-1$ + } + + /** + * Processes UI events until no marker job of {@link EditorOpener} is scheduled or running and + * no UI runnable that schedules one is pending. + */ + private static void waitForMarkerJobs() throws InterruptedException { + long deadline= System.currentTimeMillis() + JOB_TIMEOUT_MS; + while (true) { + processUiEvents(); + if (Job.getJobManager().find(EditorOpener.MARKER_JOB_FAMILY).length == 0) { + // a finished create job has already posted its UI runnable, which may schedule the delete job + processUiEvents(); + if (Job.getJobManager().find(EditorOpener.MARKER_JOB_FAMILY).length == 0) { + return; + } + } + assertTrue(System.currentTimeMillis() < deadline, "timeout waiting for the marker jobs"); //$NON-NLS-1$ + Thread.sleep(10); + } + } + + private static void processUiEvents() { + Display display= Display.getCurrent(); + while (display.readAndDispatch()) { + // process all pending events + } + } + + /** + * Holds the workspace lock like a slow resource change listener does: a background job changes + * the trigger file, and a {@code POST_CHANGE} listener blocks while the workspace notifies + * about it, until the holder is closed or at most {@link #LOCK_RELEASE_MS} passed. A UI thread + * that waits for the lock fails the test instead of hanging it. + */ + private static final class WorkspaceLockHolder implements AutoCloseable { + private final CountDownLatch fHolding= new CountDownLatch(1); + + private final CountDownLatch fRelease= new CountDownLatch(1); + + private final AtomicBoolean fBlocked= new AtomicBoolean(); + + private final Timer fWatchdog= new Timer(true); + + private final IResourceChangeListener fListener; + + private final Job fJob; + + WorkspaceLockHolder(IFile trigger) throws InterruptedException { + fListener= event -> { + IResourceDelta delta= event.getDelta(); + if (delta != null && delta.findMember(trigger.getFullPath()) != null && fBlocked.compareAndSet(false, true)) { + fHolding.countDown(); + try { + fRelease.await(2 * LOCK_RELEASE_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }; + ResourcesPlugin.getWorkspace().addResourceChangeListener(fListener, IResourceChangeEvent.POST_CHANGE); + fJob= Job.create("touch trigger file", (ICoreRunnable) trigger::touch); //$NON-NLS-1$ + fJob.setSystem(true); + fJob.schedule(); + boolean holding= fHolding.await(5, TimeUnit.SECONDS); + if (!holding) { + fRelease.countDown(); + ResourcesPlugin.getWorkspace().removeResourceChangeListener(fListener); + } + assertTrue(holding, "workspace lock not acquired"); //$NON-NLS-1$ + fWatchdog.schedule(new TimerTask() { + @Override + public void run() { + fRelease.countDown(); + } + }, LOCK_RELEASE_MS); + } + + @Override + public void close() throws InterruptedException { + fRelease.countDown(); + fWatchdog.cancel(); + long deadline= System.currentTimeMillis() + JOB_TIMEOUT_MS; + while (fJob.getState() != Job.NONE && System.currentTimeMillis() < deadline) { + processUiEvents(); + Thread.sleep(10); + } + ResourcesPlugin.getWorkspace().removeResourceChangeListener(fListener); + } + } +} From 3c65f7da9b48ac740bfcf314a8c521de604c87bb Mon Sep 17 00:00:00 2001 From: Tobias Melcher Date: Wed, 11 Nov 2026 17:31:22 +0100 Subject: [PATCH 49/52] Keep valid code minings visible when a provider supplies an invalid position An invalid position can abort an annotation batch update before the remaining annotations are added and the model change event is fired. Filter invalid positions in InlinedAnnotationSupport, dispose rejected code minings, and retain only valid annotations for reuse. Keep the position check in AnnotationCodeMiningProvider so it does not return invalid minings. --- .../inlined/InlinedAnnotationSupport.java | 14 +++- .../AnnotationCodeMiningProvider.java | 10 ++- .../text/tests/codemining/CodeMiningTest.java | 50 +++++++++++- .../inlined/InlinedAnnotationSupportTest.java | 47 +++++++++++ .../AnnotationCodeMiningProviderTest.java | 80 +++++++++++++++++++ .../ui/editors/tests/EditorsTestSuite.java | 2 + 6 files changed, 200 insertions(+), 3 deletions(-) create mode 100644 tests/org.eclipse.ui.editors.tests/src/org/eclipse/jface/text/tests/codemining/AnnotationCodeMiningProviderTest.java diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java index 05b1a9790a0..746c9fd8085 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java @@ -16,6 +16,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -548,7 +549,18 @@ public void updateAnnotations(Set annotations) { ? new ArrayList<>(previousAnnotations) : Collections.emptyList(); // Loop for annotations to update + Set validAnnotations= new HashSet<>(); for (AbstractInlinedAnnotation ann : annotations) { + Position position= ann.getPosition(); + int documentLength= document.getLength(); + // One invalid position would abort replaceAnnotations and suppress the + // model change event, leaving the other code minings invisible as well. + if (position.isDeleted() || position.offset < 0 || position.length < 0 + || position.offset > documentLength || position.length > documentLength - position.offset) { + ann.markDeleted(true); + continue; + } + validAnnotations.add(ann); boolean known= annotationsToRemove.remove(ann); // An annotation a client removed from the annotation model behind our back is // still known here, but invisible, so add it again. @@ -585,7 +597,7 @@ public void updateAnnotations(Set annotations) { } } } - fInlinedAnnotations= annotations; + fInlinedAnnotations= validAnnotations; } } diff --git a/bundles/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/codemining/annotation/AnnotationCodeMiningProvider.java b/bundles/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/codemining/annotation/AnnotationCodeMiningProvider.java index 3316b689223..d17e61d5012 100644 --- a/bundles/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/codemining/annotation/AnnotationCodeMiningProvider.java +++ b/bundles/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/codemining/annotation/AnnotationCodeMiningProvider.java @@ -275,8 +275,16 @@ private List createCodeMinings(Stream annotation } try { + final IDocument document= getDocument(); final Consumer action= createAction(annotation); - return new AnnotationCodeMining(getAnnotationAccess(), annotation, lineNumber, getDocument(), this, action); + final AnnotationCodeMining mining= new AnnotationCodeMining(getAnnotationAccess(), annotation, lineNumber, document, this, action); + final Position position= mining.getPosition(); + if (position.offset < 0 || position.length < 0 || position.offset > document.getLength() + || position.length > document.getLength() - position.offset) { + mining.dispose(); + return null; + } + return mining; } catch (BadLocationException e) { return null; } diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java index d8f0d95b0f6..b78a1975be5 100644 --- a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/codemining/CodeMiningTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019, 2025 Red Hat Inc. and others. + * Copyright (c) 2019, 2026 Red Hat Inc. and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -797,6 +797,54 @@ protected boolean condition() { }.waitForCondition(fViewer.getTextWidget().getDisplay(), 10_000), "Code mining is not visible at end of document"); } + @Test + public void testInvalidMiningDoesNotBlockOtherMinings() { + fViewer.getDocument().set("first\nsecond\n"); + AtomicInteger disposed= new AtomicInteger(); + ICodeMiningProvider mixedProvider= new AbstractCodeMiningProvider() { + @Override + public CompletableFuture> provideCodeMinings(ITextViewer viewer, IProgressMonitor monitor) { + try { + LineHeaderCodeMining invalid= new LineHeaderCodeMining(new Position(viewer.getDocument().getLength(), 1), this, null) { + @Override + public void dispose() { + super.dispose(); + disposed.incrementAndGet(); + } + }; + invalid.setLabel("invalid"); + LineHeaderCodeMining valid= new LineHeaderCodeMining(0, viewer.getDocument(), this) {}; + valid.setLabel("valid from mixed provider"); + return CompletableFuture.completedFuture(List.of(invalid, valid)); + } catch (BadLocationException e) { + throw new AssertionError(e); + } + } + }; + ICodeMiningProvider otherProvider= new AbstractCodeMiningProvider() { + @Override + public CompletableFuture> provideCodeMinings(ITextViewer viewer, IProgressMonitor monitor) { + try { + LineHeaderCodeMining valid= new LineHeaderCodeMining(1, viewer.getDocument(), this) {}; + valid.setLabel("valid from other provider"); + return CompletableFuture.completedFuture(List.of(valid)); + } catch (BadLocationException e) { + throw new AssertionError(e); + } + } + }; + fViewer.setCodeMiningProviders(new ICodeMiningProvider[] { mixedProvider, otherProvider }); + fViewer.updateCodeMinings(); + StyledText widget= fViewer.getTextWidget(); + Assertions.assertTrue(new DisplayHelper() { + @Override + protected boolean condition() { + return widget.getLineVerticalIndent(0) > 0 && widget.getLineVerticalIndent(1) > 0; + } + }.waitForCondition(widget.getDisplay(), 10_000), "An invalid mining prevented valid minings from rendering"); + Assertions.assertTrue(disposed.get() > 0, "Invalid mining was not disposed"); + } + @Test public void testCodeMiningEndOfLine() { fViewer.getDocument().set("a\n"); diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/source/inlined/InlinedAnnotationSupportTest.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/source/inlined/InlinedAnnotationSupportTest.java index a7e71add797..3f1acc10a78 100644 --- a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/source/inlined/InlinedAnnotationSupportTest.java +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/source/inlined/InlinedAnnotationSupportTest.java @@ -10,10 +10,16 @@ *******************************************************************************/ package org.eclipse.jface.text.tests.source.inlined; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -26,6 +32,7 @@ import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.source.inlined.AbstractInlinedAnnotation; import org.eclipse.jface.text.source.inlined.InlinedAnnotationSupport; import org.eclipse.jface.text.source.inlined.LineContentAnnotation; import org.eclipse.jface.text.tests.source.inlined.LineContentBoundsDrawingTest.AccessAllAnnoations; @@ -73,6 +80,46 @@ public void tearDown() { fShell.dispose(); } + @Test + public void testInvalidPositionsDoNotBlockBatchUpdate() { + int documentLength= fViewer.getDocument().getLength(); + List invalidPositions= List.of(new Position(documentLength, 1), + new Position(documentLength + 1, 0), new Position(1, Integer.MAX_VALUE)); + AtomicInteger changes= new AtomicInteger(); + fModel.addAnnotationModelListener(_ -> changes.incrementAndGet()); + for (Position position : invalidPositions) { + LineContentAnnotation valid= new LineContentAnnotation(new Position(0, 1), fViewer); + LineContentAnnotation invalid= new LineContentAnnotation(position, fViewer); + changes.set(0); + fSupport.updateAnnotations(new LinkedHashSet<>(List.of(invalid, valid))); + assertEquals(valid.getPosition(), fModel.getPosition(valid)); + assertNull(fModel.getPosition(invalid)); + assertTrue(invalid.isMarkedDeleted()); + assertNull(fSupport.findExistingAnnotation(position)); + assertTrue(changes.get() > 0, "valid annotations did not notify the painter"); + fSupport.updateAnnotations(Collections.emptySet()); + } + } + + @Test + public void testInvalidExistingAnnotationIsRemoved() { + LineContentAnnotation annotation= new LineContentAnnotation(new Position(0, 1), fViewer); + fSupport.updateAnnotations(Collections.singleton(annotation)); + annotation.getPosition().length= Integer.MAX_VALUE; + fSupport.updateAnnotations(Collections.singleton(annotation)); + assertNull(fModel.getPosition(annotation)); + assertTrue(annotation.isMarkedDeleted()); + assertFalse(fModel.getAnnotationIterator().hasNext()); + } + + @Test + public void testZeroLengthPositionAtDocumentEndIsRetained() { + AbstractInlinedAnnotation annotation= new LineContentAnnotation(new Position(fViewer.getDocument().getLength(), 0), fViewer); + fSupport.updateAnnotations(Set.of(annotation)); + assertEquals(annotation.getPosition(), fModel.getPosition(annotation)); + assertFalse(annotation.isMarkedDeleted()); + } + @Test public void testUpdateRacingUninstallAddsNoAnnotations() { fModel.onLock= fSupport::uninstall; diff --git a/tests/org.eclipse.ui.editors.tests/src/org/eclipse/jface/text/tests/codemining/AnnotationCodeMiningProviderTest.java b/tests/org.eclipse.ui.editors.tests/src/org/eclipse/jface/text/tests/codemining/AnnotationCodeMiningProviderTest.java new file mode 100644 index 00000000000..ab08952b8cd --- /dev/null +++ b/tests/org.eclipse.ui.editors.tests/src/org/eclipse/jface/text/tests/codemining/AnnotationCodeMiningProviderTest.java @@ -0,0 +1,80 @@ +package org.eclipse.jface.text.tests.codemining; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.junit.jupiter.api.Test; + +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.codemining.AbstractCodeMining; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.AnnotationModel; +import org.eclipse.jface.text.source.IAnnotationAccessExtension; +import org.eclipse.jface.text.source.SourceViewer; + +import org.eclipse.ui.internal.editors.text.codemining.annotation.AnnotationCodeMiningProvider; + +public class AnnotationCodeMiningProviderTest { + + @Test + public void skipsWhitespaceOnlyFinalLine() throws Exception { + assertNull(createMining(" \t ", 0)); + } + + @Test + public void skipsEmptyDocument() throws Exception { + assertNull(createMining("", 0)); + } + + @Test + public void skipsTrailingEmptyLine() throws Exception { + assertNull(createMining("text\n", 5)); + } + + @Test + public void retainsMiningOnNonemptyLine() throws Exception { + AbstractCodeMining mining= createMining(" text", 2); + assertNotNull(mining); + try { + assertEquals(2, mining.getPosition().offset); + assertEquals(1, mining.getPosition().length); + assertEquals("diagnostic", mining.getLabel()); + } finally { + mining.dispose(); + } + } + + private AbstractCodeMining createMining(String text, int annotationOffset) throws Exception { + Document document= new Document(text); + AnnotationModel model= new AnnotationModel(); + model.connect(document); + AnnotationCodeMiningProvider provider= new AnnotationCodeMiningProvider(); + try { + Annotation annotation= new Annotation("test", false, "diagnostic"); + model.addAnnotation(annotation, new Position(annotationOffset, 0)); + SourceViewer viewer= mock(SourceViewer.class); + when(viewer.getDocument()).thenReturn(document); + when(viewer.getVisualAnnotationModel()).thenReturn(model); + setField(provider, "viewer", viewer); + setField(provider, "annotationAccess", mock(IAnnotationAccessExtension.class)); + Method method= AnnotationCodeMiningProvider.class.getDeclaredMethod("createCodeMining", Annotation.class); + method.setAccessible(true); + return (AbstractCodeMining) method.invoke(provider, annotation); + } finally { + model.disconnect(document); + } + } + + private void setField(AnnotationCodeMiningProvider provider, String name, Object value) throws Exception { + Field field= AnnotationCodeMiningProvider.class.getDeclaredField(name); + field.setAccessible(true); + field.set(provider, value); + } +} diff --git a/tests/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/EditorsTestSuite.java b/tests/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/EditorsTestSuite.java index e8353b3e803..76f2ffaade4 100644 --- a/tests/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/EditorsTestSuite.java +++ b/tests/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/EditorsTestSuite.java @@ -18,6 +18,7 @@ import org.junit.platform.suite.api.Suite; import org.junit.platform.suite.api.SelectClasses; +import org.eclipse.jface.text.tests.codemining.AnnotationCodeMiningProviderTest; import org.eclipse.jface.text.tests.codemining.CodeMiningTest; import org.eclipse.ui.internal.texteditor.stickyscroll.DefaultStickyLinesProviderTest; @@ -56,6 +57,7 @@ StickyLineTest.class, StickyLinesProviderRegistryTest.class, + AnnotationCodeMiningProviderTest.class, CodeMiningTest.class, }) public class EditorsTestSuite { From 860c3fb8e05d879ae5a2eb18ed9ead6ea1809cdc Mon Sep 17 00:00:00 2001 From: LukasHackl2 Date: Sun, 8 Nov 2026 11:12:13 +0100 Subject: [PATCH 50/52] Provide reusable breadcrumb viewer implementations in JFace #4495 Move the reusable breadcrumb implementations to org.eclipse.jface.viewers, providing both element-based and TreePath-based variants. Keep client-specific behavior configurable through extension hooks for drop-down handling, element openability and dialog settings. --- .../src/org/eclipse/jface/messages.properties | 5 + .../eclipse/jface/viewers/BreadcrumbItem.java | 315 +++++++ .../jface/viewers/BreadcrumbItemDetails.java | 485 ++++++++++ .../jface/viewers/BreadcrumbItemDropDown.java | 739 ++++++++++++++++ .../jface/viewers/BreadcrumbViewer.java | 825 +++++++++++++++++ .../jface/viewers/BreadcrumbViewerRow.java | 194 ++++ .../TreePathBreadcrumbDropDownSite.java | 41 + .../jface/viewers/TreePathBreadcrumbItem.java | 237 +++++ .../TreePathBreadcrumbItemDetails.java | 393 +++++++++ .../TreePathBreadcrumbItemDropDown.java | 583 ++++++++++++ .../viewers/TreePathBreadcrumbViewer.java | 832 ++++++++++++++++++ 11 files changed, 4649 insertions(+) create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItem.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDetails.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDropDown.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewer.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewerRow.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbDropDownSite.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItem.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDetails.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDropDown.java create mode 100644 bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbViewer.java diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/messages.properties b/bundles/org.eclipse.jface/src/org/eclipse/jface/messages.properties index 2dbb4c71ffb..4c8b01ed4a2 100644 --- a/bundles/org.eclipse.jface/src/org/eclipse/jface/messages.properties +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/messages.properties @@ -198,6 +198,11 @@ F20 = F20 SafeRunnable.errorMessage = An error has occurred. See error log for more details. ColorSelector.Name=Color Selector +############################################################# +# org.eclipse.jface.viewers +############################################################# +BreadcrumbItemDropDown_showDropDownMenu_action_toolTip=Show Children + ############################################################# # org.eclipse.jface.viewers.deferred ############################################################# diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItem.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItem.java new file mode 100644 index 00000000000..320274b9518 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItem.java @@ -0,0 +1,315 @@ +/******************************************************************************* + * Copyright (c) 2008, 2011 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Fabio Zadrozny - Bug 465666 + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Item; +import org.eclipse.swt.widgets.Shell; + +/** + * An item in a breadcrumb viewer. + *

+ * The item shows a label and an image. It also has the ability to expand, that + * is to open a drop down menu. + *

+ *

+ * The drop down allows to select any child of the items input element. The item + * shows the label and icon of its data element, if any. + *

+ * + * @since 3.41 + */ +class BreadcrumbItem extends Item { + + private final BreadcrumbViewer fParent; + private Composite fContainer; + + private BreadcrumbItemDetails fDetailsBlock; + private BreadcrumbItemDropDown fExpandBlock; + private boolean fIsLast; + + /** + * A new breadcrumb item which is shown inside the given viewer. + * + * @param viewer the items viewer + * @param parent the container containing the item + */ + public BreadcrumbItem(BreadcrumbViewer viewer, Composite parent) { + super(parent, SWT.NONE); + + fParent = viewer; + + fContainer = new Composite(parent, SWT.NONE); + fContainer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + GridLayout layout = new GridLayout(2, false); + layout.marginBottom = 1; + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.horizontalSpacing = 0; + fContainer.setLayout(layout); + + fDetailsBlock = new BreadcrumbItemDetails(this, fContainer); + + fExpandBlock = new BreadcrumbItemDropDown(this, fContainer); + + fContainer.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Returns this items viewer. + * + * @return the viewer showing this item + */ + public BreadcrumbViewer getViewer() { + return fParent; + } + + /* + * @see org.eclipse.swt.widgets.Widget#dispose() + */ + @Override + public void dispose() { + Shell shell = fExpandBlock.getDropDownShell(); + if (shell != null && !shell.isDisposed()) { + shell.dispose(); + } + fContainer.dispose(); + super.dispose(); + } + + /** + * Should this item show a text label. + * + * @param enabled true if it should + */ + void setShowText(boolean enabled) { + fDetailsBlock.setTextVisible(enabled); + } + + /** + * Does this item show a text label? + * + * @return true if it does. + */ + boolean isShowText() { + return fDetailsBlock.isTextVisible(); + } + + /** + * Returns the width of this item. + * + * @return the width of this item + */ + int getWidth() { + return fDetailsBlock.getWidth() + fExpandBlock.getWidth() + 2; + } + + /** + * Sets whether this item has to be marked as selected or not. + * + * @param selected true if marked as selected + */ + void setSelected(boolean selected) { + fDetailsBlock.setSelected(selected); + } + + /** + * Sets whether this item has the keyboard focus. + * + * @param state true if it has focus, false otherwise + */ + void setFocus(boolean state) { + fDetailsBlock.setFocus(state); + } + + /** + * Returns whether this item has the keyboard focus. + * + * @return true if this item has the keyboard focus + */ + boolean hasFocus() { + return fDetailsBlock.hasFocus(); + } + + /** + * Redraws this item using the viewer's current providers. + */ + void refresh() { + IBaseLabelProvider labelProvider = fParent.getLabelProvider(); + + if (labelProvider instanceof CellLabelProvider cellLabelProvider) { + BreadcrumbViewerRow row = new BreadcrumbViewerRow(fParent, this); + ViewerCell cell = row.getCell(0); + cellLabelProvider.update(cell); + } else { + ILabelProvider simpleLabelProvider = (ILabelProvider) labelProvider; + String text = simpleLabelProvider.getText(getData()); + Image image = simpleLabelProvider.getImage(getData()); + + setText(text); + setImage(image); + } + + refreshToolTip(); + refreshArrow(); + } + + void refreshToolTip() { + ILabelProvider toolTipLabelProvider = fParent.getToolTipLabelProvider(); + if (toolTipLabelProvider != null) { + fDetailsBlock.setToolTip(toolTipLabelProvider.getText(getData())); + } else { + fDetailsBlock.setToolTip(getText()); + } + } + + /** + * Refresh the arrows visibility. + */ + void refreshArrow() { + ITreeContentProvider contentProvider = (ITreeContentProvider) fParent.getContentProvider(); + fExpandBlock.setEnabled(contentProvider.hasChildren(getData())); + } + + /** + * Set whether this is the last item in the breadcrumb item chain or not. + * + * @param isLast true if this is the last item, false + * otherwise + */ + void setIsLastItem(boolean isLast) { + fIsLast = isLast; + + GridData data = (GridData) fContainer.getLayoutData(); + data.grabExcessHorizontalSpace = isLast; + } + + /** + * Sets whether or not the this item should show the details (name and label). + * + * @param visible true if the item shows details + */ + void setDetailsVisible(boolean visible) { + fDetailsBlock.setVisible(visible); + } + + /** + * Expand this item, shows the drop down menu. + */ + void openDropDownMenu() { + fExpandBlock.showMenu(); + } + + /** + * @return true if this item is expanded + */ + boolean isMenuShown() { + return fExpandBlock.isMenuShown(); + } + + /** + * Returns the drop down shell. + * + * @return the shell of the drop down if shown, null otherwise + */ + Shell getDropDownShell() { + return fExpandBlock.getDropDownShell(); + } + + /** + * Returns the drop down selection provider of this item. + * + * @return the selection provider of the drop down or null + */ + ISelectionProvider getDropDownSelectionProvider() { + return fExpandBlock.getDropDownSelectionProvider(); + } + + /** + * Returns the bounds of this item. + * + * @return the bounds of this item + */ + public Rectangle getBounds() { + return fContainer.getBounds(); + } + + /** + * Set the tool tip of the item to the given text. + * + * @param text the tool tip for the item + */ + public void setToolTip(String text) { + fDetailsBlock.setToolTip(text); + } + + Color getForeground() { + return fDetailsBlock.getForeground(); + } + + void setForeground(Color color) { + fDetailsBlock.setForeground(color); + } + + Color getBackground() { + return fDetailsBlock.getBackground(); + } + + void setBackground(Color color) { + fDetailsBlock.setBackground(color); + } + + Font getFont() { + return fDetailsBlock.getFont(); + } + + void setFont(Font font) { + fDetailsBlock.setFont(font); + } + + /* + * @see org.eclipse.swt.widgets.Item#setText(java.lang.String) + */ + @Override + public void setText(String string) { + if (string == null) { + string = ""; //$NON-NLS-1$ + } + + super.setText(string); + fDetailsBlock.setText(string); + + // more or less space might be required for the label + if (fIsLast) + fContainer.layout(true, true); + } + + /* + * @see org.eclipse.swt.widgets.Item#setImage(org.eclipse.swt.graphics.Image) + */ + @Override + public void setImage(Image image) { + super.setImage(image); + fDetailsBlock.setImage(image); + } + +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDetails.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDetails.java new file mode 100644 index 00000000000..6ab8496a992 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDetails.java @@ -0,0 +1,485 @@ +/******************************************************************************* + * Copyright (c) 2008, 2011 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Fabio Zadrozny - Bug 465666 + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * The label and icon part of the breadcrumb item. + * + * @since 3.41 + */ +class BreadcrumbItemDetails { + + private final Label fElementImage; + private final Label fElementText; + private final Composite fDetailComposite; + private final BreadcrumbItem fParent; + private final Composite fTextComposite; + private final Composite fImageComposite; + + private boolean fTextVisible; + private boolean fSelected; + private boolean fHasFocus; + + private Color fForeground; + private Color fDefaultForeground; + private Font fFont; + private Font fDefaultFont; + private Color fBackground; + private Color fDefaultDetailBackground; + private Color fDefaultTextBackground; + private Color fDefaultImageBackground; + private Color fDefaultElementTextBackground; + private Color fDefaultElementImageBackground; + + public BreadcrumbItemDetails(BreadcrumbItem parent, Composite parentContainer) { + fParent = parent; + fTextVisible = true; + + fDetailComposite = new Composite(parentContainer, SWT.NONE); + fDetailComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + GridLayout layout = new GridLayout(2, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.horizontalSpacing = 0; + fDetailComposite.setLayout(layout); + addElementListener(fDetailComposite); + + fImageComposite = new Composite(fDetailComposite, SWT.NONE); + fImageComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + layout = new GridLayout(1, false); + layout.marginHeight = 1; + layout.marginWidth = 2; + fImageComposite.setLayout(layout); + fImageComposite.addPaintListener(e -> { + if (fHasFocus && !isTextVisible()) { + e.gc.drawFocus(e.x, e.y, e.width, e.height); + } + }); + installFocusComposite(fImageComposite); + addElementListener(fImageComposite); + + fElementImage = new Label(fImageComposite, SWT.NONE); + GridData layoutData = new GridData(SWT.BEGINNING, SWT.CENTER, false, false); + fElementImage.setLayoutData(layoutData); + addElementListener(fElementImage); + + fTextComposite = new Composite(fDetailComposite, SWT.NONE); + fTextComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + layout = new GridLayout(1, false); + layout.marginHeight = 2; + layout.marginWidth = 2; + fTextComposite.setLayout(layout); + addElementListener(fTextComposite); + fTextComposite.addPaintListener(e -> { + if (fHasFocus && isTextVisible()) { + e.gc.drawFocus(e.x, e.y, e.width, e.height); + } + }); + installFocusComposite(fTextComposite); + + fElementText = new Label(fTextComposite, SWT.NONE); + layoutData = new GridData(SWT.BEGINNING, SWT.CENTER, false, false); + fElementText.setLayoutData(layoutData); + addElementListener(fElementText); + + fTextComposite.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result = fElementText.getText(); + } + }); + fImageComposite.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result = fElementText.getText(); + } + }); + + fDetailComposite.setTabList(new Control[] { fTextComposite }); + + fDetailComposite.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemDetailComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + fTextComposite.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemDetailTextComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + fImageComposite.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemDetailImageComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + fElementImage.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemDetailImageLabel"); //$NON-NLS-1$ //$NON-NLS-2$ + fElementText.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemDetailTextLabel"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Returns whether this element has the keyboard focus. + * + * @return true if this element has the keyboard focus. + */ + public boolean hasFocus() { + return fHasFocus; + } + + /** + * Sets the tool tip to the given text. + * + * @param text the tool tip + */ + public void setToolTip(String text) { + if (isTextVisible()) { + fElementText.getParent().setToolTipText(text); + fElementText.setToolTipText(text); + + fElementImage.setToolTipText(text); + } else { + fElementText.getParent().setToolTipText(null); + fElementText.setToolTipText(null); + + fElementImage.setToolTipText(text); + } + } + + /** + * Sets the image to the given image. + * + * @param image the image to use + */ + public void setImage(Image image) { + if (image != fElementImage.getImage()) { + fElementImage.setImage(image); + } + } + + /** + * Sets the text to the given text. + * + * @param text the text to use + */ + public void setText(String text) { + if (text == null) { + text = ""; //$NON-NLS-1$ + } + if (!text.equals(fElementText.getText())) { + fElementText.setText(text); + } + } + + public Color getForeground() { + return fForeground; + } + + public void setForeground(Color color) { + if (fForeground == null && color == null) { + return; + } + + if (fForeground == null) { + fDefaultForeground = fElementText.getForeground(); + } + + fForeground = color; + fElementText.setForeground(color != null ? color : fDefaultForeground); + } + + public Color getBackground() { + return fBackground; + } + + public void setBackground(Color color) { + if (fBackground == null && color == null) { + return; + } + + if (fBackground == null) { + // Preserve the themed defaults so they can be restored when the provider + // returns null. + fDefaultDetailBackground = fDetailComposite.getBackground(); + fDefaultTextBackground = fTextComposite.getBackground(); + fDefaultImageBackground = fImageComposite.getBackground(); + fDefaultElementTextBackground = fElementText.getBackground(); + fDefaultElementImageBackground = fElementImage.getBackground(); + } + + fBackground = color; + + fDetailComposite.setBackground(color != null ? color : fDefaultDetailBackground); + fTextComposite.setBackground(color != null ? color : fDefaultTextBackground); + fImageComposite.setBackground(color != null ? color : fDefaultImageBackground); + fElementText.setBackground(color != null ? color : fDefaultElementTextBackground); + fElementImage.setBackground(color != null ? color : fDefaultElementImageBackground); + } + + public Font getFont() { + return fFont; + } + + public void setFont(Font font) { + if (fFont == null && font == null) { + return; + } + + if (fFont == null) { + fDefaultFont = fElementText.getFont(); + } + + fFont = font; + fElementText.setFont(font != null ? font : fDefaultFont); + } + + /** + * Returns the width of this element. + * + * @return current width of this element + */ + public int getWidth() { + int result = 2; + + if (fElementImage.getImage() != null) + result += fElementImage.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + + if (fTextVisible && fElementText.getText().length() > 0) + result += fElementText.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + + return result; + } + + public void setTextVisible(boolean enabled) { + if (fTextVisible == enabled) + return; + + fTextVisible = enabled; + + GridData data = (GridData) fTextComposite.getLayoutData(); + data.exclude = !enabled; + fTextComposite.setVisible(enabled); + + if (fTextVisible) { + fDetailComposite.setTabList(new Control[] { fTextComposite }); + } else { + fDetailComposite.setTabList(new Control[] { fImageComposite }); + } + + if (fHasFocus) { + if (isTextVisible()) { + fTextComposite.setFocus(); + } else { + fImageComposite.setFocus(); + } + } + } + + /** + * Tells whether this item shows a text or only an image. + * + * @return true if it shows a text and an image, false if it only + * shows the image + */ + public boolean isTextVisible() { + return fTextVisible; + } + + /** + * Sets whether details should be shown. + * + * @param visible true if details should be shown + */ + public void setVisible(boolean visible) { + fDetailComposite.setVisible(visible); + + GridData data = (GridData) fDetailComposite.getLayoutData(); + data.exclude = !visible; + } + + public void setSelected(boolean selected) { + if (selected == fSelected) + return; + + fSelected = selected; + if (!fSelected) + fHasFocus = false; + + } + + public void setFocus(boolean enabled) { + if (enabled == fHasFocus) + return; + + fHasFocus = enabled; + if (fHasFocus) { + if (isTextVisible()) { + fTextComposite.setFocus(); + } else { + fImageComposite.setFocus(); + } + } + } + + /** + * Install focus and key listeners to the given composite. + * + * @param composite the composite which may get focus + */ + private void installFocusComposite(Composite composite) { + composite.addTraverseListener(e -> { + if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { + int index = fParent.getViewer().getIndexOfItem(fParent); + if (e.detail == SWT.TRAVERSE_TAB_NEXT) { + index++; + } else { + index--; + } + + if (index > 0 && index < fParent.getViewer().getItemCount()) { + fParent.getViewer().selectItem(fParent.getViewer().getItem(index)); + } + + e.doit = true; + } + }); + composite.addKeyListener(new KeyListener() { + @Override + public void keyPressed(KeyEvent e) { + BreadcrumbViewer viewer = fParent.getViewer(); + + switch (e.keyCode) { + case SWT.ARROW_LEFT: + if (fSelected) { + viewer.doTraverse(false); + e.doit = false; + } else { + viewer.selectItem(fParent); + } + break; + case SWT.ARROW_RIGHT: + if (fSelected) { + viewer.doTraverse(true); + e.doit = false; + } else { + viewer.selectItem(fParent); + } + break; + case SWT.ARROW_DOWN: + case SWT.KEYPAD_ADD: + if (!fSelected) { + viewer.selectItem(fParent); + } + openDropDown(); + e.doit = false; + break; + case SWT.CR: + if (!fSelected) { + viewer.selectItem(fParent); + } + viewer.fireOpen(); + break; + default: + if (e.character == ' ') { + if (!fSelected) { + viewer.selectItem(fParent); + } + openDropDown(); + e.doit = false; + } + break; + } + } + + private void openDropDown() { + BreadcrumbViewer viewer = fParent.getViewer(); + + int index = viewer.getIndexOfItem(fParent); + BreadcrumbItem parent = fParent.getViewer().getItem(index - 1); + + Shell shell = parent.getDropDownShell(); + if (shell == null) { + parent.openDropDownMenu(); + shell = parent.getDropDownShell(); + } + shell.setFocus(); + } + + @Override + public void keyReleased(KeyEvent e) { + } + }); + + composite.addFocusListener(new FocusListener() { + @Override + public void focusGained(FocusEvent e) { + if (!fHasFocus) { + fHasFocus = true; + } + } + + @Override + public void focusLost(FocusEvent e) { + if (fHasFocus) { + fHasFocus = false; + } + } + }); + } + + /** + * Add mouse listeners to the given control. + * + * @param control the control to which may be clicked + */ + private void addElementListener(Control control) { + control.addMouseListener(new MouseListener() { + @Override + public void mouseDoubleClick(MouseEvent e) { + } + + @Override + public void mouseDown(MouseEvent e) { + BreadcrumbViewer viewer = fParent.getViewer(); + + int parentIndex = viewer.getIndexOfItem(fParent) - 1; + Shell shell = null; + if (parentIndex >= 0) {// sanity check, must always hold + BreadcrumbItem dropDownItem = viewer.getItem(parentIndex); + shell = dropDownItem.getDropDownShell(); + } + + viewer.selectItem(fParent); + if (shell == null && e.button == 1 && e.stateMask == 0) { + fParent.getViewer().fireDoubleClick(); + } + } + + @Override + public void mouseUp(MouseEvent e) { + } + }); + control.addMenuDetectListener(e -> { + BreadcrumbViewer viewer = fParent.getViewer(); + viewer.selectItem(fParent); + fParent.getViewer().fireMenuDetect(e); + }); + } +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDropDown.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDropDown.java new file mode 100644 index 00000000000..a81edbb237b --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbItemDropDown.java @@ -0,0 +1,739 @@ +/******************************************************************************* + * Copyright (c) 2008, 2020 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Fabio Zadrozny - Bug 465666 + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.ToolBarManager; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.resource.CompositeImageDescriptor; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.util.OpenStrategy; +import org.eclipse.jface.util.Util; +import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.ControlListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.MouseMoveListener; +import org.eclipse.swt.events.ShellEvent; +import org.eclipse.swt.events.ShellListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageDataProvider; +import org.eclipse.swt.graphics.ImageGcDrawer; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Item; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.swt.widgets.Widget; + +/** + * The part of the breadcrumb item with the drop down menu. + * + * @since 3.41 + */ +class BreadcrumbItemDropDown { + private static final boolean IS_MAC_WORKAROUND = "carbon".equals(SWT.getPlatform()); //$NON-NLS-1$ + + /** + * An arrow image descriptor. The images color is related to the list fore- and + * background color. This makes the arrow visible even in high contrast mode. If + * ltr is true the arrow points to the right, otherwise it points + * to the left. + */ + private final class AccessibleArrowImage extends CompositeImageDescriptor { + + private final static int ARROW_SIZE = 5; + + private final boolean fLTR; + + public AccessibleArrowImage(boolean ltr) { + fLTR = ltr; + } + + @Override + protected void drawCompositeImage(int width, int height) { + Display display = fParentComposite.getDisplay(); + + ImageDataProvider imageProvider = zoom -> { + ImageGcDrawer drawer = new ImageGcDrawer() { + @Override + public void drawOn(GC gc, int iWidth, int iHeight) { + gc.setAntialias(SWT.ON); + Color triangleColor = createColor(SWT.COLOR_LIST_FOREGROUND, SWT.COLOR_LIST_BACKGROUND, 20, + display); + gc.setBackground(triangleColor); + gc.fillPolygon(new int[] { 0, 0, ARROW_SIZE, ARROW_SIZE, 0, ARROW_SIZE * 2 }); + triangleColor.dispose(); + } + + @Override + public int getGcStyle() { + return fLTR ? SWT.LEFT_TO_RIGHT : SWT.RIGHT_TO_LEFT; + } + }; + Image image = new Image(display, drawer, ARROW_SIZE, ARROW_SIZE * 2); + + ImageData imageData = image.getImageData(zoom); + image.dispose(); + int zoomedArrowSize = ARROW_SIZE * zoom / 100; + for (int y1 = 0; y1 < zoomedArrowSize; y1++) { + // set opaque pixels for top half of the breadcrumb arrow + for (int x1 = 0; x1 <= y1; x1++) { + imageData.setAlpha(fLTR ? x1 : zoomedArrowSize - x1 - 1, y1, 255); + } + // set transparent pixels for top half of the breadcrumbe arrow + for (int x1 = y1 + 1; x1 < zoomedArrowSize; x1++) { + imageData.setAlpha(fLTR ? x1 : zoomedArrowSize - x1 - 1, y1, 0); + } + } + for (int y2 = 0; y2 < zoomedArrowSize; y2++) { + // set opaque pixels for bottom half of the breadcrumb arrow + for (int x2 = 0; x2 <= y2; x2++) { + imageData.setAlpha(fLTR ? x2 : zoomedArrowSize - x2 - 1, zoomedArrowSize * 2 - y2 - 1, 255); + } + // set transparent pixels for bottom half of the breadcrumbe arrow + for (int x2 = y2 + 1; x2 < zoomedArrowSize; x2++) { + imageData.setAlpha(fLTR ? x2 : zoomedArrowSize - x2 - 1, zoomedArrowSize * 2 - y2 - 1, 0); + } + } + return imageData; + }; + drawImage(imageProvider, (width / 2) - (ARROW_SIZE / 2), (height / 2) - ARROW_SIZE); + } + + @Override + protected Point getSize() { + return new Point(10, 16); + } + + private Color createColor(int color1, int color2, int ratio, Display display) { + RGB rgb1 = display.getSystemColor(color1).getRGB(); + RGB rgb2 = display.getSystemColor(color2).getRGB(); + + RGB blend = blend(rgb2, rgb1, ratio); + + return new Color(blend); + } + + private static RGB blend(RGB rgb1, RGB rgb2, int ratio) { + int r = (rgb1.red * ratio + rgb2.red * (100 - ratio)) / 100; + int g = (rgb1.green * ratio + rgb2.green * (100 - ratio)) / 100; + int b = (rgb1.blue * ratio + rgb2.blue * (100 - ratio)) / 100; + + return new RGB(r, g, b); + } + } + + private static final int DROP_DOWN_MIN_WIDTH = 250; + private static final int DROP_DOWN_MAX_WIDTH = 500; + + private static final int DROP_DOWN_DEFAULT_MIN_HEIGHT = 200; + private static final int DROP_DOWN_DEFAULT_MAX_HEIGHT = 300; + + private static final String DIALOG_SETTINGS = "BreadcrumbItemDropDown"; //$NON-NLS-1$ + private static final String DIALOG_HEIGHT = "height"; //$NON-NLS-1$ + + private final BreadcrumbItem fParent; + private final Composite fParentComposite; + private final ToolBar fToolBar; + + private boolean fMenuIsShown; + private boolean fEnabled; + private TreeViewer fDropDownViewer; + private Shell fShell; + private boolean isResizingProgrammatically; + + public BreadcrumbItemDropDown(BreadcrumbItem parent, Composite composite) { + fParent = parent; + fParentComposite = composite; + fMenuIsShown = false; + fEnabled = true; + + String showChildrenText = JFaceResources.getString("BreadcrumbItemDropDown_showDropDownMenu_action_toolTip"); //$NON-NLS-1$ + + fToolBar = new ToolBar(composite, SWT.FLAT); + fToolBar.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false)); + fToolBar.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent event) { + event.result = showChildrenText; + } + }); + ToolBarManager manager = new ToolBarManager(fToolBar); + + final Action showDropDownMenuAction = new Action(null, SWT.NONE) { + @Override + public void run() { + Shell shell = fParent.getDropDownShell(); + if (shell != null) + return; + + shell = fParent.getViewer().getDropDownShell(); + if (shell != null) + shell.close(); + + showMenu(); + + fShell.setFocus(); + } + }; + + showDropDownMenuAction.setImageDescriptor(new AccessibleArrowImage(isLTR())); + showDropDownMenuAction + .setToolTipText(showChildrenText); + manager.add(showDropDownMenuAction); + + manager.update(true); + if (IS_MAC_WORKAROUND) { + manager.getControl().addMouseListener(new MouseAdapter() { + // see also BreadcrumbItemDetails#addElementListener(Control) + @Override + public void mouseDown(MouseEvent e) { + showDropDownMenuAction.run(); + } + }); + } + fToolBar.setData("org.eclipse.e4.ui.css.id", "BreadcrumbItemDropDownToolBar"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Return the width of this element. + * + * @return the width of this element + */ + public int getWidth() { + return fToolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + } + + /** + * Set whether the drop down menu is available. + * + * @param enabled true if available + */ + public void setEnabled(boolean enabled) { + fEnabled = enabled; + + fToolBar.setVisible(enabled); + } + + /** + * Tells whether the menu is shown. + * + * @return true if the menu is open + */ + public boolean isMenuShown() { + return fMenuIsShown; + } + + /** + * Returns the shell used for the drop down menu if it is shown. + * + * @return the drop down shell or null + */ + public Shell getDropDownShell() { + if (!isMenuShown()) + return null; + + return fShell; + } + + /** + * Returns the drop down selection provider. + * + * @return the selection provider of the drop down if the menu is shown, + * {@code null} otherwise. + */ + public ISelectionProvider getDropDownSelectionProvider() { + if (!fMenuIsShown) + return null; + + return fDropDownViewer; + } + + /** + * Opens the drop down menu. + */ + public void showMenu() { + + if (!fEnabled || fMenuIsShown) + return; + + fMenuIsShown = true; + + fShell = new Shell(fToolBar.getShell(), SWT.RESIZE | SWT.TOOL | SWT.ON_TOP); + + GridLayout layout = new GridLayout(1, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + fShell.setLayout(layout); + + Composite composite = new Composite(fShell, SWT.NONE); + composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout gridLayout = new GridLayout(1, false); + gridLayout.marginHeight = 0; + gridLayout.marginWidth = 0; + composite.setLayout(gridLayout); + + fDropDownViewer = fParent.getViewer().createDropDownViewer(composite, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); + fDropDownViewer.setUseHashlookup(true); + + final Tree tree = (Tree) fDropDownViewer.getControl(); + tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + Object input = fParent.getData(); + fParent.getViewer().configureDropDownViewer(fDropDownViewer, input); + fDropDownViewer.setInput(input); + + setShellBounds(fShell); + + fShell.addControlListener(new ControlAdapter() { + /* + * @see + * org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events. + * ControlEvent) + */ + @Override + public void controlResized(ControlEvent e) { + if (isResizingProgrammatically) + return; + + Point size = fShell.getSize(); + getDialogSettings().put(DIALOG_HEIGHT, size.y); + } + }); + + fDropDownViewer.addOpenListener(event -> { + + ISelection selection = event.getSelection(); + if (!(selection instanceof IStructuredSelection)) + return; + + Object element = ((IStructuredSelection) selection).getFirstElement(); + if (element == null) + return; + + openElement(element); + }); + + tree.addMouseListener(new MouseListener() { + @Override + public void mouseUp(MouseEvent e) { + + if (e.button != 1) + return; + + if ((OpenStrategy.getOpenMethod() & OpenStrategy.SINGLE_CLICK) != 0) + return; + + Item item = tree.getItem(new Point(e.x, e.y)); + if (item == null) + return; + + openElement(item.getData()); + } + + @Override + public void mouseDown(MouseEvent e) { + } + + @Override + public void mouseDoubleClick(MouseEvent e) { + } + }); + + tree.addMouseMoveListener(new MouseMoveListener() { + TreeItem fLastItem = null; + + @Override + public void mouseMove(MouseEvent e) { + if (tree.equals(e.getSource())) { + TreeItem o = tree.getItem(new Point(e.x, e.y)); + if ((o != null && !o.equals(fLastItem)) || (fLastItem != null && o == null)) { + boolean showHandPointer = false; + if (o != null) { + Object itemData = o.getData(); + showHandPointer = itemData != null && fParent.getViewer().isElementOpenable(itemData); + } + tree.setCursor(showHandPointer ? tree.getDisplay().getSystemCursor(SWT.CURSOR_HAND) : null); + } + if (o != null) { + Rectangle clientArea = tree.getClientArea(); + TreeItem currentItem = o; + if (!o.equals(fLastItem)) { + fLastItem = o; + tree.setSelection(new TreeItem[] { fLastItem }); + } else if (e.y - clientArea.y < tree.getItemHeight() / 4) { + // Scroll up + if (currentItem.getParentItem() == null) { + int index = tree.indexOf(o); + if (index < 1) + return; + + fLastItem = tree.getItem(index - 1); + tree.setSelection(new TreeItem[] { fLastItem }); + } else { + Point p = tree.toDisplay(e.x, e.y); + Item item = fDropDownViewer.scrollUp(p.x, p.y); + if (item instanceof TreeItem) { + fLastItem = (TreeItem) item; + tree.setSelection(new TreeItem[] { fLastItem }); + } + } + } else if (clientArea.y + clientArea.height - e.y < tree.getItemHeight() / 4) { + // Scroll down + if (currentItem.getParentItem() == null) { + int index = tree.indexOf(o); + if (index >= tree.getItemCount() - 1) + return; + + fLastItem = tree.getItem(index + 1); + tree.setSelection(new TreeItem[] { fLastItem }); + } else { + Point p = tree.toDisplay(e.x, e.y); + Item item = fDropDownViewer.scrollDown(p.x, p.y); + if (item instanceof TreeItem) { + fLastItem = (TreeItem) item; + tree.setSelection(new TreeItem[] { fLastItem }); + } + } + } + } else { + fLastItem = null; + } + } + } + }); + + tree.addKeyListener(new KeyListener() { + @Override + public void keyPressed(KeyEvent e) { + if (e.keyCode == SWT.ARROW_UP) { + TreeItem[] selection = tree.getSelection(); + if (selection.length != 1) + return; + + int selectionIndex = tree.indexOf(selection[0]); + if (selectionIndex != 0) + return; + + fShell.close(); + } + } + + @Override + public void keyReleased(KeyEvent e) { + } + }); + + fDropDownViewer.addTreeListener(new ITreeViewerListener() { + @Override + public void treeCollapsed(TreeExpansionEvent event) { + } + + @Override + public void treeExpanded(TreeExpansionEvent event) { + Shell shell = fShell; + tree.setRedraw(false); + shell.getDisplay().asyncExec(() -> { + if (shell.isDisposed() || tree.isDisposed()) + return; + + try { + resizeShell(shell); + } finally { + if (!tree.isDisposed()) + tree.setRedraw(true); + } + }); + } + }); + + int index = fParent.getViewer().getIndexOfItem(fParent); + if (index < fParent.getViewer().getItemCount() - 1) { + BreadcrumbItem childItem = fParent.getViewer().getItem(index + 1); + Object child = childItem.getData(); + + fDropDownViewer.setSelection(new StructuredSelection(child), true); + + TreeItem[] selection = tree.getSelection(); + if (selection.length > 0) { + tree.setTopItem(selection[0]); + } + } + + fShell.setVisible(true); + installCloser(fShell); + } + + private void openElement(Object data) { + if (data == null) + return; + + // This might or might not open an editor + fParent.getViewer().fireMenuSelection(data); + + boolean treeHasFocus = !fShell.isDisposed() && fDropDownViewer.getTree().isFocusControl(); + + if (fShell.isDisposed()) + return; + + if (!treeHasFocus) { + fShell.close(); + return; + } + + toggleExpansionState(data); + } + + private void toggleExpansionState(Object element) { + Tree tree = fDropDownViewer.getTree(); + if (fDropDownViewer.getExpandedState(element)) + fDropDownViewer.collapseToLevel(element, 1); + else { + tree.setRedraw(false); + try { + fDropDownViewer.expandToLevel(element, 1); + resizeShell(fShell); + } finally { + tree.setRedraw(true); + } + } + } + + /** + * The closer closes the given shell when the focus is lost. + * + * @param shell the shell to install the closer to + */ + private void installCloser(final Shell shell) { + final Listener focusListener = event -> { + Widget focusElement = event.widget; + boolean isFocusBreadcrumbTreeFocusWidget = focusElement == shell + || focusElement instanceof Tree && ((Tree) focusElement).getShell() == shell; + boolean isFocusWidgetParentShell = focusElement instanceof Control + && ((Control) focusElement).getShell().getParent() == shell; + + switch (event.type) { + case SWT.FocusIn: + + if (!isFocusBreadcrumbTreeFocusWidget && !isFocusWidgetParentShell) { + shell.close(); + } + break; + + case SWT.FocusOut: + + if (event.display.getActiveShell() == null) { + shell.close(); + } + break; + + default: + Assert.isTrue(false); + } + }; + + final Display display = shell.getDisplay(); + display.addFilter(SWT.FocusIn, focusListener); + display.addFilter(SWT.FocusOut, focusListener); + + final ControlListener controlListener = new ControlListener() { + @Override + public void controlMoved(ControlEvent e) { + shell.close(); + } + + @Override + public void controlResized(ControlEvent e) { + shell.close(); + } + }; + fToolBar.getShell().addControlListener(controlListener); + + shell.addDisposeListener(e -> { + + display.removeFilter(SWT.FocusIn, focusListener); + display.removeFilter(SWT.FocusOut, focusListener); + + if (!fToolBar.isDisposed()) { + fToolBar.getShell().removeControlListener(controlListener); + } + + // The shell may be disposed directly without receiving shellClosed. + fMenuIsShown = false; + fDropDownViewer = null; + }); + shell.addShellListener(new ShellListener() { + @Override + public void shellActivated(ShellEvent e) { + } + + @Override + public void shellClosed(ShellEvent e) { + + if (!fMenuIsShown) + return; + + fMenuIsShown = false; + fDropDownViewer = null; + } + + @Override + public void shellDeactivated(ShellEvent e) { + } + + @Override + public void shellDeiconified(ShellEvent e) { + } + + @Override + public void shellIconified(ShellEvent e) { + } + }); + } + + private IDialogSettings getDialogSettings() { + IDialogSettings viewerSettings = fParent.getViewer().getDialogSettings(); + IDialogSettings settings = viewerSettings.getSection(DIALOG_SETTINGS); + if (settings == null) + settings = viewerSettings.addNewSection(DIALOG_SETTINGS); + return settings; + } + + private int getMaxHeight() { + try { + return getDialogSettings().getInt(DIALOG_HEIGHT); + } catch (NumberFormatException e) { + return DROP_DOWN_DEFAULT_MAX_HEIGHT; + } + } + + /** + * Calculates a useful size for the given shell. + * + * @param shell the shell to calculate the size for. + */ + private void setShellBounds(Shell shell) { + Rectangle rect = fParentComposite.getBounds(); + Rectangle toolbarBounds = fToolBar.getBounds(); + + shell.pack(); + Point size = shell.getSize(); + int height = Math.max(Math.min(size.y, getMaxHeight()), DROP_DOWN_DEFAULT_MIN_HEIGHT); + int width = Math.max(Math.min(size.x, DROP_DOWN_MAX_WIDTH), DROP_DOWN_MIN_WIDTH); + + int imageBoundsX = 0; + if (fDropDownViewer.getTree().getItemCount() > 0) { + TreeItem item = fDropDownViewer.getTree().getItem(0); + imageBoundsX = item.getImageBounds(0).x; + } + + Rectangle trim = fShell.computeTrim(0, 0, width, height); + int x = toolbarBounds.x + toolbarBounds.width + 2 + trim.x - imageBoundsX; + if (!isLTR()) + x += width; + + // toDisplay expects coordinates relative to fParentComposite. + Point pt = new Point(x, rect.height); + pt = fParentComposite.toDisplay(pt); + + Rectangle monitor = Util.getClosestMonitor(shell.getDisplay(), pt).getClientArea(); + int overlap = (pt.x + width) - (monitor.x + monitor.width); + if (overlap > 0) + pt.x -= overlap; + if (pt.x < monitor.x) + pt.x = monitor.x; + + shell.setLocation(pt); + shell.setSize(width, height); + } + + /** + * Set the size of the given shell such that more content can be shown. The + * shell size does not exceed a user-configurable maximum. + * + * @param shell the shell to resize + */ + private void resizeShell(final Shell shell) { + Point size = shell.getSize(); + int currentWidth = size.x; + int currentHeight = size.y; + + int maxHeight = getMaxHeight(); + + if (currentHeight >= maxHeight && currentWidth >= DROP_DOWN_MAX_WIDTH) + return; + + Point preferedSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + + int newWidth; + if (currentWidth >= DROP_DOWN_MAX_WIDTH) { + newWidth = currentWidth; + } else { + newWidth = Math.min(Math.max(preferedSize.x, currentWidth), DROP_DOWN_MAX_WIDTH); + } + int newHeight; + if (currentHeight >= maxHeight) { + newHeight = currentHeight; + } else { + newHeight = Math.min(Math.max(preferedSize.y, currentHeight), maxHeight); + } + + if (newHeight != currentHeight || newWidth != currentWidth) { + shell.setRedraw(false); + try { + isResizingProgrammatically = true; + shell.setSize(newWidth, newHeight); + if (!isLTR()) { + Point location = shell.getLocation(); + shell.setLocation(location.x - (newWidth - currentWidth), location.y); + } + } finally { + isResizingProgrammatically = false; + shell.setRedraw(true); + } + } + } + + /** + * Tells whether this the breadcrumb is in LTR or RTL mode. + * + * @return true if the breadcrumb in left-to-right mode, + * false otherwise + */ + private boolean isLTR() { + return (fParentComposite.getStyle() & SWT.RIGHT_TO_LEFT) == 0; + } +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewer.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewer.java new file mode 100644 index 00000000000..ddec7e7a139 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewer.java @@ -0,0 +1,825 @@ +/******************************************************************************* + * Copyright (c) 2008, 2011 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Fabio Zadrozny - Bug 465666 + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.dialogs.DialogSettings; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.MenuDetectEvent; +import org.eclipse.swt.events.MenuDetectListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Widget; + +/** + * A breadcrumb viewer shows a the parent chain of its input element in a list. + * Each breadcrumb item of that list can be expanded and a sibling of the + * element presented by the breadcrumb item can be selected. + *

+ * Content providers for breadcrumb viewers must implement the + * ITreeContentProvider interface. + *

+ *

+ * Label providers for breadcrumb viewers must either implement + * ILabelProvider or extend CellLabelProvider. + *

+ * + * @since 3.41 + */ +public abstract class BreadcrumbViewer extends StructuredViewer { + + private static final boolean IS_GTK = "gtk".equals(SWT.getPlatform()); //$NON-NLS-1$ + + private final Composite fContainer; + private final ArrayList fBreadcrumbItems; + private final ListenerList fMenuListeners; + + private Image fGradientBackground; + private BreadcrumbItem fSelectedItem; + private ILabelProvider fToolTipLabelProvider; + private final IDialogSettings fDialogSettings = new DialogSettings("BreadcrumbViewer"); //$NON-NLS-1$ + + private final boolean fVertical; + + /** + * Create a new BreadcrumbViewer. + *

+ * Style is one of: + *

    + *
  • SWT.NONE
  • + *
  • SWT.VERTICAL
  • + *
  • SWT.HORIZONTAL
  • + *
+ * + * @param parent the container for the viewer + * @param style the style flag used for this viewer + */ + public BreadcrumbViewer(Composite parent, int style) { + fBreadcrumbItems = new ArrayList<>(); + fMenuListeners = new ListenerList<>(); + + fVertical = (SWT.VERTICAL & style) != 0; + + fContainer = new Composite(parent, SWT.NONE); + GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); + fContainer.setLayoutData(layoutData); + fContainer.addTraverseListener(e -> e.doit = true); + fContainer.setBackgroundMode(SWT.INHERIT_DEFAULT); + fContainer.setData("org.eclipse.e4.ui.css.id", "BreadcrumbComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + + hookControl(fContainer); + + int columns = 1000; + if (fVertical) { + columns = 1; + } + + GridLayout gridLayout = new GridLayout(columns, false); + gridLayout.marginWidth = 0; + gridLayout.marginHeight = 0; + gridLayout.verticalSpacing = 0; + gridLayout.horizontalSpacing = 0; + fContainer.setLayout(gridLayout); + + fContainer.addListener(SWT.Resize, event -> refresh()); + } + + /** + * Configure the given drop down viewer. The given input is used for the viewers + * input. Clients must at least set the label and the content provider for the + * viewer. + * + * @param viewer the viewer to configure + * @param input the input for the viewer + */ + protected abstract void configureDropDownViewer(TreeViewer viewer, Object input); + + /** + * The tool tip to use for the tool tip labels. null if the viewers + * label provider should be used. + * + * @param toolTipLabelProvider the label provider for the tool tips or + * null + */ + public void setToolTipLabelProvider(ILabelProvider toolTipLabelProvider) { + fToolTipLabelProvider = toolTipLabelProvider; + + for (BreadcrumbItem item : fBreadcrumbItems) { + item.refreshToolTip(); + } + } + + ILabelProvider getToolTipLabelProvider() { + return fToolTipLabelProvider; + } + + /* + * @see org.eclipse.jface.viewers.Viewer#getControl() + */ + @Override + public Control getControl() { + return fContainer; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#getRoot() + */ + @Override + protected Object getRoot() { + if (fBreadcrumbItems.isEmpty()) + return null; + + return fBreadcrumbItems.get(0).getData(); + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#reveal(java.lang.Object) + */ + @Override + public void reveal(Object element) { + // all elements are always visible + } + + /** + * Transfers the keyboard focus into the viewer. + */ + public void setFocus() { + fContainer.setFocus(); + + if (fSelectedItem != null) { + fSelectedItem.setFocus(true); + } else { + if (fBreadcrumbItems.isEmpty()) + return; + + BreadcrumbItem item = fBreadcrumbItems.get(fBreadcrumbItems.size() - 1); + if (item.getData() == null) { + if (fBreadcrumbItems.size() < 2) + return; + + item = fBreadcrumbItems.get(fBreadcrumbItems.size() - 2); + } + item.setFocus(true); + } + } + + /** + * @return true if any of the items in the viewer is expanded + */ + public boolean isDropDownOpen() { + for (BreadcrumbItem item : fBreadcrumbItems) { + if (item.isMenuShown()) + return true; + } + + return false; + } + + /** + * The shell used for the shown drop down or null if no drop down + * is shown at the moment. + * + * @return the drop downs shell or null + */ + public Shell getDropDownShell() { + for (BreadcrumbItem item : fBreadcrumbItems) { + if (item.isMenuShown()) + return item.getDropDownShell(); + } + + return null; + } + + /** + * Returns the selection provider which provides the selection of the drop down + * currently opened or null if no drop down is open at the moment. + * + * @return the selection provider of the open drop down or null + */ + public ISelectionProvider getDropDownSelectionProvider() { + for (BreadcrumbItem item : fBreadcrumbItems) { + if (item.isMenuShown()) { + return item.getDropDownSelectionProvider(); + } + } + + return null; + } + + /** + * Add the given listener to the set of listeners which will be informed when a + * context menu is requested for a breadcrumb item. + * + * @param listener the listener to add + */ + public void addMenuDetectListener(MenuDetectListener listener) { + fMenuListeners.add(listener); + } + + /** + * Remove the given listener from the set of menu detect listeners. Does nothing + * if the listener is not element of the set. + * + * @param listener the listener to remove + */ + public void removeMenuDetectListener(MenuDetectListener listener) { + fMenuListeners.remove(listener); + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#assertContentProviderType(org. + * eclipse.jface.viewers.IContentProvider) + */ + @Override + protected void assertContentProviderType(IContentProvider provider) { + super.assertContentProviderType(provider); + Assert.isTrue(provider instanceof ITreeContentProvider); + } + + /* + * @see org.eclipse.jface.viewers.Viewer#inputChanged(java.lang.Object, + * java.lang.Object) + */ + @Override + protected void inputChanged(Object fInput, Object oldInput) { + if (fContainer.isDisposed()) + return; + + disableRedraw(); + try { + rebuildItemChain(fInput); + } finally { + enableRedraw(); + } + } + + private void rebuildItemChain(Object input) { + if (fBreadcrumbItems.size() > 0) { + BreadcrumbItem last = fBreadcrumbItems.get(fBreadcrumbItems.size() - 1); + last.setIsLastItem(false); + } + + int lastIndex = buildItemChain(input); + + if (lastIndex > 0) { + BreadcrumbItem last = fBreadcrumbItems.get(lastIndex - 1); + last.setIsLastItem(true); + } + + while (lastIndex < fBreadcrumbItems.size()) { + BreadcrumbItem item = fBreadcrumbItems.remove(fBreadcrumbItems.size() - 1); + if (item == fSelectedItem) { + selectItem(null); + } + if (item.getData() != null) + unmapElement(item.getData(), item); + item.dispose(); + } + + updateSize(); + fContainer.layout(true, true); + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#doFindInputItem(java.lang.Object) + */ + @Override + protected Widget doFindInputItem(Object element) { + if (element == null) + return null; + + if (equals(element, getInput())) + return doFindItem(element); + + return null; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#doFindItem(java.lang.Object) + */ + @Override + protected Widget doFindItem(Object element) { + if (element == null) + return null; + + for (BreadcrumbItem item : fBreadcrumbItems) { + if (equals(element, item.getData())) + return item; + } + + return null; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#doUpdateItem(org.eclipse.swt. + * widgets.Widget, java.lang.Object, boolean) + */ + @Override + protected void doUpdateItem(Widget widget, Object element, boolean fullMap) { + if (widget instanceof BreadcrumbItem) { + final BreadcrumbItem item = (BreadcrumbItem) widget; + + // remember element we are showing + if (fullMap) { + associate(element, item); + } else { + Object data = item.getData(); + if (data != null) { + unmapElement(data, item); + } + item.setData(element); + mapElement(element, item); + } + + BreadcrumbViewerRow row = new BreadcrumbViewerRow(this, item); + ViewerCell cell = row.getCell(0); + + IBaseLabelProvider labelProvider = getLabelProvider(); + if (labelProvider instanceof CellLabelProvider cellLabelProvider) { + cellLabelProvider.update(cell); + } else { + ILabelProvider simpleLabelProvider = (ILabelProvider) labelProvider; + cell.setText(simpleLabelProvider.getText(element)); + cell.setImage(simpleLabelProvider.getImage(element)); + } + + item.refreshArrow(); + item.refreshToolTip(); + + updateSize(); + fContainer.layout(true, true); + } + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#getSelectionFromWidget() + */ + @Override + protected List getSelectionFromWidget() { + if (fSelectedItem == null) + return Collections.EMPTY_LIST; + + if (fSelectedItem.getData() == null) + return Collections.EMPTY_LIST; + + ArrayList result = new ArrayList<>(); + result.add(fSelectedItem.getData()); + return result; + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#internalRefresh(java.lang.Object) + */ + @Override + protected void internalRefresh(Object element) { + + disableRedraw(); + try { + if (equals(element, getRoot())) { + rebuildItemChain(getInput()); + return; + } + + BreadcrumbItem item = (BreadcrumbItem) doFindItem(element); + if (item == null) { + for (BreadcrumbItem item1 : fBreadcrumbItems) { + item1.refresh(); + } + } else { + item.refresh(); + } + + updateSize(); + fContainer.layout(true, true); + } finally { + enableRedraw(); + } + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#setSelectionToWidget(java.util. + * List, boolean) + */ + @Override + protected void setSelectionToWidget(List l, boolean reveal) { + BreadcrumbItem focusItem = null; + + for (BreadcrumbItem item : fBreadcrumbItems) { + if (item.hasFocus()) + focusItem = item; + + item.setSelected(false); + } + + fSelectedItem = null; + + if (l == null) + return; + + for (Object element : l) { + BreadcrumbItem item = (BreadcrumbItem) doFindItem(element); + if (item != null) { + item.setSelected(true); + fSelectedItem = item; + if (item == focusItem) { + item.setFocus(true); + } + } + } + } + + /** + * Set a single selection to the given item. null to deselect all. + * + * @param item the item to select or null + */ + void selectItem(BreadcrumbItem item) { + if (fSelectedItem != null) + fSelectedItem.setSelected(false); + + fSelectedItem = item; + setSelectionToWidget(getSelection(), false); + + if (item != null) { + setFocus(); + } else { + for (BreadcrumbItem listItem : fBreadcrumbItems) { + listItem.setFocus(false); + } + } + + fireSelectionChanged(new SelectionChangedEvent(this, getSelection())); + } + + /** + * Returns the item count. + * + * @return number of items shown in the viewer + */ + int getItemCount() { + return fBreadcrumbItems.size(); + } + + /** + * Returns the item for the given item index. + * + * @param index the index of the item + * @return the item ad the given index + */ + BreadcrumbItem getItem(int index) { + return fBreadcrumbItems.get(index); + } + + /** + * Returns the index of the given item. + * + * @param item the item to search + * @return the index of the item or -1 if not found + */ + int getIndexOfItem(BreadcrumbItem item) { + for (int i = 0, size = fBreadcrumbItems.size(); i < size; i++) { + BreadcrumbItem pItem = fBreadcrumbItems.get(i); + if (pItem == item) + return i; + } + + return -1; + } + + /** + * Notifies all double click listeners. + */ + void fireDoubleClick() { + fireDoubleClick(new DoubleClickEvent(this, getSelection())); + } + + /** + * Notifies all open listeners. + */ + void fireOpen() { + fireOpen(new OpenEvent(this, getSelection())); + } + + /** + * The given element was selected from a drop down menu. + * + * @param element the selected element + */ + void fireMenuSelection(Object element) { + fireOpen(new OpenEvent(this, new StructuredSelection(element))); + } + + /** + * A context menu has been requested for the selected breadcrumb item. + * + * @param event the event issued the menu detection + */ + void fireMenuDetect(MenuDetectEvent event) { + for (MenuDetectListener listener : fMenuListeners) { + listener.menuDetected(event); + } + } + + /** + * Set selection to the next or previous element if possible. + * + * @param next true if the next element should be selected, + * otherwise the previous one will be selected + */ + void doTraverse(boolean next) { + if (fSelectedItem == null) + return; + + int index = fBreadcrumbItems.indexOf(fSelectedItem); + if (next) { + if (index == fBreadcrumbItems.size() - 1) { + BreadcrumbItem current = fBreadcrumbItems.get(index); + + ITreeContentProvider contentProvider = (ITreeContentProvider) getContentProvider(); + if (!contentProvider.hasChildren(current.getData())) + return; + + current.openDropDownMenu(); + current.getDropDownShell().setFocus(); + } else { + BreadcrumbItem nextItem = fBreadcrumbItems.get(index + 1); + selectItem(nextItem); + } + } else { + if (index == 1) { + BreadcrumbItem root = fBreadcrumbItems.get(0); + root.openDropDownMenu(); + root.getDropDownShell().setFocus(); + } else { + selectItem(fBreadcrumbItems.get(index - 1)); + } + } + } + + /** + * Generates the parent chain of the given element. + * + * @param element element to build the parent chain for + * @return the first index of an item in fBreadcrumbItems which is not part of + * the chain + */ + private int buildItemChain(Object element) { + if (element == null) + return 0; + + ITreeContentProvider contentProvider = (ITreeContentProvider) getContentProvider(); + Object parent = contentProvider.getParent(element); + + int index = buildItemChain(parent); + + BreadcrumbItem item; + if (index < fBreadcrumbItems.size()) { + item = fBreadcrumbItems.get(index); + } else { + item = createItem(); + fBreadcrumbItems.add(item); + } + + if (equals(element, item.getData())) { + item.refresh(); + } else { + if (item.getData() != null) + unmapElement(item.getData(), item); + + item.setData(element); + item.refresh(); + } + if (parent == null) { + // don't show the models root + item.setDetailsVisible(false); + } + + mapElement(element, item); + + return index + 1; + } + + /** + * Creates and returns a new instance of a breadcrumb item. + * + * @return new instance of a breadcrumb item + */ + private BreadcrumbItem createItem() { + return new BreadcrumbItem(this, fContainer); + } + + /** + * Update the size of the items such that all items are visible, if possible. + * + * @return true if any item has changed, false + * otherwise + */ + private boolean updateSize() { + int width = fContainer.getClientArea().width; + + int currentWidth = getCurrentWidth(); + + boolean requiresLayout = false; + + if (currentWidth > width) { + int index = 0; + while (currentWidth > width && index < fBreadcrumbItems.size() - 1) { + BreadcrumbItem viewer = fBreadcrumbItems.get(index); + if (viewer.isShowText()) { + viewer.setShowText(false); + currentWidth = getCurrentWidth(); + requiresLayout = true; + } + + index++; + } + + } else if (currentWidth < width) { + + int index = fBreadcrumbItems.size() - 1; + while (currentWidth < width && index >= 0) { + + BreadcrumbItem viewer = fBreadcrumbItems.get(index); + if (!viewer.isShowText()) { + viewer.setShowText(true); + currentWidth = getCurrentWidth(); + if (currentWidth > width) { + viewer.setShowText(false); + index = 0; + } else { + requiresLayout = true; + } + } + + index--; + } + } + + return requiresLayout; + } + + /** + * Returns the current width of all items in the list. + * + * @return the width of all items in the list + */ + private int getCurrentWidth() { + int result = 0; + for (BreadcrumbItem viewer : fBreadcrumbItems) { + if (fVertical) { + result = Math.max(result, viewer.getWidth()); + } else { + result += viewer.getWidth(); + } + } + + return result; + } + + /** + * Enables redrawing of the breadcrumb. + */ + private void enableRedraw() { + if (IS_GTK) // flickers on GTK + return; + + fContainer.setRedraw(true); + } + + /** + * Disables redrawing of the breadcrumb. + * + *

+ * A call to this method must be followed by a call to + * {@link #enableRedraw()} + *

+ */ + private void disableRedraw() { + if (IS_GTK) // flickers on GTK + return; + + fContainer.setRedraw(false); + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#handleDispose(org.eclipse.swt. + * events.DisposeEvent) + * + */ + @Override + protected void handleDispose(DisposeEvent event) { + if (fGradientBackground != null) { + fGradientBackground.dispose(); + fGradientBackground = null; + } + + if (fToolTipLabelProvider != null) { + fToolTipLabelProvider.dispose(); + fToolTipLabelProvider = null; + } + + if (fBreadcrumbItems != null) { + Iterator iterator = fBreadcrumbItems.iterator(); + while (iterator.hasNext()) { + BreadcrumbItem item = iterator.next(); + item.dispose(); + } + } + + super.handleDispose(event); + } + + /** + * Returns whether the given element can be opened directly. + *

+ * Subclasses may override this method to define which elements can be opened. + * The default implementation returns {@code false}. + *

+ * + * @param element the element to check + * @return {@code true} if the element can be opened directly, {@code false} + * otherwise + */ + protected boolean isElementOpenable(Object element) { + return false; + } + + /** + * Creates the tree viewer used for the breadcrumb drop down. + *

+ * Subclasses may override this method to provide a specialized + * {@link TreeViewer}. The default implementation creates a standard + * {@link TreeViewer}. + *

+ * + * @param parent the parent composite + * @param style the SWT style bits + * @return the tree viewer used for the drop down + */ + protected TreeViewer createDropDownViewer(Composite parent, int style) { + return new TreeViewer(parent, style); + } + + /** + * Opens the drop down menu of the parent breadcrumb item for the given element. + * Does nothing if the element is not shown in the breadcrumb or has no parent + * item. + * + * @param element the element whose parent drop down should be opened + */ + public void openParentDropDown(Object element) { + BreadcrumbItem item = (BreadcrumbItem) doFindItem(element); + if (item == null) + return; + + int index = getIndexOfItem(item); + if (index <= 0) + return; + + BreadcrumbItem parent = getItem(index - 1); + if (parent != null) + parent.openDropDownMenu(); + } + + /** + * Returns the dialog settings used to store breadcrumb UI state. + *

+ * Subclasses may override this method to provide persistent dialog settings. + * The default implementation returns non-persistent settings. + *

+ * + * @return the dialog settings + */ + protected IDialogSettings getDialogSettings() { + return fDialogSettings; + } +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewerRow.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewerRow.java new file mode 100644 index 00000000000..7f389a76b8b --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/BreadcrumbViewerRow.java @@ -0,0 +1,194 @@ +/******************************************************************************* + * Copyright (c) 2007, 2011 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Widget; + +/** + * A viewer row for the breadcrumb viewer. + * + * @since 3.41 + */ +class BreadcrumbViewerRow extends ViewerRow { + + private final BreadcrumbItem fItem; + private final BreadcrumbViewer fViewer; + + public BreadcrumbViewerRow(BreadcrumbViewer viewer, BreadcrumbItem item) { + fViewer = viewer; + fItem = item; + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#clone() + */ + @Override + public Object clone() { + return new BreadcrumbViewerRow(fViewer, fItem); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getBackground(int) + */ + @Override + public Color getBackground(int columnIndex) { + return fItem.getBackground(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getBounds(int) + */ + @Override + public Rectangle getBounds(int columnIndex) { + return getBounds(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getBounds() + */ + @Override + public Rectangle getBounds() { + return fItem.getBounds(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getColumnCount() + */ + @Override + public int getColumnCount() { + return 1; + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getControl() + */ + @Override + public Control getControl() { + return fViewer.getControl(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getElement() + */ + @Override + public Object getElement() { + return fItem.getData(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getFont(int) + */ + @Override + public Font getFont(int columnIndex) { + return fItem.getFont(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getForeground(int) + */ + @Override + public Color getForeground(int columnIndex) { + return fItem.getForeground(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getImage(int) + */ + @Override + public Image getImage(int columnIndex) { + return fItem.getImage(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getItem() + */ + @Override + public Widget getItem() { + return fItem; + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getNeighbor(int, boolean) + */ + @Override + public ViewerRow getNeighbor(int direction, boolean sameLevel) { + return null; + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getText(int) + */ + @Override + public String getText(int columnIndex) { + return fItem.getText(); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#getTreePath() + */ + @Override + public TreePath getTreePath() { + return new TreePath(new Object[] { getElement() }); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#setBackground(int, + * org.eclipse.swt.graphics.Color) + */ + @Override + public void setBackground(int columnIndex, Color color) { + fItem.setBackground(color); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#setFont(int, + * org.eclipse.swt.graphics.Font) + */ + @Override + public void setFont(int columnIndex, Font font) { + fItem.setFont(font); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#setForeground(int, + * org.eclipse.swt.graphics.Color) + */ + @Override + public void setForeground(int columnIndex, Color color) { + fItem.setForeground(color); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#setImage(int, + * org.eclipse.swt.graphics.Image) + */ + @Override + public void setImage(int columnIndex, Image image) { + fItem.setImage(image); + } + + /* + * @see org.eclipse.jface.viewers.ViewerRow#setText(int, java.lang.String) + */ + @Override + public void setText(int columnIndex, String text) { + fItem.setText(text); + } + +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbDropDownSite.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbDropDownSite.java new file mode 100644 index 00000000000..65494a45468 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbDropDownSite.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2009 Wind River Systems and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Wind River Systems - initial API and implementation + *******************************************************************************/ +package org.eclipse.jface.viewers; + +/** + * Interface allowing breadcrumb drop-down implementors to communicate with + * their containing breadcrumb. + * + * @since 3.41 + */ +public interface TreePathBreadcrumbDropDownSite { + + /** + * Notifies the breadcrumb that the given selection was made in the drop-down + * viewer. + * @param selection Selection to set to breadcrumb. + */ + void notifySelection(ISelection selection); + + /** + * Notifies the breadcrumb that the drop-down viewer should be closed. + */ + void close(); + + /** + * Notifies the breadcrumb that the drop-down viewer's contents have + * changed and viewer shell should be adjusted for the new size. + */ + void updateSize(); +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItem.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItem.java new file mode 100644 index 00000000000..e9eb1e5df2e --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItem.java @@ -0,0 +1,237 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Pawel Piech (Wind River) - adapted breadcrumb for use in Debug view (Bug 252677) + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Item; +import org.eclipse.swt.widgets.Shell; + + +/** + * An item in a breadcrumb viewer. + *

+ * The item shows a label and an image. It also has the ability to expand, that + * is to open a drop down menu. + *

+ *

+ * The drop down allows to select any child of the items input element. The item + * shows the label and icon of its data element, if any. + *

+ * + * @since 3.41 + */ +class TreePathBreadcrumbItem extends Item { + + private TreePath fPath; + + private final TreePathBreadcrumbViewer fParent; + private final Composite fContainer; + + private final TreePathBreadcrumbItemDropDown fExpandBlock; + private final TreePathBreadcrumbItemDetails fDetailsBlock; + + private boolean fIsLast; + + /** + * A new breadcrumb item which is shown inside the given viewer. + * + * @param viewer the items viewer + * @param parent the container containing the item + */ + public TreePathBreadcrumbItem(TreePathBreadcrumbViewer viewer, Composite parent) { + super(parent, SWT.NONE); + + fParent= viewer; + + fContainer= new Composite(parent, SWT.NONE); + fContainer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + GridLayout layout= new GridLayout(2, false); + layout.marginBottom= 1; + layout.marginHeight= 0; + layout.marginWidth= 0; + layout.horizontalSpacing= 0; + fContainer.setLayout(layout); + + fExpandBlock= new TreePathBreadcrumbItemDropDown(this, fContainer); + fDetailsBlock= new TreePathBreadcrumbItemDetails(this, fContainer); + fContainer.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Returns this items viewer. + * + * @return the viewer showing this item + */ + public TreePathBreadcrumbViewer getViewer() { + return fParent; + } + + /* + * @see org.eclipse.swt.widgets.Widget#dispose() + */ + @Override + public void dispose() { + Shell shell = fExpandBlock.getDropDownShell(); + if (shell != null && !shell.isDisposed()) { + shell.dispose(); + } + fContainer.dispose(); + super.dispose(); + } + + public TreePath getPath() { + return fPath; + } + + public void setPath(TreePath path) { + fPath = path; + } + + /** + * Should this item show a text label. + * + * @param enabled true if it should + */ + void setShowText(boolean enabled) { + fDetailsBlock.setTextVisible(enabled); + } + + /** + * Does this item show a text label? + * + * @return true if it does. + */ + boolean isShowText() { + return fDetailsBlock.isTextVisible(); + } + + /** + * Returns the width of this item. + * + * @return the width of this item + */ + int getWidth() { + return fDetailsBlock.getWidth() + fExpandBlock.getWidth() + 2; + } + + /** + * Sets whether this item has to be marked as + * selected or not. + * + * @param selected true if marked as selected + */ + void setSelected(boolean selected) { + fDetailsBlock.setSelected(selected); + } + + /** + * Sets whether this item has the keyboard focus. + * + * @param state true if it has focus, false otherwise + */ + void setFocus(boolean state) { + fDetailsBlock.setFocus(state); + } + + /** + * Returns whether this item has the keyboard focus. + * + * @return true if this item has the keyboard focus + */ + boolean hasFocus() { + return fDetailsBlock.hasFocus(); + } + + /** + * Set whether this is the last item in the breadcrumb item chain or not. + * + * @param isLast true if this is the last item, false otherwise + */ + void setIsLastItem(boolean isLast) { + fIsLast= isLast; + + GridData data= (GridData) fContainer.getLayoutData(); + data.grabExcessHorizontalSpace= isLast; + } + + /** + * Expand this item, shows the drop down menu. + */ + void openDropDownMenu() { + fExpandBlock.showMenu(); + } + + /** + * @return true if this item is expanded + */ + boolean isMenuShown() { + return fExpandBlock.isMenuShown(); + } + + /** + * Returns the drop down shell. + * + * @return the shell of the drop down if shown, null otherwise + */ + Shell getDropDownShell() { + return fExpandBlock.getDropDownShell(); + } + + /** + * Returns the bounds of this item. + * + * @return the bounds of this item + */ + public Rectangle getBounds() { + return fContainer.getBounds(); + } + + /** + * Set the tool tip of the item to the given text. + * + * @param text the tool tip for the item + */ + public void setToolTip(String text) { + fDetailsBlock.setToolTip(text); + } + + /* + * @see org.eclipse.swt.widgets.Item#setText(java.lang.String) + */ + @Override + public void setText(String string) { + super.setText(string); + fDetailsBlock.setText(string); + + //more or less space might be required for the label + if (fIsLast) { + fContainer.layout(true, true); + } + } + + /* + * @see org.eclipse.swt.widgets.Item#setImage(org.eclipse.swt.graphics.Image) + */ + @Override + public void setImage(Image image) { + super.setImage(image); + fDetailsBlock.setImage(image); + } +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDetails.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDetails.java new file mode 100644 index 00000000000..f25841611c6 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDetails.java @@ -0,0 +1,393 @@ +/******************************************************************************* + * Copyright (c) 2008, 2009 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Pawel Piech (Wind River) - adapted breadcrumb for use in Debug view (Bug 252677) + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + + +/** + * The label and icon part of the breadcrumb item. + * + * @since 3.41 + */ +class TreePathBreadcrumbItemDetails { + + private final Label fElementImage; + private final Label fElementText; + private final Composite fDetailComposite; + private final TreePathBreadcrumbItem fParent; + private final Composite fTextComposite; + private final Composite fImageComposite; + + private boolean fTextVisible; + private boolean fSelected; + private boolean fHasFocus; + + + public TreePathBreadcrumbItemDetails(TreePathBreadcrumbItem parent, Composite parentContainer) { + fParent= parent; + fTextVisible= true; + + fDetailComposite= new Composite(parentContainer, SWT.NONE); + fDetailComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + GridLayout layout= new GridLayout(2, false); + layout.marginHeight= 0; + layout.marginWidth= 0; + layout.horizontalSpacing= 0; + fDetailComposite.setLayout(layout); + addElementListener(fDetailComposite); + + fImageComposite= new Composite(fDetailComposite, SWT.NONE); + fImageComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + layout= new GridLayout(1, false); + layout.marginHeight= 1; + layout.marginWidth= 2; + fImageComposite.setLayout(layout); + fImageComposite.addPaintListener(e -> { + if (fHasFocus && !isTextVisible()) { + e.gc.drawFocus(e.x, e.y, e.width, e.height); + } + }); + installFocusComposite(fImageComposite); + addElementListener(fImageComposite); + + fElementImage= new Label(fImageComposite, SWT.NONE); + GridData layoutData= new GridData(SWT.BEGINNING, SWT.CENTER, false, false); + fElementImage.setLayoutData(layoutData); + addElementListener(fElementImage); + + fTextComposite= new Composite(fDetailComposite, SWT.NONE); + fTextComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + layout= new GridLayout(1, false); + layout.marginHeight= 2; + layout.marginWidth= 2; + fTextComposite.setLayout(layout); + addElementListener(fTextComposite); + fTextComposite.addPaintListener(e -> { + if (fHasFocus && isTextVisible()) { + e.gc.drawFocus(e.x, e.y, e.width, e.height); + } + }); + installFocusComposite(fTextComposite); + + fElementText= new Label(fTextComposite, SWT.NONE); + + layoutData= new GridData(SWT.BEGINNING, SWT.CENTER, false, false); + fElementText.setLayoutData(layoutData); + addElementListener(fElementText); + + fTextComposite.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result= fElementText.getText(); + } + }); + fImageComposite.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result= fElementText.getText(); + } + }); + + fDetailComposite.setTabList(new Control[] { fTextComposite }); + + fDetailComposite.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemDetailComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + fTextComposite.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemDetailTextComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + fImageComposite.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemDetailImageComposite"); //$NON-NLS-1$ //$NON-NLS-2$ + fElementImage.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemDetailImageLabel"); //$NON-NLS-1$ //$NON-NLS-2$ + fElementText.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemDetailTextLabel"); //$NON-NLS-1$ //$NON-NLS-2$ + + } + + /** + * Returns whether this element has the keyboard focus. + * + * @return true if this element has the keyboard focus. + */ + public boolean hasFocus() { + return fHasFocus; + } + + /** + * Sets the tool tip to the given text. + * + * @param text the tool tip + */ + public void setToolTip(String text) { + if (isTextVisible()) { + fElementText.getParent().setToolTipText(text); + fElementText.setToolTipText(text); + + fElementImage.setToolTipText(text); + } else { + fElementText.getParent().setToolTipText(null); + fElementText.setToolTipText(null); + + fElementImage.setToolTipText(text); + } + } + + /** + * Sets the image to the given image. + * + * @param image the image to use + */ + public void setImage(Image image) { + if (image != fElementImage.getImage()) { + fElementImage.setImage(image); + } + } + + /** + * Sets the text to the given text. + * + * @param text the text to use + */ + public void setText(String text) { + if (text == null) { + text= ""; //$NON-NLS-1$ + } + if (!text.equals(fElementText.getText())) { + fElementText.setText(text); + } + } + + /** + * Returns the width of this element. + * + * @return current width of this element + */ + public int getWidth() { + int result= 2; + + if (fElementImage.getImage() != null) { + result+= fElementImage.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + } + + if (fTextVisible && fElementText.getText().length() > 0) { + result+= fElementText.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + } + + return result; + } + + public void setTextVisible(boolean enabled) { + if (fTextVisible == enabled) { + return; + } + + fTextVisible= enabled; + + GridData data= (GridData) fTextComposite.getLayoutData(); + data.exclude= !enabled; + fTextComposite.setVisible(enabled); + + if (fTextVisible) { + fDetailComposite.setTabList(new Control[] { fTextComposite }); + } else { + fDetailComposite.setTabList(new Control[] { fImageComposite }); + } + + if (fHasFocus) { + if (isTextVisible()) { + fTextComposite.setFocus(); + } else { + fImageComposite.setFocus(); + } + } + } + + /** + * Tells whether this item shows a text or only an image. + * + * @return true if it shows a text and an image, false if it only shows the image + */ + public boolean isTextVisible() { + return fTextVisible; + } + + public void setSelected(boolean selected) { + if (selected == fSelected) { + return; + } + + fSelected= selected; + + } + + public void setFocus(boolean enabled) { + if (enabled == fHasFocus) { + return; + } + + fHasFocus= enabled; + if (fHasFocus) { + if (isTextVisible()) { + fTextComposite.setFocus(); + } else { + fImageComposite.setFocus(); + } + } + } + + /** + * Install focus and key listeners to the given composite. + * + * @param composite the composite which may get focus + */ + private void installFocusComposite(Composite composite) { + composite.addTraverseListener(e -> { + if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { + int index= fParent.getViewer().getIndexOfItem(fParent); + if (e.detail == SWT.TRAVERSE_TAB_NEXT) { + index++; + } else { + index--; + } + + if (index > 0 && index < fParent.getViewer().getItemCount()) { + fParent.getViewer().selectItem(fParent.getViewer().getItem(index)); + } + + e.doit= true; + } + }); + composite.addKeyListener(new KeyListener() { + @Override + public void keyPressed(KeyEvent e) { + TreePathBreadcrumbViewer viewer= fParent.getViewer(); + + switch (e.keyCode) { + case SWT.ARROW_LEFT: + if (fSelected) { + viewer.doTraverse(false); + e.doit= false; + } else { + viewer.selectItem(fParent); + } + break; + case SWT.ARROW_RIGHT: + if (fSelected) { + viewer.doTraverse(true); + e.doit= false; + } else { + viewer.selectItem(fParent); + } + break; + case SWT.ARROW_DOWN: + case SWT.ARROW_UP: + case SWT.KEYPAD_ADD: + if (!fSelected) { + viewer.selectItem(fParent); + } + openDropDown(); + e.doit= false; + break; + case SWT.CR: + if (!fSelected) { + viewer.selectItem(fParent); + } + viewer.fireOpen(); + break; + default: + if (e.character == ' ') { + if (!fSelected) { + viewer.selectItem(fParent); + } + openDropDown(); + e.doit= false; + } + break; + } + } + + private void openDropDown() { + Shell shell = fParent.getDropDownShell(); + if (shell == null) { + fParent.openDropDownMenu(); + shell = fParent.getDropDownShell(); + } + shell.setFocus(); + } + + @Override + public void keyReleased(KeyEvent e) { + } + }); + + composite.addFocusListener(new FocusListener() { + @Override + public void focusGained(FocusEvent e) { + if (!fHasFocus) { + fHasFocus= true; + } + } + + @Override + public void focusLost(FocusEvent e) { + if (fHasFocus) { + fHasFocus= false; + } + } + }); + } + + /** + * Add mouse listeners to the given control. + * + * @param control the control to which may be clicked + */ + private void addElementListener(Control control) { + control.addMouseListener(new MouseListener() { + @Override + public void mouseDoubleClick(MouseEvent e) { + } + + @Override + public void mouseDown(MouseEvent e) { + TreePathBreadcrumbViewer viewer= fParent.getViewer(); + Shell shell= fParent.getDropDownShell(); + viewer.selectItem(fParent); + if (shell == null && e.button == 1 && e.stateMask == 0) { + fParent.getViewer().fireDoubleClick(); + } + } + + @Override + public void mouseUp(MouseEvent e) { + } + }); + control.addMenuDetectListener(e -> { + TreePathBreadcrumbViewer viewer= fParent.getViewer(); + viewer.selectItem(fParent); + fParent.getViewer().fireMenuDetect(e); + }); + } +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDropDown.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDropDown.java new file mode 100644 index 00000000000..a3425a10168 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbItemDropDown.java @@ -0,0 +1,583 @@ +/******************************************************************************* + * Copyright (c) 2008, 2025 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Pawel Piech (Wind River) - adapted breadcrumb for use in Debug view (Bug 252677) + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.ToolBarManager; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.resource.CompositeImageDescriptor; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.util.Util; +import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.ControlListener; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.ShellEvent; +import org.eclipse.swt.events.ShellListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageDataProvider; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.Widget; + + +/** + * The part of the breadcrumb item with the drop down menu. + * + * @since 3.41 + */ +class TreePathBreadcrumbItemDropDown implements TreePathBreadcrumbDropDownSite { + + private static final boolean IS_MAC_WORKAROUND= "carbon".equals(SWT.getPlatform()); //$NON-NLS-1$ + + /** + * An arrow image descriptor. The images color is related to the list + * fore- and background color. This makes the arrow visible even in high contrast + * mode. If ltr is true the arrow points to the right, otherwise it + * points to the left. + */ + private final class AccessibleArrowImage extends CompositeImageDescriptor { + + private final static int ARROW_SIZE= 5; + + private final boolean fLTR; + + public AccessibleArrowImage(boolean ltr) { + fLTR= ltr; + } + + /* + * @see org.eclipse.jface.resource.CompositeImageDescriptor#drawCompositeImage(int, int) + */ + @Override + protected void drawCompositeImage(int width, int height) { + Display display= fParentComposite.getDisplay(); + ImageDataProvider imageProvider = zoom -> { + Image image = new Image(display, ARROW_SIZE, ARROW_SIZE * 2); + + GC gc = new GC(image, fLTR ? SWT.LEFT_TO_RIGHT : SWT.RIGHT_TO_LEFT); + gc.setAntialias(SWT.ON); + + Color triangleColor = createColor(SWT.COLOR_LIST_FOREGROUND, SWT.COLOR_LIST_BACKGROUND, 0.2, display); + gc.setBackground(triangleColor); + gc.fillPolygon(new int[] { + 0, 0, ARROW_SIZE, ARROW_SIZE, 0, ARROW_SIZE * 2 }); + gc.dispose(); + + ImageData imageData = image.getImageData(zoom); + image.dispose(); + int zoomedArrowSize = ARROW_SIZE * zoom / 100; + for (int y1 = 0; y1 < zoomedArrowSize; y1++) { + // set opaque pixels for top half of the breadcrumb arrow + for (int x1 = 0; x1 <= y1; x1++) { + imageData.setAlpha(fLTR ? x1 : zoomedArrowSize - x1 - 1, y1, 255); + } + // set transparent pixels for top half of the breadcrumbe arrow + for (int x1 = y1 + 1; x1 < zoomedArrowSize; x1++) { + imageData.setAlpha(fLTR ? x1 : zoomedArrowSize - x1 - 1, y1, 0); + } + } + for (int y2 = 0; y2 < zoomedArrowSize; y2++) { + // set opaque pixels for bottom half of the breadcrumb arrow + for (int x2 = 0; x2 <= y2; x2++) { + imageData.setAlpha(fLTR ? x2 : zoomedArrowSize - x2 - 1, zoomedArrowSize * 2 - y2 - 1, 255); + } + // set transparent pixels for bottom half of the breadcrumbe arrow + for (int x2 = y2 + 1; x2 < zoomedArrowSize; x2++) { + imageData.setAlpha(fLTR ? x2 : zoomedArrowSize - x2 - 1, zoomedArrowSize * 2 - y2 - 1, 0); + } + } + return imageData; + }; + drawImage(imageProvider, (width / 2) - (ARROW_SIZE / 2), (height / 2) - ARROW_SIZE); + + } + + /* + * @see org.eclipse.jface.resource.CompositeImageDescriptor#getSize() + */ + @Override + protected Point getSize() { + return new Point(10, 16); + } + + private Color createColor(int color1, int color2, double weight, Display display) { + RGB rgb1= display.getSystemColor(color1).getRGB(); + RGB rgb2= display.getSystemColor(color2).getRGB(); + + return new Color(rgb1.blend(rgb2, weight)); + } + } + + // Workaround for bug 258196: set the minimum size to 500 because on Linux + // the size is not adjusted correctly in a virtual tree. + private static final int DROP_DOWN_MIN_WIDTH= 500; + private static final int DROP_DOWN_MAX_WIDTH= 501; + + private static final int DROP_DOWN_DEFAULT_MIN_HEIGHT= 100; + private static final int DROP_DOWN_DEFAULT_MAX_HEIGHT= 500; + + private static final String DIALOG_SETTINGS= "BreadcrumbItemDropDown"; //$NON-NLS-1$ + private static final String DIALOG_HEIGHT= "height"; //$NON-NLS-1$ + private static final String DIALOG_WIDTH= "width"; //$NON-NLS-1$ + + private final TreePathBreadcrumbItem fParent; + private final Composite fParentComposite; + private final ToolBar fToolBar; + + private boolean fMenuIsShown; + private boolean fEnabled; + private Shell fShell; + private boolean fIsResizingProgrammatically; + private int fCurrentWidth = -1; + private int fCurrentHeight = -1; + + + public TreePathBreadcrumbItemDropDown(TreePathBreadcrumbItem parent, Composite composite) { + fParent= parent; + fParentComposite= composite; + fMenuIsShown= false; + fEnabled= true; + + fToolBar= new ToolBar(composite, SWT.FLAT); + fToolBar.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false)); + fToolBar.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent e) { + e.result= JFaceResources.getString("BreadcrumbItemDropDown_showDropDownMenu_action_toolTip"); //$NON-NLS-1$ + } + }); + ToolBarManager manager= new ToolBarManager(fToolBar); + + final Action showDropDownMenuAction= new Action(null, SWT.NONE) { + @Override + public void run() { + Shell shell= fParent.getDropDownShell(); + if (shell != null) { + return; + } + + shell= fParent.getViewer().getDropDownShell(); + if (shell != null && !shell.isDisposed()) { + shell.close(); + } + + showMenu(); + + fShell.setFocus(); + } + }; + + showDropDownMenuAction.setImageDescriptor(new AccessibleArrowImage(isLeft())); + showDropDownMenuAction + .setToolTipText(JFaceResources.getString("BreadcrumbItemDropDown_showDropDownMenu_action_toolTip")); //$NON-NLS-1$ + manager.add(showDropDownMenuAction); + + manager.update(true); + if (IS_MAC_WORKAROUND) { + manager.getControl().addMouseListener(new MouseAdapter() { + // see also BreadcrumbItemDetails#addElementListener(Control) + @Override + public void mouseDown(MouseEvent e) { + showDropDownMenuAction.run(); + } + }); + } + fToolBar.setData("org.eclipse.e4.ui.css.id", "DebugBreadcrumbItemDropDownToolBar"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Return the width of this element. + * + * @return the width of this element + */ + public int getWidth() { + return fToolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + } + + /** + * Set whether the drop down menu is available. + * + * @param enabled true if available + */ + public void setEnabled(boolean enabled) { + fEnabled= enabled; + + fToolBar.setVisible(enabled); + } + + /** + * Tells whether the menu is shown. + * + * @return true if the menu is open + */ + public boolean isMenuShown() { + return fMenuIsShown; + } + + /** + * Returns the shell used for the drop down menu if it is shown. + * + * @return the drop down shell or null + */ + public Shell getDropDownShell() { + if (!isMenuShown()) { + return null; + } + + return fShell; + } + + /** + * Opens the drop down menu. + */ + public void showMenu() { + + if (!fEnabled || fMenuIsShown) { + return; + } + + fMenuIsShown= true; + + fShell= new Shell(fToolBar.getShell(), SWT.RESIZE | SWT.TOOL | SWT.ON_TOP); + + fShell.addControlListener(new ControlAdapter() { + /* + * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent) + */ + @Override + public void controlResized(ControlEvent e) { + if (fIsResizingProgrammatically) { + return; + } + + Point size= fShell.getSize(); + fCurrentWidth = size.x; + fCurrentHeight = size.y; + getDialogSettings().put(DIALOG_WIDTH, size.x); + getDialogSettings().put(DIALOG_HEIGHT, size.y); + } + }); + + GridLayout layout= new GridLayout(1, false); + layout.marginHeight= 0; + layout.marginWidth= 0; + fShell.setLayout(layout); + + Composite composite= new Composite(fShell, SWT.NONE); + composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout gridLayout= new GridLayout(1, false); + gridLayout.marginHeight= 0; + gridLayout.marginWidth= 0; + composite.setLayout(gridLayout); + + TreePath path= fParent.getPath(); + + Control control = fParent.getViewer().createDropDown(composite, this, path); + + control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + setShellBounds(fShell); + fShell.setVisible(true); + installCloser(fShell); + } + + /** + * The closer closes the given shell when the focus is lost. + * + * @param shell the shell to install the closer to + */ + private void installCloser(final Shell shell) { + final Listener focusListener= event -> { + Widget focusElement= event.widget; + boolean isFocusBreadcrumbTreeFocusWidget= focusElement == shell || focusElement instanceof Control && ((Control)focusElement).getShell() == shell; + boolean isFocusWidgetParentShell= focusElement instanceof Control && ((Control)focusElement).getShell().getParent() == shell; + + switch (event.type) { + case SWT.FocusIn: + + if (!isFocusBreadcrumbTreeFocusWidget && !isFocusWidgetParentShell) { + shell.close(); + } + break; + + case SWT.FocusOut: + if (event.display.getActiveShell() == null) { + shell.close(); + } + break; + + default: + Assert.isTrue(false); + } + }; + + final Display display= shell.getDisplay(); + display.addFilter(SWT.FocusIn, focusListener); + display.addFilter(SWT.FocusOut, focusListener); + + final ControlListener controlListener= new ControlListener() { + @Override + public void controlMoved(ControlEvent e) { + if (!shell.isDisposed()) { + shell.close(); + } + } + + @Override + public void controlResized(ControlEvent e) { + if (!shell.isDisposed()) { + shell.close(); + } + } + }; + fToolBar.getShell().addControlListener(controlListener); + + shell.addDisposeListener(e -> { + + display.removeFilter(SWT.FocusIn, focusListener); + display.removeFilter(SWT.FocusOut, focusListener); + + if (!fToolBar.isDisposed()) { + fToolBar.getShell().removeControlListener(controlListener); + } + // The shell may be disposed directly without receiving shellClosed. + fMenuIsShown = false; + }); + shell.addShellListener(new ShellListener() { + @Override + public void shellActivated(ShellEvent e) { + } + + @Override + public void shellClosed(ShellEvent e) { + if (!fMenuIsShown) { + return; + } + + fMenuIsShown= false; + } + + @Override + public void shellDeactivated(ShellEvent e) { + } + + @Override + public void shellDeiconified(ShellEvent e) { + } + + @Override + public void shellIconified(ShellEvent e) { + } + }); + } + + private IDialogSettings getDialogSettings() { + IDialogSettings viewerSettings = fParent.getViewer().getDialogSettings(); + IDialogSettings settings = viewerSettings.getSection(DIALOG_SETTINGS); + if (settings == null) { + settings = viewerSettings.addNewSection(DIALOG_SETTINGS); + } + return settings; + } + + private int getMaxWidth() { + try { + return getDialogSettings().getInt(DIALOG_WIDTH); + } catch (NumberFormatException e) { + return DROP_DOWN_MAX_WIDTH; + } + } + + private int getMaxHeight() { + try { + return getDialogSettings().getInt(DIALOG_HEIGHT); + } catch (NumberFormatException e) { + return DROP_DOWN_DEFAULT_MAX_HEIGHT; + } + } + + /** + * Calculates a useful size for the given shell. + * + * @param shell the shell to calculate the size for. + */ + private void setShellBounds(Shell shell) { + + Rectangle rect= fParentComposite.getBounds(); + Rectangle toolbarBounds= fToolBar.getBounds(); + + Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, false); + int height= Math.max(Math.min(size.y, getMaxHeight()), DROP_DOWN_DEFAULT_MIN_HEIGHT); + int width= Math.max(getMaxWidth(), DROP_DOWN_MIN_WIDTH); + + int imageBoundsX= 0; + if (fParent.getImage() != null) { + imageBoundsX= fParent.getImage().getImageData().width; + } + + Rectangle trim= fShell.computeTrim(0, 0, width, height); + int x= toolbarBounds.x + toolbarBounds.width + 2 + trim.x - imageBoundsX; + if (!isLeft()) { + x+= width; + } + + int y = 0; + if (isTop()) { + y+= rect.height; + } else { + y-= height; + } + + Point pt= new Point(x, y); + pt= fParentComposite.toDisplay(pt); + + Rectangle monitor = Util.getClosestMonitor(shell.getDisplay(), pt).getClientArea(); + int overlap= (pt.x + width) - (monitor.x + monitor.width); + if (overlap > 0) { + pt.x-= overlap; + } + if (pt.x < monitor.x) { + pt.x= monitor.x; + } + + shell.setLocation(pt); + fIsResizingProgrammatically= true; + try { + shell.setSize(width, height); + fCurrentWidth = width; + fCurrentHeight = height; + } finally { + fIsResizingProgrammatically= false; + } + } + + /** + * Set the size of the given shell such that more content can be shown. The shell size does not + * exceed a user-configurable maximum. + * + * @param shell the shell to resize + */ + private void resizeShell(final Shell shell) { + int maxHeight= getMaxHeight(); + int maxWidth = getMaxWidth(); + + if (fCurrentHeight >= maxHeight && fCurrentWidth >= maxWidth) { + return; + } + + Point preferedSize= shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + + int newWidth; + if (fCurrentWidth >= DROP_DOWN_MAX_WIDTH) { + newWidth= fCurrentWidth; + } else { + // Workaround for bug 319612: Do not resize width below the + // DROP_DOWN_MIN_WIDTH. This can happen because the Shell.getSize() + // is incorrectly small on Linux. + newWidth= Math.min(Math.max(Math.max(preferedSize.x, fCurrentWidth), DROP_DOWN_MIN_WIDTH), maxWidth); + } + int newHeight; + if (fCurrentHeight >= maxHeight) { + newHeight= fCurrentHeight; + } else { + newHeight= Math.min(Math.max(preferedSize.y, fCurrentHeight), maxHeight); + } + + if (newHeight != fCurrentHeight || newWidth != fCurrentWidth) { + shell.setRedraw(false); + try { + fIsResizingProgrammatically= true; + shell.setSize(newWidth, newHeight); + + Point location = shell.getLocation(); + Point newLocation = location; + if (!isLeft()) { + newLocation = new Point(newLocation.x - (newWidth - fCurrentWidth), newLocation.y); + } + if (!isTop()) { + newLocation = new Point(newLocation.x, newLocation.y - (newHeight - fCurrentHeight)); + } + if (!location.equals(newLocation)) { + shell.setLocation(newLocation.x, newLocation.y); + } + fCurrentWidth = newWidth; + fCurrentHeight = newHeight; + } finally { + fIsResizingProgrammatically= false; + shell.setRedraw(true); + } + } + } + + /** + * Tells whether this the breadcrumb is in LTR mode or RTL mode. Or whether the breadcrumb + * is on the right-side status coolbar, which has the same effect on layout. + * + * @return true if the breadcrumb in left-to-right mode, false + * otherwise + */ + private boolean isLeft() { + return (fParentComposite.getStyle() & SWT.RIGHT_TO_LEFT) == 0 && + (fParent.getViewer().getStyle() & SWT.RIGHT) == 0; + } + + /** + * Tells whether this the breadcrumb is in LTR mode or RTL mode. Or whether the breadcrumb + * is on the right-side status coolbar, which has the same effect on layout. + * + * @return true if the breadcrumb in left-to-right mode, false + * otherwise + */ + private boolean isTop() { + return (fParent.getViewer().getStyle() & SWT.BOTTOM) == 0; + } + + @Override + public void close() { + if (fShell != null && !fShell.isDisposed()) { + fShell.close(); + } + } + + @Override + public void notifySelection(ISelection selection) { + fParent.getViewer().fireMenuSelection(selection); + } + + @Override + public void updateSize() { + if (fShell != null && !fShell.isDisposed()) { + resizeShell(fShell); + } + } +} diff --git a/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbViewer.java b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbViewer.java new file mode 100644 index 00000000000..db357794b25 --- /dev/null +++ b/bundles/org.eclipse.jface/src/org/eclipse/jface/viewers/TreePathBreadcrumbViewer.java @@ -0,0 +1,832 @@ +/******************************************************************************* + * Copyright (c) 2008, 2018 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Pawel Piech (Wind River) - adapted breadcrumb for use in Debug view (Bug 252677) + *******************************************************************************/ +package org.eclipse.jface.viewers; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.dialogs.DialogSettings; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.MenuDetectEvent; +import org.eclipse.swt.events.MenuDetectListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Widget; + + +/** + * A breadcrumb viewer shows a the parent chain of its input element in a list. + * Each breadcrumb item of that list can be expanded and a sibling of the + * element presented by the breadcrumb item can be selected. + *

+ * Content providers for breadcrumb viewers must implement the + * ITreePathContentProvider interface. + *

+ *

+ * Label providers for breadcrumb viewers must implement the + * ITreePathLabelProvider interface. + *

+ * + * @since 3.41 + */ +public abstract class TreePathBreadcrumbViewer extends StructuredViewer { + + private static final boolean IS_GTK= "gtk".equals(SWT.getPlatform()); //$NON-NLS-1$ + private final IDialogSettings fDialogSettings = new DialogSettings("TreePathBreadcrumbViewer"); //$NON-NLS-1$ + + private final int fStyle; + private final Composite fContainer; + private final ArrayList fTreePathBreadcrumbItems; + private final ListenerList fMenuListeners; + + private Image fGradientBackground; + private TreePathBreadcrumbItem fSelectedItem; + + /** + * Create a new TreePathBreadcrumbViewer. + *

+ * Style is one of: + *

    + *
  • SWT.NONE
  • + *
  • SWT.VERTICAL
  • + *
  • SWT.HORIZONTAL
  • + *
  • SWT.BOTTOM
  • + *
  • SWT.RIGHT
  • + *
+ * + * @param parent the container for the viewer + * @param style the style flag used for this viewer + */ + public TreePathBreadcrumbViewer(Composite parent, int style) { + fStyle = style; + fTreePathBreadcrumbItems = new ArrayList<>(); + fMenuListeners= new ListenerList<>(); + + fContainer= new Composite(parent, SWT.NONE); + GridData layoutData= new GridData(SWT.FILL, SWT.TOP, true, false); + fContainer.setLayoutData(layoutData); + fContainer.addTraverseListener(e -> e.doit = true); + fContainer.setBackgroundMode(SWT.INHERIT_DEFAULT); + + hookControl(fContainer); + + int columns= 1000; + if ((SWT.VERTICAL & style) != 0) { + columns= 2; + } + + GridLayout gridLayout= new GridLayout(columns, false); + gridLayout.marginWidth= 0; + gridLayout.marginHeight= 0; + gridLayout.verticalSpacing= 0; + gridLayout.horizontalSpacing= 0; + fContainer.setLayout(gridLayout); + + fContainer.addListener(SWT.Resize, event -> { + updateSize(); + fContainer.layout(true, true); + }); + } + + int getStyle() { + return fStyle; + } + + /** + * Configure the given drop down viewer. The given input is used for the viewers input. Clients + * must at least set the label and the content provider for the viewer. + * @param parent the parent composite + * @param site the site to create the drop down for + * @param path the path to show + * @return the drop down control + */ + protected abstract Control createDropDown(Composite parent, TreePathBreadcrumbDropDownSite site, TreePath path); + + /* + * @see org.eclipse.jface.viewers.Viewer#getControl() + */ + @Override + public Control getControl() { + return fContainer; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#reveal(java.lang.Object) + */ + @Override + public void reveal(Object element) { + //all elements are always visible + } + + /** + * Transfers the keyboard focus into the viewer. + */ + public void setFocus() { + fContainer.setFocus(); + + if (fSelectedItem != null) { + fSelectedItem.setFocus(true); + } else { + if (fTreePathBreadcrumbItems.isEmpty()) { + return; + } + + TreePathBreadcrumbItem item= fTreePathBreadcrumbItems.get(fTreePathBreadcrumbItems.size() - 1); + item.setFocus(true); + } + } + + /** + * @return true if any of the items in the viewer is expanded + */ + public boolean isDropDownOpen() { + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + if (item.isMenuShown()) { + return true; + } + } + + return false; + } + + /** + * The shell used for the shown drop down or null + * if no drop down is shown at the moment. + * + * @return the drop downs shell or null + */ + public Shell getDropDownShell() { + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + if (item.isMenuShown()) { + return item.getDropDownShell(); + } + } + + return null; + } + + /** + * Add the given listener to the set of listeners which will be informed + * when a context menu is requested for a breadcrumb item. + * + * @param listener the listener to add + */ + public void addMenuDetectListener(MenuDetectListener listener) { + fMenuListeners.add(listener); + } + + /** + * Remove the given listener from the set of menu detect listeners. + * Does nothing if the listener is not element of the set. + * + * @param listener the listener to remove + */ + public void removeMenuDetectListener(MenuDetectListener listener) { + fMenuListeners.remove(listener); + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#assertContentProviderType(org.eclipse.jface.viewers.IContentProvider) + */ + @Override + protected void assertContentProviderType(IContentProvider provider) { + super.assertContentProviderType(provider); + Assert.isTrue(provider instanceof ITreePathContentProvider); + } + + /* + * @see org.eclipse.jface.viewers.Viewer#inputChanged(java.lang.Object, java.lang.Object) + */ + @Override + protected void inputChanged(final Object input, Object oldInput) { + if (fContainer.isDisposed()) { + return; + } + + disableRedraw(); + try { + preservingSelection(() -> buildItemChain(input)); + } finally { + enableRedraw(); + } + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#doFindInputItem(java.lang.Object) + */ + @Override + protected Widget doFindInputItem(Object element) { + if (element == null) { + return null; + } + + if (equals(element, getInput())) { + return doFindItem(element); + } + + return null; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#doFindItem(java.lang.Object) + */ + @Override + protected Widget doFindItem(Object element) { + if (element == null) { + return null; + } + + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + if (equals(element, item.getData())) { + return item; + } + } + + return null; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#doUpdateItem(org.eclipse.swt.widgets.Widget, java.lang.Object, boolean) + */ + @Override + protected void doUpdateItem(Widget widget, Object element, boolean fullMap) { + if (myDoUpdateItem(widget, element, fullMap)) { + updateSize(); + fContainer.layout(true, true); + } + } + + private boolean myDoUpdateItem(Widget widget, Object element, boolean fullMap) { + if (widget instanceof final TreePathBreadcrumbItem item) { + // remember element we are showing + if (fullMap) { + associate(element, item); + } else { + Object data= item.getData(); + if (data != null) { + unmapElement(data, item); + } + item.setData(element); + mapElement(element, item); + } + + return refreshItem(item); + } + return false; + } + + /** + * This implementation of getSelection() returns an instance of + * ITreeSelection. + * @return the current selection + */ + @Override + public ISelection getSelection() { + Control control = getControl(); + if (control == null || control.isDisposed()) { + return TreeSelection.EMPTY; + } + if (fSelectedItem != null) { + TreePath path = getTreePathFromItem(fSelectedItem); + if (path != null) { + return new TreeSelection(new TreePath[] { path }); + } + } + return TreeSelection.EMPTY; + } + + private TreePath getTreePathFromItem(TreePathBreadcrumbItem item) { + if (!fTreePathBreadcrumbItems.contains(item)) { + return null; + } + return item.getPath(); + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#getSelectionFromWidget() + */ + @Override + protected List getSelectionFromWidget() { + if (fSelectedItem == null) { + return Collections.EMPTY_LIST; + } + + if (fSelectedItem.getData() == null) { + return Collections.EMPTY_LIST; + } + + ArrayList result = new ArrayList<>(); + result.add(fSelectedItem.getData()); + return result; + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#internalRefresh(java.lang.Object) + */ + @Override + protected void internalRefresh(Object element) { + + disableRedraw(); + try { + if (equals(element, getRoot())) { + buildItemChain(getInput()); + return; + } + + boolean layoutChanged = false; + + TreePathBreadcrumbItem item= (TreePathBreadcrumbItem) doFindItem(element); + if (item == null) { + for (TreePathBreadcrumbItem currItem : fTreePathBreadcrumbItems) { + layoutChanged = refreshItem(currItem) || layoutChanged; + } + } else { + layoutChanged = refreshItem(item) || layoutChanged; + } + + if (layoutChanged) { + updateSize(); + fContainer.layout(true, true); + } + } finally { + enableRedraw(); + } + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#setSelectionToWidget(org.eclipse. + * jface.viewers.ISelection, boolean) + */ + @Override + protected void setSelectionToWidget(ISelection selection, boolean reveal) { + if (selection instanceof ITreeSelection treeSelection) { + TreePathBreadcrumbItem focusItem = null; + + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + if (item.hasFocus()) { + focusItem = item; + } + item.setSelected(false); + } + + fSelectedItem = null; + + for (TreePath path : treeSelection.getPaths()) { + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + if (path.equals(item.getPath(), getComparer())) { + item.setSelected(true); + fSelectedItem = item; + if (item == focusItem) { + focusItem = null; + } + break; + } + } + } + + if (fSelectedItem != null && focusItem != null) { + focusItem.setFocus(false); + } + return; + } + + super.setSelectionToWidget(selection, reveal); + } + + /* + * @see org.eclipse.jface.viewers.StructuredViewer#setSelectionToWidget(java.util.List, boolean) + */ + @Override + protected void setSelectionToWidget(List l, boolean reveal) { + TreePathBreadcrumbItem focusItem= null; + + // Unselect the currently selected items, and remember the focused item. + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + if (item.hasFocus()) { + focusItem= item; + } + + item.setSelected(false); + } + + if (l == null) { + l = Collections.EMPTY_LIST; + } + + // Set the new selection to items. + fSelectedItem = null; + for (Iterator iterator = l.iterator(); iterator.hasNext();) { + Object element= iterator.next(); + TreePathBreadcrumbItem item= (TreePathBreadcrumbItem) doFindItem(element); + if (item != null) { + item.setSelected(true); + fSelectedItem= item; + if (item == focusItem) { + focusItem = null; + } + } + } + + // If there is a new selection, and it does not overlap the old selection, + // remove the focus marker from the old focus item. + if (fSelectedItem != null && focusItem != null) { + focusItem.setFocus(false); + } + } + + /** + * Opens the drop-down menu for the breadcrumb item representing the given + * element. Does nothing if the element is not shown in the breadcrumb. + * + * @param element the element whose drop-down menu should be opened + * @since 3.41 + */ + public void openDropDownMenu(Object element) { + TreePathBreadcrumbItem item = (TreePathBreadcrumbItem) doFindItem(element); + if (item != null) { + item.openDropDownMenu(); + } + } + + /** + * Set a single selection to the given item. null to deselect all. + * + * @param item the item to select or null + */ + void selectItem(TreePathBreadcrumbItem item) { + if (fSelectedItem != null) { + fSelectedItem.setSelected(false); + } + + fSelectedItem= item; + setSelectionToWidget(getSelection(), false); + setFocus(); + + fireSelectionChanged(new SelectionChangedEvent(this, getSelection())); + } + + /** + * Returns the item count. + * + * @return number of items shown in the viewer + */ + int getItemCount() { + return fTreePathBreadcrumbItems.size(); + } + + /** + * Returns the item for the given item index. + * + * @param index the index of the item + * @return the item ad the given index + */ + TreePathBreadcrumbItem getItem(int index) { + return fTreePathBreadcrumbItems.get(index); + } + + /** + * Returns the index of the given item. + * + * @param item the item to search + * @return the index of the item or -1 if not found + */ + int getIndexOfItem(TreePathBreadcrumbItem item) { + for (int i= 0, size= fTreePathBreadcrumbItems.size(); i < size; i++) { + TreePathBreadcrumbItem pItem= fTreePathBreadcrumbItems.get(i); + if (pItem == item) { + return i; + } + } + + return -1; + } + + /** + * Notifies all double click listeners. + */ + void fireDoubleClick() { + fireDoubleClick(new DoubleClickEvent(this, getSelection())); + } + + /** + * Notifies all open listeners. + */ + void fireOpen() { + fireOpen(new OpenEvent(this, getSelection())); + } + + /** + * The given element was selected from a drop down menu. + * + * @param selection the selected element + */ + void fireMenuSelection(ISelection selection) { + fireOpen(new OpenEvent(this, selection)); + } + + /** + * A context menu has been requested for the selected breadcrumb item. + * + * @param event the event issued the menu detection + */ + void fireMenuDetect(MenuDetectEvent event) { + for (MenuDetectListener menuDetectListener : fMenuListeners) { + menuDetectListener.menuDetected(event); + } + } + + /** + * Set selection to the next or previous element if possible. + * + * @param next true if the next element should be selected, otherwise the previous + * one will be selected + */ + void doTraverse(boolean next) { + if (fSelectedItem == null) { + return; + } + + int index= fTreePathBreadcrumbItems.indexOf(fSelectedItem); + if (next) { + if (index == fTreePathBreadcrumbItems.size() - 1) { + TreePathBreadcrumbItem current= fTreePathBreadcrumbItems.get(index); + + current.openDropDownMenu(); + current.getDropDownShell().setFocus(); + } else { + TreePathBreadcrumbItem nextItem= fTreePathBreadcrumbItems.get(index + 1); + selectItem(nextItem); + } + } else { + if (index == 0) { + TreePathBreadcrumbItem root= fTreePathBreadcrumbItems.get(index); + root.openDropDownMenu(); + root.getDropDownShell().setFocus(); + } else { + selectItem(fTreePathBreadcrumbItems.get(index - 1)); + } + } + } + + /** + * Generates the parent chain of the given element. + * @param input element to build the parent chain for + */ + private void buildItemChain(Object input) { + if (fTreePathBreadcrumbItems.size() > 0) { + TreePathBreadcrumbItem last= fTreePathBreadcrumbItems.get(fTreePathBreadcrumbItems.size() - 1); + last.setIsLastItem(false); + } + + int index = 0; + boolean updateLayout = false; + if (input != null) { + ITreePathContentProvider contentProvider= (ITreePathContentProvider) getContentProvider(); + TreePath path = new TreePath(new Object[0]); + + // Top level elements need to be retrieved using getElements(), rest + // using getChildren(). + Object[] children = contentProvider.getElements(input); + Object element = children != null && children.length != 0 ? children[0] : null; + while (element != null) { + path = path.createChildPath(element); + + // All but last item are hidden if the viewer is in a vertical toolbar. + children = contentProvider.getChildren(path); + if ((getStyle() & SWT.VERTICAL) == 0 || children == null || children.length == 0) { + updateLayout = updateOrCreateItem(index++, path, element) || updateLayout; + } + + if (children != null && children.length != 0) { + element = children[0]; + } else { + break; + } + + } + } + + TreePathBreadcrumbItem last = null; + if (index > 0 && index <= fTreePathBreadcrumbItems.size()) { + last = (fTreePathBreadcrumbItems.get(index - 1)); + last.setIsLastItem(true); + } + + while (index < fTreePathBreadcrumbItems.size()) { + updateLayout = true; + TreePathBreadcrumbItem item= fTreePathBreadcrumbItems.remove(fTreePathBreadcrumbItems.size() - 1); + if (item.hasFocus() && last != null) { + last.setFocus(true); + } + if (item == fSelectedItem) { + selectItem(null); + } + if (item.getData() != null) { + unmapElement(item.getData(), item); + } + item.dispose(); + } + + if (updateLayout) { + updateSize(); + fContainer.layout(true, true); + } + } + + /** + * @param item Item to refresh. + * @return returns whether the item's size and layout needs to be updated. + */ + private boolean refreshItem(TreePathBreadcrumbItem item) { + boolean layoutChanged = false; + + TreePath path = getTreePathFromItem(item); + + ViewerLabel label = new ViewerLabel(item.getText(), item.getImage()); + ((ITreePathLabelProvider)getLabelProvider()).updateLabel(label, path); + + if (label.hasNewText()) { + item.setText(label.getText()); + layoutChanged = true; + } + if (label.hasNewImage()) { + item.setImage(label.getImage()); + layoutChanged = true; + } + if (label.hasNewTooltipText()) { + item.setToolTip(label.getTooltipText()); + } + return layoutChanged; + } + + /** + * Creates or updates a breadcrumb item. + * @param index the index + * @param path the path + * @param element the element + * + * @return whether breadcrumb layout needs to be updated due to this change + */ + private boolean updateOrCreateItem(int index, TreePath path, Object element) { + TreePathBreadcrumbItem item; + if (fTreePathBreadcrumbItems.size() > index) { + item = fTreePathBreadcrumbItems.get(index); + if (item.getData() != null) { + unmapElement(item.getData(), item); + } + } else { + item = new TreePathBreadcrumbItem(this, fContainer); + fTreePathBreadcrumbItems.add(item); + } + + boolean updateLayout = false; + + if (equals(element, item.getData())) { + item.setPath(path); + updateLayout = myDoUpdateItem(item, element, false); + } else { + item.setData(element); + item.setPath(path); + mapElement(element, item); + updateLayout = refreshItem(item); + } + + return updateLayout; + } + + /** + * Update the size of the items such that all items are visible, if possible. + * + * @return true if any item has changed, false otherwise + */ + private boolean updateSize() { + int width= fContainer.getClientArea().width; + + int currentWidth= getCurrentWidth(); + + boolean requiresLayout= false; + + if (currentWidth > width) { + int index= 0; + while (currentWidth > width && index < fTreePathBreadcrumbItems.size() - 1) { + TreePathBreadcrumbItem viewer= fTreePathBreadcrumbItems.get(index); + if (viewer.isShowText()) { + viewer.setShowText(false); + currentWidth= getCurrentWidth(); + requiresLayout= true; + } + + index++; + } + + } else if (currentWidth < width) { + + int index= fTreePathBreadcrumbItems.size() - 1; + while (currentWidth < width && index >= 0) { + + TreePathBreadcrumbItem viewer= fTreePathBreadcrumbItems.get(index); + if (!viewer.isShowText()) { + viewer.setShowText(true); + currentWidth= getCurrentWidth(); + if (currentWidth > width) { + viewer.setShowText(false); + index= 0; + } else { + requiresLayout= true; + } + } + + index--; + } + } + + return requiresLayout; + } + + /** + * Returns the current width of all items in the list. + * + * @return the width of all items in the list + */ + private int getCurrentWidth() { + int result= 0; + for (TreePathBreadcrumbItem viewer : fTreePathBreadcrumbItems) { + result+= viewer.getWidth(); + } + + return result; + } + + /** + * Enables redrawing of the breadcrumb. + */ + private void enableRedraw() { + if (IS_GTK) { + return; + } + + fContainer.setRedraw(true); + } + + /** + * Disables redrawing of the breadcrumb. + * + *

+ * A call to this method must be followed by a call to {@link #enableRedraw()} + *

+ */ + private void disableRedraw() { + if (IS_GTK) { + return; + } + + fContainer.setRedraw(false); + } + + /* + * @see + * org.eclipse.jface.viewers.StructuredViewer#handleDispose(org.eclipse.swt.events.DisposeEvent) + * + */ + @Override + protected void handleDispose(DisposeEvent event) { + if (fGradientBackground != null) { + fGradientBackground.dispose(); + fGradientBackground= null; + } + + if (fTreePathBreadcrumbItems != null) { + for (TreePathBreadcrumbItem item : fTreePathBreadcrumbItems) { + item.dispose(); + } + } + + super.handleDispose(event); + } + protected IDialogSettings getDialogSettings() { + return fDialogSettings; + } + } From e8ee5fbacbeac5a77a75c9841fbac762cd0c6dda Mon Sep 17 00:00:00 2001 From: Deepika Udayagiri Date: Fri, 6 Nov 2026 17:00:06 +0530 Subject: [PATCH 51/52] Add support for image zooming inside editor --- .../org.eclipse.ui.browser/plugin.properties | 1 + bundles/org.eclipse.ui.browser/plugin.xml | 12 +- .../internal/browser/ImageViewerEditor.java | 197 +++++++ .../ui/internal/browser/ImageZoomCanvas.java | 553 ++++++++++++++++++ .../ui/internal/browser/ImageZoomModel.java | 233 ++++++++ .../eclipse/ui/internal/browser/Messages.java | 5 + .../ui/internal/browser/Messages.properties | 5 + .../ui/tests/browser/internal/AllTests.java | 4 +- .../internal/ImageViewerEditorTest.java | 224 +++++++ .../browser/internal/ImageZoomModelTest.java | 269 +++++++++ 10 files changed, 1500 insertions(+), 3 deletions(-) create mode 100644 bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageViewerEditor.java create mode 100644 bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomCanvas.java create mode 100644 bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomModel.java create mode 100644 tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageViewerEditorTest.java create mode 100644 tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageZoomModelTest.java diff --git a/bundles/org.eclipse.ui.browser/plugin.properties b/bundles/org.eclipse.ui.browser/plugin.properties index 17c89ba0e5d..d275369de98 100644 --- a/bundles/org.eclipse.ui.browser/plugin.properties +++ b/bundles/org.eclipse.ui.browser/plugin.properties @@ -18,6 +18,7 @@ Plugin.providerName=Eclipse.org browser_extension_point_name=Web Browser viewWebBrowserTitle=Internal Web Browser +editorImageViewerTitle=Image Viewer viewWebBrowserSupportTitle= Web Browser preferenceWebBrowserTitle=Web Browser preferenceKeywords=HTML Firefox Mozilla Internet Opera Safari Chrome diff --git a/bundles/org.eclipse.ui.browser/plugin.xml b/bundles/org.eclipse.ui.browser/plugin.xml index fb1311ac06b..751218fd5d6 100644 --- a/bundles/org.eclipse.ui.browser/plugin.xml +++ b/bundles/org.eclipse.ui.browser/plugin.xml @@ -53,6 +53,16 @@ + + + + diff --git a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageViewerEditor.java b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageViewerEditor.java new file mode 100644 index 00000000000..4360c7b6a03 --- /dev/null +++ b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageViewerEditor.java @@ -0,0 +1,197 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.browser; + +import org.eclipse.core.runtime.Adapters; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.osgi.util.NLS; +import org.eclipse.swt.SWTError; +import org.eclipse.swt.SWTException; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorSite; +import org.eclipse.ui.IPathEditorInput; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.part.EditorPart; + +/** + * Shows an image file. A click zooms in and a click with the + * {@link org.eclipse.swt.SWT#MOD1} key zooms out, see {@link ImageZoomCanvas}. + *

+ * The file is decoded in a background job, so that a large image does not block + * the workbench. The SWT images are created in the UI thread. + *

+ *

+ * An SVG file is not loaded here: SWT would rasterize it once into a bitmap + * that gets blurry when zoomed, whereas the {@link WebBrowserEditor} renders it + * as a vector. It is opened in the browser editor right away, whether or not an + * SVG rasterizer is installed. + *

+ *

+ * A file that SWT cannot load, that holds no image, or that cannot be shown for + * lack of memory or handles, is opened in the {@link WebBrowserEditor} instead. + * The browser editor is opened before this editor is closed, so that the tab + * stays where it is. If the browser editor cannot be opened, a message is shown + * in this editor. + *

+ */ +public class ImageViewerEditor extends EditorPart { + public static final String IMAGE_VIEWER_EDITOR_ID = "org.eclipse.ui.browser.imageViewer"; //$NON-NLS-1$ + + private IPath path; + private ImageZoomCanvas canvas; + private Job loadJob; + + @Override + public void init(IEditorSite site, IEditorInput input) throws PartInitException { + IPathEditorInput pathInput = input instanceof IPathEditorInput pei ? pei + : Adapters.adapt(input, IPathEditorInput.class); + path = pathInput != null ? pathInput.getPath() : null; + if (path == null) { + throw new PartInitException(NLS.bind(Messages.errorInvalidImageInput, input.getName())); + } + setSite(site); + setInput(input); + setPartName(input.getName()); + String toolTip = input.getToolTipText(); + setTitleToolTip(toolTip != null ? toolTip : input.getName()); + } + + @Override + public void createPartControl(Composite parent) { + canvas = new ImageZoomCanvas(parent, 0); + Display display = parent.getDisplay(); + IWorkbenchPage page = getSite().getPage(); + IEditorInput input = getEditorInput(); + if (isSvg(input.getName())) { + // not directly: the editor is still being opened + display.asyncExec(() -> reopenInBrowser(page, input)); + return; + } + loadJob = Job.createSystem(NLS.bind(Messages.imageViewerLoading, input.getName()), monitor -> { + Runnable result; + try { + ImageLoader loader = new ImageLoader(); + ImageData[] data = loader.load(path.toOSString()); + result = () -> showImage(loader, data, page, input); + } catch (RuntimeException | SWTError | OutOfMemoryError e) { + result = () -> showFailure(e, page, input); + } + if (monitor.isCanceled()) { + return; + } + try { + display.asyncExec(result); + } catch (SWTException e) { + // the display is disposed, the workbench is closing + } + }); + loadJob.schedule(); + } + + private static boolean isSvg(String file) { + return file.regionMatches(true, file.length() - 4, ".svg", 0, 4); //$NON-NLS-1$ + } + + /** Runs in the UI thread. */ + private void showImage(ImageLoader loader, ImageData[] data, IWorkbenchPage page, IEditorInput input) { + if (canvas.isDisposed()) { + return; + } + if (data.length == 0) { + // a TIFF file with a header but no directory + showFailure(null, page, input); + return; + } + try { + canvas.setImageData(loader, data); + } catch (RuntimeException | SWTError | OutOfMemoryError e) { + showFailure(e, page, input); + } + } + + /** Runs in the UI thread. */ + private void showFailure(Throwable error, IWorkbenchPage page, IEditorInput input) { + Trace.trace(Trace.WARNING, "Cannot show " + input.getName() + " in the image viewer", error); //$NON-NLS-1$ //$NON-NLS-2$ + reopenInBrowser(page, input); + } + + @Override + public void dispose() { + if (loadJob != null) { + loadJob.cancel(); + } + super.dispose(); + } + + private void reopenInBrowser(IWorkbenchPage page, IEditorInput input) { + if (canvas.isDisposed()) { + return; + } + try { + // MATCH_ID is needed: with MATCH_INPUT alone this editor would be found + // and activated again instead of opening the browser editor. + IEditorPart opened = page.openEditor(input, WebBrowserEditor.WEB_BROWSER_EDITOR_ID, + page.getActivePart() == this, + IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID | IWorkbenchPage.MATCH_IGNORE_SIZE); + if (opened instanceof WebBrowserEditor) { + page.closeEditor(this, false); + } else { + // the workbench replaces a browser editor that fails to initialize with an + // error part, without throwing + if (opened != null) { + page.closeEditor(opened, false); + } + canvas.setMessage(NLS.bind(Messages.errorImageNotShown, input.getName())); + } + } catch (PartInitException e) { + Trace.trace(Trace.SEVERE, "Error opening " + input.getName() + " in the browser", e); //$NON-NLS-1$ //$NON-NLS-2$ + canvas.setMessage(NLS.bind(Messages.errorImageNotShown, input.getName())); + } + } + + @Override + public void setFocus() { + if (canvas != null && !canvas.isDisposed()) { + canvas.setFocus(); + } + } + + @Override + public void doSave(IProgressMonitor monitor) { + // read only + } + + @Override + public void doSaveAs() { + // read only + } + + @Override + public boolean isDirty() { + return false; + } + + @Override + public boolean isSaveAsAllowed() { + return false; + } +} diff --git a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomCanvas.java b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomCanvas.java new file mode 100644 index 00000000000..90dd05f3a66 --- /dev/null +++ b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomCanvas.java @@ -0,0 +1,553 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.browser; + +import java.util.function.BooleanSupplier; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.SWTException; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Cursor; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageGcDrawer; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.swt.widgets.ScrollBar; + +/** + * Shows one image with scrollbars. A click zooms in, a click with the + * {@link SWT#MOD1} key zooms out, and the mouse wheel with {@link SWT#MOD1} + * zooms continuously. The point under the mouse stays under the mouse. The + * context menu returns to fit mode or shows the image at its actual size. + *

+ * There is no keyboard shortcut yet. Reset to fit with Ctrl+0 and zoom with + * Ctrl+plus and Ctrl+minus need workbench commands, because the workbench + * already binds some of these keys, and are left for a later change. + *

+ *

+ * An image with several frames (an animated GIF) is played. + *

+ */ +public class ImageZoomCanvas extends Canvas { + + /** Size of the zoom cursor in points. */ + private static final int CURSOR_SIZE = 20; + /** The center of the lens, so the cursor points at what is zoomed. */ + private static final int CURSOR_HOTSPOT = 8; + + private final ImageZoomModel model = new ImageZoomModel(); + private final Cursor zoomInCursor; + private final Cursor zoomOutCursor; + + /** The scale when the current pinch gesture began, 0 if there is none. */ + private double pinchStartScale; + + private Image image; + private int imageWidth; + private int imageHeight; + private String message; + + private ImageData[] frames; + private int frameIndex; + private int loopsLeft; + private int repeatCount; + private Image snapshot; + private Runnable animationStep; + + /** + * @param parent the parent + * @param style the style, see {@link Canvas} + */ + public ImageZoomCanvas(Composite parent, int style) { + super(parent, style | SWT.H_SCROLL | SWT.V_SCROLL | SWT.DOUBLE_BUFFERED); + Display display = getDisplay(); + Cursor inCursor = createZoomCursor(display, true); + Cursor outCursor; + try { + outCursor = createZoomCursor(display, false); + } catch (RuntimeException | Error e) { + // The Dispose listener is not registered yet. + inCursor.dispose(); + throw e; + } + zoomInCursor = inCursor; + zoomOutCursor = outCursor; + setCursor(zoomInCursor); + + ScrollBar horizontal = getHorizontalBar(); + horizontal.setIncrement(20); + horizontal.addListener(SWT.Selection, e -> redraw()); + ScrollBar vertical = getVerticalBar(); + vertical.setIncrement(20); + vertical.addListener(SWT.Selection, e -> redraw()); + + addListener(SWT.Paint, e -> paint(e.gc)); + addListener(SWT.Resize, e -> updateScrollbars()); + addListener(SWT.MouseDown, e -> { + if (e.button == 1) { + boolean zoomOut = (e.stateMask & SWT.MOD1) != 0; + zoomAround(e.x, e.y, () -> zoomOut ? model.zoomOut(fitScale()) : model.zoomIn(fitScale())); + } + }); + addListener(SWT.MouseMove, e -> updateCursor((e.stateMask & SWT.MOD1) != 0)); + addListener(SWT.MouseEnter, e -> updateCursor((e.stateMask & SWT.MOD1) != 0)); + addListener(SWT.KeyDown, e -> { + if (e.keyCode == SWT.MOD1) { + updateCursor(true); + } + }); + addListener(SWT.KeyUp, e -> { + if (e.keyCode == SWT.MOD1) { + updateCursor(false); + } + }); + addListener(SWT.Gesture, this::handleGesture); + addListener(SWT.MouseWheel, e -> { + if ((e.stateMask & SWT.MOD1) != 0) { + e.doit = false; + // Event.count is not the same on every platform (3 per notch on GTK, lines + // per notch on Windows, at least 1 on macOS), so only the direction is used. + double notches = Integer.signum(e.count); + zoomAround(e.x, e.y, () -> model.zoomByWheel(notches, fitScale())); + } + }); + createContextMenu(); + addListener(SWT.Dispose, e -> { + Menu menu = getMenu(); + if (menu != null && !menu.isDisposed()) { + menu.dispose(); + } + clearImage(); + zoomInCursor.dispose(); + zoomOutCursor.dispose(); + }); + } + + private void createContextMenu() { + Menu menu = new Menu(this); + MenuItem fit = new MenuItem(menu, SWT.PUSH); + fit.setText(Messages.imageViewerFit); + fit.addListener(SWT.Selection, e -> { + model.setFit(); + updateScrollbars(); + redraw(); + }); + MenuItem actualSize = new MenuItem(menu, SWT.PUSH); + actualSize.setText(Messages.imageViewerActualSize); + actualSize.addListener(SWT.Selection, e -> { + Rectangle client = getClientArea(); + zoomAround(client.width / 2, client.height / 2, () -> model.actualSize(fitScale())); + }); + setMenu(menu); + } + + /** + * Shows a text instead of an image, for example the reason why there is none. + * The text is drawn while there is no image. + * + * @param text the text to show + */ + public void setMessage(String text) { + message = text; + redraw(); + } + + /** + * Shows the given images and returns to fit mode. The canvas creates its own + * {@link Image} from them and disposes it when it is disposed or when another + * image is set. + *

+ * Only a GIF with several images is played. Other formats, such as ICO and + * TIFF, also return several images, but these are alternatives and pages. The + * largest of them is shown. + *

+ * + * @param loader the loader that loaded data + * @param data the images, nothing is shown if it is empty + */ + public void setImageData(ImageLoader loader, ImageData[] data) { + clearImage(); + if (data.length == 0) { + return; + } + if (data.length > 1 && data[0].type == SWT.IMAGE_GIF) { + startAnimation(loader, data); + } else { + ImageData largest = data[0]; + for (ImageData candidate : data) { + if ((long) candidate.width * candidate.height > (long) largest.width * largest.height) { + largest = candidate; + } + } + image = new Image(getDisplay(), largest); + Rectangle bounds = image.getBounds(); + imageWidth = bounds.width; + imageHeight = bounds.height; + } + model.setFit(); + updateScrollbars(); + redraw(); + } + + private void startAnimation(ImageLoader loader, ImageData[] data) { + int width = loader.logicalScreenWidth; + int height = loader.logicalScreenHeight; + for (ImageData frame : data) { + width = Math.max(width, frame.x + frame.width); + height = Math.max(height, frame.y + frame.height); + } + imageWidth = width; + imageHeight = height; + image = new Image(getDisplay(), width, height); + fillBackground(new Rectangle(0, 0, width, height)); + frames = data; + frameIndex = 0; + repeatCount = loader.repeatCount; + loopsLeft = repeatCount; + renderFrame(frames[0]); + scheduleNextFrame(); + } + + private void scheduleNextFrame() { + // Delays of 0 and 10 ms are common in GIF files and are played as 100 ms. + int delay = frames[frameIndex].delayTime * 10; + Runnable step = new Runnable() { + @Override + public void run() { + if (!isDisposed() && animationStep == this) { + advanceFrame(); + } + } + }; + animationStep = step; + getDisplay().timerExec(delay <= 10 ? 100 : delay, step); + } + + private void advanceFrame() { + int next = frameIndex + 1; + if (next == frames.length) { + // repeat count 0 means forever + if (repeatCount != 0 && --loopsLeft <= 0) { + animationStep = null; + return; + } + next = 0; + } + ImageData current = frames[frameIndex]; + GC gc = new GC(image); + try { + if (current.disposalMethod == SWT.DM_FILL_BACKGROUND) { + // The canvas background is used on purpose, not the GIF background colour: it is + // usually unspecified (-1) and browsers clear a disposed frame to transparent. + gc.setBackground(getBackground()); + gc.fillRectangle(current.x, current.y, current.width, current.height); + } else if (current.disposalMethod == SWT.DM_FILL_PREVIOUS && snapshot != null) { + gc.drawImage(snapshot, 0, 0); + } + } finally { + gc.dispose(); + } + if (next == 0) { + // A new loop starts on a cleared image. This comes after the disposal of the + // last frame, because DM_FILL_PREVIOUS would bring back the old content. + fillBackground(new Rectangle(0, 0, imageWidth, imageHeight)); + } + frameIndex = next; + renderFrame(frames[frameIndex]); + scheduleNextFrame(); + redraw(); + } + + /** Draws a frame into the frame buffer. */ + private void renderFrame(ImageData data) { + if (snapshot != null) { + snapshot.dispose(); + snapshot = null; + } + if (data.disposalMethod == SWT.DM_FILL_PREVIOUS) { + snapshot = new Image(getDisplay(), imageWidth, imageHeight); + GC snapshotGc = new GC(snapshot); + try { + snapshotGc.drawImage(image, 0, 0); + } finally { + snapshotGc.dispose(); + } + } + Image frame = new Image(getDisplay(), data); + GC gc = null; + try { + gc = new GC(image); + gc.drawImage(frame, data.x, data.y); + } finally { + if (gc != null) { + gc.dispose(); + } + frame.dispose(); + } + } + + private void fillBackground(Rectangle area) { + GC gc = new GC(image); + try { + gc.setBackground(getBackground()); + gc.fillRectangle(area); + } finally { + gc.dispose(); + } + } + + private void clearImage() { + if (animationStep != null) { + getDisplay().timerExec(-1, animationStep); + animationStep = null; + } + frames = null; + if (snapshot != null) { + snapshot.dispose(); + snapshot = null; + } + if (image != null) { + image.dispose(); + image = null; + } + imageWidth = 0; + imageHeight = 0; + } + + private double fitScale() { + return fitScale(getClientArea()); + } + + private double fitScale(Rectangle client) { + return ImageZoomModel.fitScale(imageWidth, imageHeight, client.width, client.height); + } + + private double currentScale(Rectangle client) { + return model.getScale(fitScale(client)); + } + + /** + * Zooms with a pinch on a track pad. The magnification that SWT reports is + * relative to the start of the gesture, so the scale at that moment is kept. + */ + private void handleGesture(Event e) { + switch (e.detail) { + case SWT.GESTURE_BEGIN: + pinchStartScale = image != null ? currentScale(getClientArea()) : 0; + break; + case SWT.GESTURE_END: + pinchStartScale = 0; + break; + case SWT.GESTURE_MAGNIFY: + if (pinchStartScale > 0 && e.magnification > 0) { + e.doit = false; + double target = pinchStartScale * e.magnification; + zoomAround(e.x, e.y, () -> model.zoomTo(target, fitScale())); + } + break; + default: + break; + } + } + + private void updateCursor(boolean zoomOut) { + Cursor wanted = zoomOut ? zoomOutCursor : zoomInCursor; + if (getCursor() != wanted) { + setCursor(wanted); + } + } + + /** + * Changes the scale and scrolls so that the image point under (x, y) stays + * there, as far as the scroll range allows. + */ + private void zoomAround(int x, int y, BooleanSupplier changeScale) { + if (image == null) { + return; + } + ScrollBar horizontal = getHorizontalBar(); + ScrollBar vertical = getVerticalBar(); + Rectangle client = getClientArea(); + double oldScale = currentScale(client); + int oldOriginX = ImageZoomModel.origin(ImageZoomModel.scaledSize(imageWidth, oldScale), client.width, + horizontal.getSelection()); + int oldOriginY = ImageZoomModel.origin(ImageZoomModel.scaledSize(imageHeight, oldScale), client.height, + vertical.getSelection()); + double imageX = ImageZoomModel.imageCoordinate(x, oldOriginX, oldScale); + double imageY = ImageZoomModel.imageCoordinate(y, oldOriginY, oldScale); + + if (!changeScale.getAsBoolean()) { + return; + } + updateScrollbars(); + client = getClientArea(); + double newScale = currentScale(client); + int scaledWidth = ImageZoomModel.scaledSize(imageWidth, newScale); + int scaledHeight = ImageZoomModel.scaledSize(imageHeight, newScale); + if (scaledWidth > client.width) { + horizontal.setSelection( + clamp(ImageZoomModel.scrollOffsetFor(imageX, x, newScale), 0, scaledWidth - client.width)); + } + if (scaledHeight > client.height) { + vertical.setSelection( + clamp(ImageZoomModel.scrollOffsetFor(imageY, y, newScale), 0, scaledHeight - client.height)); + } + redraw(); + } + + private void updateScrollbars() { + if (isDisposed()) { + return; + } + // A scrollbar that appears or disappears changes the client area. Once more + // is enough for the second bar. + for (int pass = 0; pass < 2; pass++) { + Rectangle client = getClientArea(); + double scale = currentScale(client); + configure(getHorizontalBar(), ImageZoomModel.scaledSize(imageWidth, scale), client.width); + configure(getVerticalBar(), ImageZoomModel.scaledSize(imageHeight, scale), client.height); + } + } + + private static void configure(ScrollBar bar, int size, int viewSize) { + if (size <= viewSize) { + bar.setVisible(false); + bar.setSelection(0); + return; + } + bar.setMaximum(size); + bar.setThumb(viewSize); + bar.setPageIncrement(viewSize); + bar.setSelection(Math.min(bar.getSelection(), size - viewSize)); + bar.setVisible(true); + } + + private void paint(GC gc) { + if (image == null) { + if (message != null) { + gc.drawText(message, 10, 10, SWT.DRAW_TRANSPARENT | SWT.DRAW_DELIMITER); + } + return; + } + Rectangle client = getClientArea(); + double scale = currentScale(client); + int scaledWidth = ImageZoomModel.scaledSize(imageWidth, scale); + int scaledHeight = ImageZoomModel.scaledSize(imageHeight, scale); + int originX = ImageZoomModel.origin(scaledWidth, client.width, getHorizontalBar().getSelection()); + int originY = ImageZoomModel.origin(scaledHeight, client.height, getVerticalBar().getSelection()); + + // Only the visible part is drawn. At 2000% the whole image can be far larger + // than the window. + int visibleLeft = Math.max(0, originX); + int visibleTop = Math.max(0, originY); + int visibleRight = Math.min(client.width, originX + scaledWidth); + int visibleBottom = Math.min(client.height, originY + scaledHeight); + if (visibleRight <= visibleLeft || visibleBottom <= visibleTop) { + return; + } + int sourceLeft = clamp((int) Math.floor((visibleLeft - originX) / scale), 0, imageWidth); + int sourceTop = clamp((int) Math.floor((visibleTop - originY) / scale), 0, imageHeight); + int sourceRight = clamp((int) Math.ceil((visibleRight - originX) / scale), 0, imageWidth); + int sourceBottom = clamp((int) Math.ceil((visibleBottom - originY) / scale), 0, imageHeight); + int destLeft = originX + (int) Math.round(sourceLeft * scale); + int destTop = originY + (int) Math.round(sourceTop * scale); + int destRight = originX + (int) Math.round(sourceRight * scale); + int destBottom = originY + (int) Math.round(sourceBottom * scale); + + try { + gc.setAdvanced(true); + gc.setInterpolation(scale > ImageZoomModel.PIXELATED_ABOVE ? SWT.NONE : SWT.HIGH); + } catch (SWTException e) { + // no advanced graphics, the default scaling is used + } + int destWidth = Math.max(1, destRight - destLeft); + int destHeight = Math.max(1, destBottom - destTop); + gc.drawImage(image, sourceLeft, sourceTop, sourceRight - sourceLeft, sourceBottom - sourceTop, destLeft, + destTop, destWidth, destHeight); + } + + private static int clamp(int value, int min, int max) { + return Math.max(min, Math.min(max, value)); + } + + /** + * Creates a magnifier with a plus or a minus. SWT has no zoom cursors. + *

+ * The magnifier is drawn with an alpha channel and for the zoom that SWT asks + * for, so that it is sharp on a scaled display and has no background. + *

+ */ + private static Cursor createZoomCursor(Display display, boolean zoomIn) { + ImageGcDrawer drawer = new ImageGcDrawer() { + @Override + public void drawOn(GC gc, int width, int height) { + drawMagnifier(gc, display, zoomIn); + } + + @Override + public int getGcStyle() { + return SWT.TRANSPARENT; + } + }; + return new Cursor(display, zoom -> { + Image image = new Image(display, drawer, CURSOR_SIZE, CURSOR_SIZE); + try { + return image.getImageData(zoom); + } finally { + image.dispose(); + } + }, CURSOR_HOTSPOT, CURSOR_HOTSPOT); + } + + /** + * Draws the lens, the handle and the sign in a {@link #CURSOR_SIZE} square, + * with thin strokes. There is no halo around the shapes, so that nothing + * looks like a second handle on a coloured image. The handle starts inside + * the lens and the lens is drawn over it, so that there is no gap between + * them. + */ + private static void drawMagnifier(GC gc, Display display, boolean zoomIn) { + Color white = display.getSystemColor(SWT.COLOR_WHITE); + Color black = display.getSystemColor(SWT.COLOR_BLACK); + gc.setAntialias(SWT.ON); + + // handle, starting at the centre of the lens + gc.setLineCap(SWT.CAP_FLAT); + gc.setForeground(black); + gc.setLineWidth(2); + gc.drawLine(8, 8, 17, 17); + + // lens, drawn over the handle: white inside, black ring + gc.setBackground(white); + gc.fillOval(3, 3, 10, 10); + gc.setForeground(black); + gc.setLineWidth(1); + gc.drawOval(3, 3, 10, 10); + + // sign + gc.setLineCap(SWT.CAP_FLAT); + gc.drawLine(5, 8, 11, 8); + if (zoomIn) { + gc.drawLine(8, 5, 8, 11); + } + } +} diff --git a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomModel.java b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomModel.java new file mode 100644 index 00000000000..bc371e7f9d9 --- /dev/null +++ b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/ImageZoomModel.java @@ -0,0 +1,233 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.internal.browser; + +/** + * Zoom state and zoom arithmetic of the image viewer, without any widget. + *

+ * The viewer starts in fit mode: the image is shown as large as + * possible without being enlarged beyond 100% and without scrollbars. The first + * zoom step leaves fit mode and continues from the scale that was shown. + *

+ */ +public final class ImageZoomModel { + + /** The scales reached by the zoom in and zoom out steps. */ + private static final double[] LEVELS = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.5, 2, 3, 5, 7, 10, 15, + 20 }; + + /** Smallest scale that a zoom step can produce. */ + public static final double MIN_SCALE = LEVELS[0]; + + /** Largest scale that a zoom step can produce. */ + public static final double MAX_SCALE = LEVELS[LEVELS.length - 1]; + + /** Relative scale change of one mouse wheel notch. */ + public static final double WHEEL_STEP = 0.075; + + /** Above this scale the image is drawn without smoothing. */ + public static final double PIXELATED_ABOVE = 3; + + private static final double EPSILON = 1e-6; + + private boolean fit = true; + private double scale = 1; + + /** + * @return true if the image is fitted to the viewport + */ + public boolean isFit() { + return fit; + } + + /** + * Returns to fit mode. + */ + public void setFit() { + fit = true; + } + + /** + * @param fitScale the scale that fit mode shows right now + * @return the scale that is shown right now + */ + public double getScale(double fitScale) { + return fit ? fitScale : scale; + } + + /** + * Sets a scale that was chosen by a zoom out, by the mouse wheel or by the + * actual size. If it is the fit scale, the model returns to fit mode, so that + * the image follows the size of the viewport again. + */ + private void selectScale(double newScale, double fitScale) { + scale = newScale; + fit = Math.abs(newScale - fitScale) < EPSILON; + } + + /** + * Zooms in to the next level above the current scale. + * + * @param fitScale the scale that fit mode shows right now + * @return true if the scale changed + */ + public boolean zoomIn(double fitScale) { + double current = getScale(fitScale); + for (double level : LEVELS) { + if (level > current + EPSILON) { + scale = level; + fit = false; + return true; + } + } + return false; + } + + /** + * Zooms out to the next level below the current scale. + * + * @param fitScale the scale that fit mode shows right now + * @return true if the scale changed + */ + public boolean zoomOut(double fitScale) { + double current = getScale(fitScale); + for (int i = LEVELS.length - 1; i >= 0; i--) { + if (LEVELS[i] < current - EPSILON) { + selectScale(LEVELS[i], fitScale); + return true; + } + } + return false; + } + + /** + * Shows the image at 100%. If that is the fit scale, the model returns to fit + * mode. + * + * @param fitScale the scale that fit mode shows right now + * @return true if the scale changed + */ + public boolean actualSize(double fitScale) { + if (Math.abs(getScale(fitScale) - 1) < EPSILON) { + return false; + } + selectScale(1, fitScale); + return true; + } + + /** + * Zooms continuously, as done by the mouse wheel. + *

+ * The smallest result is {@link #MIN_SCALE}, but never more than the scale that + * is shown or than the fit scale. A large image can be fitted below + * {@link #MIN_SCALE}, and zooming out must not enlarge it. + *

+ * + * @param notches number of wheel notches, positive to zoom in, negative to + * zoom out + * @param fitScale the scale that fit mode shows right now + * @return true if the scale changed + */ + public boolean zoomByWheel(double notches, double fitScale) { + double factor = Math.max(0.01, 1 + notches * WHEEL_STEP); + return zoomTo(getScale(fitScale) * factor, fitScale); + } + + /** + * Zooms to the given scale, as done by a pinch gesture. + *

+ * The limits are those of {@link #zoomByWheel(double, double)}: the smallest + * result is {@link #MIN_SCALE}, but never more than the scale that is shown or + * than the fit scale, and the largest is {@link #MAX_SCALE}. + *

+ * + * @param target the wanted scale + * @param fitScale the scale that fit mode shows right now + * @return true if the scale changed + */ + public boolean zoomTo(double target, double fitScale) { + double current = getScale(fitScale); + double minimum = Math.min(MIN_SCALE, Math.min(fitScale, current)); + double result = Math.max(minimum, Math.min(MAX_SCALE, target)); + if (Math.abs(result - current) < EPSILON) { + return false; + } + selectScale(result, fitScale); + return true; + } + + /** + * Computes the scale at which the whole image is visible. An image that is + * smaller than the viewport is not enlarged. + * + * @return the fit scale, 1 if one of the sizes is not positive + */ + public static double fitScale(int imageWidth, int imageHeight, int viewWidth, int viewHeight) { + if (imageWidth <= 0 || imageHeight <= 0 || viewWidth <= 0 || viewHeight <= 0) { + return 1; + } + return Math.min(1, Math.min((double) viewWidth / imageWidth, (double) viewHeight / imageHeight)); + } + + /** + * @return the size of an image side at the given scale, in pixels + */ + public static int scaledSize(int imageSize, double scale) { + if (imageSize <= 0) { + return 0; + } + // Sides above 107,374,183 px at the largest scale (2000%) would overflow int. + return Math.max(1, (int) Math.round(imageSize * scale)); + } + + /** + * Returns the position of the scaled image inside the viewport along one axis. + * An image that is smaller than the viewport is centered, a larger one is + * moved by the scroll offset. + * + * @param scaledSize size of the scaled image + * @param viewSize size of the viewport + * @param scroll scroll offset, ignored if the image is not larger + * @return the viewport coordinate of the left (or top) edge of the image + */ + public static int origin(int scaledSize, int viewSize, int scroll) { + return scaledSize <= viewSize ? (viewSize - scaledSize) / 2 : -scroll; + } + + /** + * Converts a viewport coordinate into an image coordinate. + * + * @param viewPos coordinate in the viewport + * @param origin value of {@link #origin(int, int, int)} + * @param scale the scale that was shown + * @return the image coordinate under viewPos + */ + public static double imageCoordinate(int viewPos, int origin, double scale) { + return (viewPos - origin) / scale; + } + + /** + * Computes the scroll offset that puts an image coordinate at a viewport + * coordinate. This keeps the point under the mouse while zooming. The result is + * not limited to the scrollable range. + * + * @param imageCoord the image coordinate that must stay in place + * @param viewPos the viewport coordinate it must stay at + * @param scale the new scale + * @return the scroll offset + */ + public static int scrollOffsetFor(double imageCoord, int viewPos, double scale) { + return (int) Math.round(imageCoord * scale) - viewPos; + } +} diff --git a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.java b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.java index f9ab22962c1..e5510b04958 100644 --- a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.java +++ b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.java @@ -42,6 +42,11 @@ public class Messages extends NLS { public static String dialogResourceDeletedMessage; public static String dialogResourceDeletedIgnore; public static String errorInvalidEditorInput; + public static String errorInvalidImageInput; + public static String errorImageNotShown; + public static String imageViewerLoading; + public static String imageViewerFit; + public static String imageViewerActualSize; public static String preferenceWebBrowserDescription; public static String prefInternalBrowser; public static String prefExternalBrowser; diff --git a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.properties b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.properties index fd099e7b0f4..63e75a4ebe2 100644 --- a/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.properties +++ b/bundles/org.eclipse.ui.browser/src/org/eclipse/ui/internal/browser/Messages.properties @@ -51,6 +51,11 @@ errorCouldNotLaunchExternalWebBrowser=Could not launch external web browser for errorCouldNotLaunchWebBrowser=Could not launch web browser for {0}. Check the Web Browser preferences. errorNoBrowser=Could not open a web browser because there are none configured. Check the Web Browser preferences. errorInvalidEditorInput=Could not open web browser on {0}. Ensure that it is an uncompressed file. +errorInvalidImageInput=Could not open image viewer on {0}. Ensure that it is a file in the local file system. +errorImageNotShown=Could not show {0}. It is not an image that can be shown, and it could not be opened in the browser either. +imageViewerLoading=Loading image {0} +imageViewerFit=&Fit to Window +imageViewerActualSize=&Actual Size browserList=External &web browsers: add=&New... diff --git a/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/AllTests.java b/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/AllTests.java index fb30abc1dd6..cad4854ed37 100644 --- a/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/AllTests.java +++ b/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/AllTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2018 IBM Corporation and others. + * Copyright (c) 2004, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -22,7 +22,7 @@ ExistenceTestCase.class, InternalBrowserViewTestCase.class, InternalBrowserEditorTestCase.class, // ExternalBrowserTestCase.class); DialogsTestCase.class, PreferencesTestCase.class, TestInput.class, ToolbarBrowserTestCase.class, - WebBrowserUtilTestCase.class + WebBrowserUtilTestCase.class, ImageZoomModelTest.class, ImageViewerEditorTest.class }) public class AllTests { } \ No newline at end of file diff --git a/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageViewerEditorTest.java b/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageViewerEditorTest.java new file mode 100644 index 00000000000..ab38746cf5d --- /dev/null +++ b/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageViewerEditorTest.java @@ -0,0 +1,224 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.browser.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.graphics.PaletteData; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IPathEditorInput; +import org.eclipse.ui.IPersistableElement; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.internal.browser.ImageViewerEditor; +import org.eclipse.ui.internal.browser.WebBrowserEditor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Opens the image viewer on a file, to check the job that loads the image: a + * valid image stays in the viewer, a file that SWT cannot load, and an SVG, are + * reopened in the browser editor. + */ +public class ImageViewerEditorTest { + + private static final long TIMEOUT_MILLIS = 20_000; + + private IWorkbenchPage page; + private Path file; + private PathInput input; + + @BeforeEach + public void setUp() { + page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + } + + @AfterEach + public void tearDown() throws IOException { + if (input != null) { + IEditorPart editor = page.findEditor(input); + if (editor != null) { + page.closeEditor(editor, false); + } + } + if (file != null) { + Files.deleteIfExists(file); + } + } + + @Test + public void testImageStaysInTheImageViewer() throws Exception { + file = Files.createTempFile("imageViewerTest", ".png"); + ImageLoader loader = new ImageLoader(); + loader.data = new ImageData[] { new ImageData(2, 2, 24, new PaletteData(0xFF0000, 0xFF00, 0xFF)) }; + loader.save(file.toString(), SWT.IMAGE_PNG); + + openAndWaitForLoading(); + + assertInstanceOf(ImageViewerEditor.class, page.findEditor(input)); + } + + @Test + public void testFileThatCannotBeLoadedOpensInTheBrowser() throws Exception { + file = Files.createTempFile("imageViewerTest", ".png"); + Files.writeString(file, "this is not an image", StandardCharsets.UTF_8); + + openAndWaitForLoading(); + + assertInstanceOf(WebBrowserEditor.class, page.findEditor(input)); + } + + @Test + public void testFileWithoutImageOpensInTheBrowser() throws Exception { + // a TIFF header whose first directory offset is 0: SWT returns no image + file = Files.createTempFile("imageViewerTest", ".tif"); + Files.write(file, new byte[] { 0x49, 0x49, 42, 0, 0, 0, 0, 0 }); + + openAndWaitForLoading(); + + assertInstanceOf(WebBrowserEditor.class, page.findEditor(input)); + } + + @Test + public void testInputWithNullPathShowsErrorPart() throws Exception { + // init() rejects the input: the workbench shows its error part instead + IEditorPart editor = page.openEditor(new PathInput(null), ImageViewerEditor.IMAGE_VIEWER_EDITOR_ID); + try { + assertEquals("org.eclipse.ui.internal.ErrorEditorPart", editor.getClass().getName()); + } finally { + // the error part has a different input, so tearDown() cannot find it + page.closeEditor(editor, false); + } + } + + @Test + public void testSvgOpensInTheBrowser() throws Exception { + file = Files.createTempFile("imageViewerTest", ".SVG"); + Files.writeString(file, "", + StandardCharsets.UTF_8); + + input = new PathInput(IPath.fromOSString(file.toString())); + page.openEditor(input, ImageViewerEditor.IMAGE_VIEWER_EDITOR_ID); + + // no loading job: the viewer hands over to the browser from the UI thread + Display display = Display.getCurrent(); + long deadline = System.currentTimeMillis() + TIMEOUT_MILLIS; + while (!(page.findEditor(input) instanceof WebBrowserEditor)) { + assertTrue(System.currentTimeMillis() < deadline, "the SVG was not opened in the browser editor"); + if (!display.readAndDispatch()) { + Thread.sleep(10); + } + } + } + + /** + * Opens the file in the image viewer and returns when the loading job is gone + * and the result that it queued for the UI thread is handled. + */ + private void openAndWaitForLoading() throws Exception { + input = new PathInput(IPath.fromOSString(file.toString())); + page.openEditor(input, ImageViewerEditor.IMAGE_VIEWER_EDITOR_ID); + + Display display = Display.getCurrent(); + long deadline = System.currentTimeMillis() + TIMEOUT_MILLIS; + while (isLoading(input.getName())) { + assertTrue(System.currentTimeMillis() < deadline, "the loading job did not finish"); + if (!display.readAndDispatch()) { + Thread.sleep(10); + } + } + // the job queues its result before it ends + while (display.readAndDispatch()) { + // handle the queued result + } + } + + private static boolean isLoading(String fileName) { + for (Job job : Job.getJobManager().find(null)) { + if (job.getName().contains(fileName)) { + return true; + } + } + return false; + } + + private static final class PathInput implements IPathEditorInput { + private final IPath path; + + PathInput(IPath path) { + this.path = path; + } + + @Override + public IPath getPath() { + return path; + } + + @Override + public boolean exists() { + return true; + } + + @Override + public ImageDescriptor getImageDescriptor() { + return ImageDescriptor.getMissingImageDescriptor(); + } + + @Override + public String getName() { + return path != null ? path.lastSegment() : "nullPath.png"; + } + + @Override + public IPersistableElement getPersistable() { + return null; + } + + @Override + public String getToolTipText() { + return path != null ? path.toOSString() : "nullPath.png"; + } + + @Override + public T getAdapter(Class adapter) { + return null; + } + + @Override + public boolean equals(Object other) { + return other instanceof PathInput pathInput && Objects.equals(path, pathInput.path); + } + + @Override + public int hashCode() { + return Objects.hash(path); + } + } +} diff --git a/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageZoomModelTest.java b/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageZoomModelTest.java new file mode 100644 index 00000000000..e7884f0ec02 --- /dev/null +++ b/tests/org.eclipse.ui.tests.browser/src/org/eclipse/ui/tests/browser/internal/ImageZoomModelTest.java @@ -0,0 +1,269 @@ +/******************************************************************************* + * Copyright (c) 2026 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.ui.tests.browser.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.eclipse.ui.internal.browser.ImageZoomModel; +import org.junit.jupiter.api.Test; + +/** + * Tests the zoom arithmetic of the image viewer. The widget itself is not + * tested here. + */ +public class ImageZoomModelTest { + + private static final double DELTA = 1e-9; + + @Test + public void testStartsInFitMode() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.isFit()); + assertEquals(0.4, model.getScale(0.4), DELTA); + } + + @Test + public void testFirstZoomFromFitContinuesFromTheShownScale() { + ImageZoomModel in = new ImageZoomModel(); + assertTrue(in.zoomIn(0.55)); + assertFalse(in.isFit()); + assertEquals(0.6, in.getScale(0.55), DELTA); + + ImageZoomModel out = new ImageZoomModel(); + assertTrue(out.zoomOut(0.55)); + assertEquals(0.5, out.getScale(0.55), DELTA); + } + + @Test + public void testEightZoomInStepsFromFullSizeReachTheMaximum() { + ImageZoomModel model = new ImageZoomModel(); + double[] expected = { 1.5, 2, 3, 5, 7, 10, 15, 20 }; + for (double scale : expected) { + assertTrue(model.zoomIn(1), "step to " + scale); + assertEquals(scale, model.getScale(1), DELTA); + } + assertFalse(model.zoomIn(1), "no step above the maximum"); + assertEquals(ImageZoomModel.MAX_SCALE, model.getScale(1), DELTA); + } + + @Test + public void testNineZoomOutStepsFromFullSizeReachTheMinimum() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.zoomOut(1)); // leaves fit mode at 0.9 + for (int i = 0; i < 8; i++) { + assertTrue(model.zoomOut(1), "step " + (i + 2)); + } + assertEquals(ImageZoomModel.MIN_SCALE, model.getScale(1), DELTA); + assertFalse(model.zoomOut(1), "no step below the minimum"); + } + + @Test + public void testSetFitReturnsToTheFitScale() { + ImageZoomModel model = new ImageZoomModel(); + model.zoomIn(0.3); + model.setFit(); + assertTrue(model.isFit()); + assertEquals(0.25, model.getScale(0.25), DELTA); + } + + @Test + public void testActualSizeShowsFullSizeAndLeavesFitMode() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.actualSize(0.5)); + assertFalse(model.isFit()); + assertEquals(1, model.getScale(0.5), DELTA); + assertFalse(model.actualSize(0.5), "already at full size"); + } + + @Test + public void testActualSizeAtTheFitScaleStaysInFitMode() { + ImageZoomModel model = new ImageZoomModel(); + assertFalse(model.actualSize(1), "a small image is fitted at full size"); + assertTrue(model.isFit()); + model.zoomIn(1); + assertTrue(model.actualSize(1)); + assertTrue(model.isFit()); + } + + @Test + public void testWheelZoomUsesSevenAndAHalfPercentPerNotch() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.zoomByWheel(1, 1)); + assertEquals(1.075, model.getScale(1), DELTA); + assertTrue(model.zoomByWheel(-1, 1)); + assertEquals(1.075 * 0.925, model.getScale(1), DELTA); + assertFalse(model.isFit(), "above the fit scale the wheel stays in manual mode"); + } + + @Test + public void testWheelZoomIsLimited() { + ImageZoomModel model = new ImageZoomModel(); + for (int i = 0; i < 200; i++) { + model.zoomByWheel(1, 1); + } + assertEquals(ImageZoomModel.MAX_SCALE, model.getScale(1), DELTA); + assertFalse(model.zoomByWheel(1, 1)); + + for (int i = 0; i < 200; i++) { + model.zoomByWheel(-1, 1); + } + assertEquals(ImageZoomModel.MIN_SCALE, model.getScale(1), DELTA); + assertFalse(model.zoomByWheel(-1, 1)); + } + + @Test + public void testWheelZoomOutBelowMinimumDoesNotEnlargeFittedImage() { + ImageZoomModel model = new ImageZoomModel(); + double fitScale = 0.05; // below MIN_SCALE, a very large image + assertFalse(model.zoomByWheel(-1, fitScale)); + assertEquals(fitScale, model.getScale(fitScale), DELTA); + assertTrue(model.isFit()); + } + + @Test + public void testWheelZoomInFromBelowMinimumReturnsToTheFitScale() { + ImageZoomModel model = new ImageZoomModel(); + double fitScale = 0.05; + assertTrue(model.zoomByWheel(1, fitScale)); + assertEquals(fitScale * 1.075, model.getScale(fitScale), DELTA); + assertFalse(model.isFit()); + assertTrue(model.zoomByWheel(-1, fitScale)); + assertEquals(fitScale, model.getScale(fitScale), DELTA); + assertTrue(model.isFit()); + assertFalse(model.zoomByWheel(-1, fitScale)); + // the window was enlarged, a fitted image follows it + assertEquals(0.08, model.getScale(0.08), DELTA); + } + + @Test + public void testZoomToSetsTheScale() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.zoomTo(2.5, 1)); + assertFalse(model.isFit()); + assertEquals(2.5, model.getScale(1), DELTA); + assertFalse(model.zoomTo(2.5, 1), "same scale"); + } + + @Test + public void testZoomToIsLimited() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.zoomTo(1000, 1)); + assertEquals(ImageZoomModel.MAX_SCALE, model.getScale(1), DELTA); + assertFalse(model.zoomTo(1000, 1)); + + assertTrue(model.zoomTo(0.0001, 1)); + assertEquals(ImageZoomModel.MIN_SCALE, model.getScale(1), DELTA); + assertFalse(model.zoomTo(0.0001, 1)); + } + + @Test + public void testZoomToBelowMinimumDoesNotEnlargeFittedImage() { + ImageZoomModel model = new ImageZoomModel(); + double fitScale = 0.05; // below MIN_SCALE, a very large image + assertFalse(model.zoomTo(0.01, fitScale)); + assertEquals(fitScale, model.getScale(fitScale), DELTA); + assertTrue(model.isFit()); + } + + @Test + public void testZoomToTheFitScaleReturnsToFitMode() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.zoomTo(3, 0.5)); + assertFalse(model.isFit()); + assertTrue(model.zoomTo(0.5, 0.5)); + assertTrue(model.isFit()); + assertEquals(0.3, model.getScale(0.3), DELTA); + } + + @Test + public void testStepZoomOutToTheFitScaleReturnsToFitMode() { + ImageZoomModel model = new ImageZoomModel(); + assertTrue(model.zoomIn(0.5)); // 0.6 + assertTrue(model.zoomOut(0.5)); // 0.5 is a level and the fit scale + assertTrue(model.isFit()); + assertEquals(0.3, model.getScale(0.3), DELTA); + } + + @Test + public void testWheelZoomOutDoesNotEnlargeAfterTheFitScaleGrew() { + ImageZoomModel model = new ImageZoomModel(); + model.zoomByWheel(1, 0.05); // 0.05375, below MIN_SCALE + double shown = model.getScale(0.5); + // the window was enlarged, the fit scale is now larger than the shown scale + assertFalse(model.zoomByWheel(-1, 0.5)); + assertEquals(shown, model.getScale(0.5), DELTA); + } + + @Test + public void testStepZoomOutFromBelowMinimumDoesNotEnlarge() { + ImageZoomModel model = new ImageZoomModel(); + assertFalse(model.zoomOut(0.05)); + assertEquals(0.05, model.getScale(0.05), DELTA); + assertTrue(model.zoomIn(0.05)); + assertEquals(ImageZoomModel.MIN_SCALE, model.getScale(0.05), DELTA); + } + + @Test + public void testStepAfterWheelZoomGoesToTheNextLevel() { + ImageZoomModel model = new ImageZoomModel(); + model.zoomByWheel(1, 1); // 1.075 + model.zoomIn(1); + assertEquals(1.5, model.getScale(1), DELTA); + + model.zoomByWheel(-1, 1); // 1.3875 + model.zoomOut(1); + assertEquals(1, model.getScale(1), DELTA); + } + + @Test + public void testFitScaleDoesNotEnlarge() { + assertEquals(1, ImageZoomModel.fitScale(100, 50, 400, 400), DELTA); + assertEquals(0.5, ImageZoomModel.fitScale(800, 400, 400, 400), DELTA); + assertEquals(0.25, ImageZoomModel.fitScale(400, 1600, 400, 400), DELTA); + assertEquals(1, ImageZoomModel.fitScale(0, 50, 400, 400), DELTA, "empty image"); + assertEquals(1, ImageZoomModel.fitScale(100, 50, 0, 400), DELTA, "empty viewport"); + } + + @Test + public void testOriginCentersSmallImagesAndScrollsLargeOnes() { + assertEquals(100, ImageZoomModel.origin(200, 400, 77)); + assertEquals(-77, ImageZoomModel.origin(1000, 400, 77)); + assertEquals(0, ImageZoomModel.origin(400, 400, 0)); + } + + @Test + public void testPointUnderTheMouseStaysWhenZoomingIn() { + // image 1000 wide, viewport 500, scrolled by 200, mouse at 100, scale 1 + double scale = 1; + int origin = ImageZoomModel.origin(1000, 500, 200); + double imageX = ImageZoomModel.imageCoordinate(100, origin, scale); + assertEquals(300, imageX, DELTA); + + double newScale = 2; + int scroll = ImageZoomModel.scrollOffsetFor(imageX, 100, newScale); + assertEquals(500, scroll); + int newOrigin = ImageZoomModel.origin(2000, 500, scroll); + assertEquals(imageX, ImageZoomModel.imageCoordinate(100, newOrigin, newScale), DELTA); + } + + @Test + public void testScaledSizeKeepsPositiveDimensionsAtLeastOnePixel() { + assertEquals(0, ImageZoomModel.scaledSize(0, 0.5)); + assertEquals(1, ImageZoomModel.scaledSize(1, 0.01)); + assertEquals(1, ImageZoomModel.scaledSize(1, 0.1)); + assertEquals(10, ImageZoomModel.scaledSize(100, 0.1)); + } +} From 747d2bb6df2de19682001931895a1f7c92220e18 Mon Sep 17 00:00:00 2001 From: Gerd Grossmann Date: Thu, 12 Nov 2026 12:25:13 +0100 Subject: [PATCH 52/52] Keep the horizontal scroll position when the text viewer redraws again Re-enabling the redraw of a TextViewer resumes the forwarding of the document changes, which resets the content of the StyledText and scrolls it back to the start of the lines. The top index, selection and caret are restored afterwards, but the horizontal scroll position is lost. The same happens when a ProjectionViewer replaces its visible document. So while typing at the end of a long line, the editor jumps back to the start of the line whenever the redraw is toggled, for example when the folding regions of a large file are updated or a rewrite session is used, although the caret stays in place. Remember the horizontal scroll position when the redraw is disabled and restore it when the redraw is enabled again, unless a selection set in the meantime has been revealed. Do the same when the ProjectionViewer replaces its visible document. Fixes https://github.com/eclipse-platform/eclipse.platform.ui/issues/3856 Assisted-by: GitHub Copilot Claude (claude-opus-5.5) --- .../source/projection/ProjectionViewer.java | 5 ++ .../org/eclipse/jface/text/TextViewer.java | 18 ++++- .../text/tests/ProjectionViewerTest.java | 69 +++++++++++++++++++ .../jface/text/tests/TextViewerTest.java | 38 +++++++++- 4 files changed, 127 insertions(+), 3 deletions(-) diff --git a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java index ee0a1303f87..bff5f9676a9 100644 --- a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java +++ b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java @@ -953,6 +953,7 @@ private void executeReplaceVisibleDocument(IDocument visibleDocument) { } int topIndex= getTopIndex(); + int horizontalPixel= textWidget != null && !textWidget.isDisposed() ? textWidget.getHorizontalPixel() : 0; Point selection= getSelectedRange(); setVisibleDocument(visibleDocument); Point currentSelection= getSelectedRange(); @@ -960,6 +961,10 @@ private void executeReplaceVisibleDocument(IDocument visibleDocument) { setSelectedRange(selection.x, selection.y); } setTopIndex(topIndex); + // setting the visible document resets the widget, which scrolls it back to the start of the lines + if (horizontalPixel > 0 && textWidget != null && !textWidget.isDisposed()) { + textWidget.setHorizontalPixel(horizontalPixel); + } } finally { if (textWidget != null && !textWidget.isDisposed()) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java index a6905e5a74e..b1abbc23341 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2019 IBM Corporation and others. + * Copyright (c) 2000, 2026 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -1725,6 +1725,11 @@ public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { * @since 3.3 */ private ViewerState fViewerState; + /** + * The horizontal scroll offset of the text widget in pixels when the redraw was disabled, + * -1 when in redraw state. + */ + private int fHorizontalPixel= -1; /** * The editor's tab converter. * @since 3.3 @@ -5236,14 +5241,22 @@ protected void enabledRedrawing(int topIndex) { } } + boolean selectionRevealed= false; if (fViewerState != null) { - fViewerState.restore(topIndex == -1); + boolean restoreViewport= topIndex == -1; + selectionRevealed= restoreViewport && fViewerState.fSelectionSet; + fViewerState.restore(restoreViewport); fViewerState= null; } if (fTextWidget != null && !fTextWidget.isDisposed()) { + // resuming the forwarding of the document changes resets the widget, which scrolls it back to the start of the lines + if (fHorizontalPixel > 0 && !selectionRevealed) { + fTextWidget.setHorizontalPixel(fHorizontalPixel); + } fTextWidget.setRedraw(true); } + fHorizontalPixel= -1; fireRedrawChanged(); } @@ -5262,6 +5275,7 @@ protected void disableRedrawing() { } if (fTextWidget != null && !fTextWidget.isDisposed()) { + fHorizontalPixel= fTextWidget.getHorizontalPixel(); fTextWidget.setRedraw(false); } diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/ProjectionViewerTest.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/ProjectionViewerTest.java index 6c180f55a2a..8ea36f76948 100644 --- a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/ProjectionViewerTest.java +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/ProjectionViewerTest.java @@ -15,11 +15,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.layout.FillLayout; @@ -37,6 +41,7 @@ import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.projection.ProjectionDocument; +import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.IVerticalRuler; @@ -827,4 +832,68 @@ void testSetVisibleRegionUntilEOF() { viewer.setVisibleRegion(start, end - start); assertEquals(documentContent.substring(start), viewer.getVisibleDocument().get()); } + + @Test + void testReinitializeProjectionKeepsHorizontalScrollPosition() throws BadLocationException { + Shell shell= new Shell(Display.getCurrent()); + try { + String longLine= "x".repeat(500); + String content= "folded\nhidden\n" + longLine + "\n"; + ProjectionViewer viewer= createScrolledViewerWithCollapsedRegion(shell, content, content.indexOf(longLine), longLine); + StyledText textWidget= viewer.getTextWidget(); + int horizontalPixel= textWidget.getHorizontalPixel(); + assertTrue(horizontalPixel > 0, "viewer must be scrolled horizontally"); + viewer.reinitializeProjection(); + assertEquals(horizontalPixel, textWidget.getHorizontalPixel()); + } finally { + shell.dispose(); + } + } + + @Test + void testChangingManyProjectionAnnotationsKeepsHorizontalScrollPosition() { + Shell shell= new Shell(Display.getCurrent()); + try { + StringBuilder builder= new StringBuilder("folded\nhidden\n"); + for (int i= 0; i < 20; i++) { + builder.append("block").append(i).append("\nbody\n"); + } + String longLine= "x".repeat(500); + String content= builder.append(longLine).append('\n').toString(); + ProjectionViewer viewer= createScrolledViewerWithCollapsedRegion(shell, content, content.indexOf("block0"), longLine); + StyledText textWidget= viewer.getTextWidget(); + int horizontalPixel= textWidget.getHorizontalPixel(); + assertTrue(horizontalPixel > 0, "viewer must be scrolled horizontally"); + // enough annotation changes for the viewer to disable the redraw while applying them + Map additions= new HashMap<>(); + for (int i= 0; i < 20; i++) { + int start= content.indexOf("block" + i + "\n"); + additions.put(new ProjectionAnnotation(), new Position(start, content.indexOf('\n', content.indexOf("body", start)) + 1 - start)); + } + viewer.getProjectionAnnotationModel().modifyAnnotations(null, additions, null); + assertEquals(horizontalPixel, textWidget.getHorizontalPixel()); + } finally { + shell.dispose(); + } + } + + /** + * Creates a viewer whose content starts with a collapsed region and scrolls it to the end of + * the given long line. + */ + private ProjectionViewer createScrolledViewerWithCollapsedRegion(Shell shell, String content, int collapsedRegionLength, String longLine) { + shell.setLayout(new FillLayout()); + shell.setSize(200, 200); + ProjectionViewer viewer= new ProjectionViewer(shell, null, null, false, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); + viewer.setDocument(new Document(content), new AnnotationModel()); + viewer.enableProjection(); + ProjectionAnnotation annotation= new ProjectionAnnotation(); + viewer.getProjectionAnnotationModel().addAnnotation(annotation, new Position(0, collapsedRegionLength)); + viewer.getProjectionAnnotationModel().collapse(annotation); + shell.open(); + int endOfLongLine= content.indexOf(longLine) + longLine.length(); + viewer.setSelectedRange(endOfLongLine, 0); + viewer.revealRange(endOfLongLine, 0); + return viewer; + } } diff --git a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextViewerTest.java b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextViewerTest.java index e38f6aa4335..7f01c576fb9 100644 --- a/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextViewerTest.java +++ b/tests/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextViewerTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014, 2025 Google, Inc and others. + * Copyright (c) 2014, 2026 Google, Inc and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -435,6 +435,42 @@ public void testSetSelectionNoDoc() { // assert no exception is thrown } + @Test + public void testSetRedrawKeepsHorizontalScrollPosition() { + TextViewer textViewer= createViewerScrolledToEndOfLongLine(); + StyledText textWidget= textViewer.getTextWidget(); + int horizontalPixel= textWidget.getHorizontalPixel(); + assertTrue(horizontalPixel > 0, "viewer must be scrolled horizontally"); + textViewer.setRedraw(false); + textViewer.setRedraw(true); + assertEquals(horizontalPixel, textWidget.getHorizontalPixel()); + } + + @Test + public void testSetRedrawRevealsSelectionSetWhileRedrawDisabled() { + TextViewer textViewer= createViewerScrolledToEndOfLongLine(); + StyledText textWidget= textViewer.getTextWidget(); + assertTrue(textWidget.getHorizontalPixel() > 0, "viewer must be scrolled horizontally"); + textViewer.setRedraw(false); + textViewer.setSelectedRange(textViewer.getDocument().get().indexOf('x'), 0); + textViewer.setRedraw(true); + assertEquals(0, textWidget.getHorizontalPixel()); + } + + private TextViewer createViewerScrolledToEndOfLongLine() { + fShell.setLayout(new FillLayout()); + fShell.setSize(200, 200); + TextViewer textViewer= new TextViewer(fShell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); + String longLine= "x".repeat(500); + String content= "short\n" + longLine + "\nshort"; + textViewer.setDocument(new Document(content)); + fShell.open(); + int endOfLongLine= content.indexOf(longLine) + longLine.length(); + textViewer.setSelectedRange(endOfLongLine, 0); + textViewer.revealRange(endOfLongLine, 0); + return textViewer; + } + @Test public void testSelectionFromViewerState() { TextViewer textViewer= new TextViewer(fShell, SWT.NONE);