diff --git a/debug/org.eclipse.debug.core/core/org/eclipse/debug/internal/core/OutputStreamMonitor.java b/debug/org.eclipse.debug.core/core/org/eclipse/debug/internal/core/OutputStreamMonitor.java index 539904be753..c695ce0209a 100644 --- a/debug/org.eclipse.debug.core/core/org/eclipse/debug/internal/core/OutputStreamMonitor.java +++ b/debug/org.eclipse.debug.core/core/org/eclipse/debug/internal/core/OutputStreamMonitor.java @@ -70,7 +70,9 @@ public class OutputStreamMonitor implements IBinaryStreamMonitor { * of an incomplete character. */ private StreamDecoder fBufferedDecoder; + /** Decoded form of the first {@link #fDecodedLength} bytes of {@link #fContents}. */ private String fCachedDecodedContents; + private int fDecodedLength; /** * The thread which reads from the stream @@ -193,11 +195,12 @@ public synchronized String getContents() { if (!isBuffered()) { return ""; //$NON-NLS-1$ } - if (fCachedDecodedContents != null) { - return fCachedDecodedContents; + if (fDecodedLength < fContents.size()) { + // decode only the bytes not yet fed to the stateful decoder + byte[] data = getData(); + fCachedDecodedContents += fBufferedDecoder.decode(data, fDecodedLength, data.length - fDecodedLength); + fDecodedLength = data.length; } - byte[] data = getData(); - fCachedDecodedContents = fBufferedDecoder.decode(data, 0, data.length); return fCachedDecodedContents; } @@ -236,7 +239,6 @@ private void internalRead() { if (read > 0) { synchronized (this) { if (isBuffered()) { - fCachedDecodedContents = null; fContents.write(buffer, 0, read); } fireStreamAppended(buffer, 0, read); @@ -306,7 +308,8 @@ protected void startMonitoring(String name) { @Override public synchronized void setBuffered(boolean buffer) { if (isBuffered() != buffer) { - fCachedDecodedContents = null; + fCachedDecodedContents = ""; //$NON-NLS-1$ + fDecodedLength = 0; if (buffer) { fContents = new ByteArrayOutputStream(); fBufferedDecoder = new StreamDecoder(fCharset == null ? Charset.defaultCharset() : fCharset); @@ -320,7 +323,8 @@ public synchronized void setBuffered(boolean buffer) { @Override public synchronized void flushContents() { if (isBuffered()) { - fCachedDecodedContents = null; + fCachedDecodedContents = ""; //$NON-NLS-1$ + fDecodedLength = 0; fContents.reset(); } } diff --git a/debug/org.eclipse.debug.tests/META-INF/MANIFEST.MF b/debug/org.eclipse.debug.tests/META-INF/MANIFEST.MF index c283c3ad37f..f1238f1da7d 100644 --- a/debug/org.eclipse.debug.tests/META-INF/MANIFEST.MF +++ b/debug/org.eclipse.debug.tests/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.debug.tests;singleton:=true -Bundle-Version: 3.15.400.qualifier +Bundle-Version: 3.15.500.qualifier Bundle-Localization: plugin Require-Bundle: org.eclipse.ui;bundle-version="[3.208.0,4.0.0)", org.eclipse.core.runtime;bundle-version="[3.34.0,4.0.0)", diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/AutomatedSuite.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/AutomatedSuite.java index 9ca4736a1db..65fb5b9eb05 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/AutomatedSuite.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/AutomatedSuite.java @@ -22,6 +22,7 @@ import org.eclipse.debug.tests.console.ConsoleManagerTests; import org.eclipse.debug.tests.console.ConsoleOutputLineTruncateTest; import org.eclipse.debug.tests.console.ConsoleOutputLineWrapTest; +import org.eclipse.debug.tests.console.ConsolePatternMatcherTests; import org.eclipse.debug.tests.console.ConsoleShowHideTests; import org.eclipse.debug.tests.console.ConsoleTests; import org.eclipse.debug.tests.console.FileLinkTests; @@ -33,7 +34,7 @@ import org.eclipse.debug.tests.console.ProcessConsoleTests; import org.eclipse.debug.tests.console.RuntimeProcessTests; import org.eclipse.debug.tests.console.StreamsProxyTests; -import org.eclipse.debug.tests.console.TextConsoleViewerTest; +import org.eclipse.debug.tests.console.StyleRangeUtilTest; import org.eclipse.debug.tests.launching.AcceleratorSubstitutionTests; import org.eclipse.debug.tests.launching.ArgumentParsingTests; import org.eclipse.debug.tests.launching.LaunchConfigurationTests; @@ -127,11 +128,12 @@ IOConsoleTests.class, // ConsoleOutputLineWrapTest.class, // ConsoleOutputLineTruncateTest.class, // + ConsolePatternMatcherTests.class, // IOConsoleFixedWidthTests.class, // ProcessConsoleManagerTests.class, // ProcessConsoleTests.class, // StreamsProxyTests.class, // - TextConsoleViewerTest.class, // + StyleRangeUtilTest.class, // RuntimeProcessTests.class, // OutputStreamMonitorTests.class, // InputStreamMonitorTests.class, // diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ConsolePatternMatcherTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ConsolePatternMatcherTests.java new file mode 100644 index 00000000000..6c86de8d96d --- /dev/null +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ConsolePatternMatcherTests.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2026 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.debug.tests.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.debug.tests.DebugTestExtension; +import org.eclipse.ui.console.IOConsole; +import org.eclipse.ui.console.IPatternMatchListener; +import org.eclipse.ui.console.PatternMatchEvent; +import org.eclipse.ui.console.TextConsole; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +/** + * Tests {@code ConsolePatternMatcher} pattern matching on console text that + * contains ANSI escape sequences. + *

+ * Patterns are matched against the text with the escape sequences removed and + * the reported {@link PatternMatchEvent} range is mapped back to the raw + * document. The range must cover exactly the matched text plus any escape + * sequences located inside the match. Escape sequences before or after the + * match must not be part of the range, otherwise listeners that trim the + * reported range would trim an invisible escape character instead of the + * visible one. + *

+ */ +@ExtendWith(DebugTestExtension.class) +public class ConsolePatternMatcherTests { + + private static final String FILE_LINK_PATTERN = "\\([^\\s]*\\.java:\\d+\\)"; //$NON-NLS-1$ + + private IOConsole console; + + @BeforeEach + public void setUp() { + console = new IOConsole("ConsolePatternMatcherTests", "test", null); //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Test + public void testFileLinkWithTrailingEscape() throws Exception { + String text = "\tat org.example.Demo.main(Demo.java:10)\u001b[0m\n"; //$NON-NLS-1$ + PatternMatchEvent event = match(text); + assertMatch(text, event, "(Demo.java:10)"); //$NON-NLS-1$ + } + + @Test + public void testFileLinkWithInternalEscapes() throws Exception { + String text = "\tat org.example.Demo.main(\u001b[1mDemo.java:10\u001b[m)\n"; //$NON-NLS-1$ + PatternMatchEvent event = match(text); + assertMatch(text, event, "(\u001b[1mDemo.java:10\u001b[m)"); //$NON-NLS-1$ + } + + @Test + public void testFileLinkWithLeadingEscape() throws Exception { + String text = "\tat org.example.Demo.main \u001b[1m(Demo.java:10)\n"; //$NON-NLS-1$ + PatternMatchEvent event = match(text); + assertMatch(text, event, "(Demo.java:10)"); //$NON-NLS-1$ + } + + @Test + public void testFileLinkWithoutEscapes() throws Exception { + String text = "\tat org.example.Demo.main(Demo.java:10)\n"; //$NON-NLS-1$ + PatternMatchEvent event = match(text); + assertMatch(text, event, "(Demo.java:10)"); //$NON-NLS-1$ + } + + @Test + public void testMultipleFileLinksWithEscapes() throws Exception { + String text = "\u001b[31mCaused by: java.lang.NullPointerException\u001b[m\n" //$NON-NLS-1$ + + "\tat org.example.Demo.main(\u001b[1mDemo.java:10\u001b[m)\n" //$NON-NLS-1$ + + "\tat org.example.Other.run(\u001b[1mOther.java:42\u001b[m)\n"; //$NON-NLS-1$ + List events = matchAll(text); + assertEquals(2, events.size()); + assertMatch(text, events.get(0), "(\u001b[1mDemo.java:10\u001b[m)"); //$NON-NLS-1$ + assertMatch(text, events.get(1), "(\u001b[1mOther.java:42\u001b[m)"); //$NON-NLS-1$ + } + + private PatternMatchEvent match(String text) throws Exception { + List events = matchAll(text); + assertEquals(1, events.size(), () -> "expected exactly one match in: " + text); //$NON-NLS-1$ + return events.get(0); + } + + private List matchAll(String text) throws Exception { + List events = new CopyOnWriteArrayList<>(); + console.addPatternMatchListener(new CollectingMatchListener(events)); + console.getDocument().set(text); + // the match job family is the console itself + Job.getJobManager().join(console, null); + return events; + } + + private static void assertMatch(String text, PatternMatchEvent event, String rawMatch) { + assertEquals(text.indexOf(rawMatch), event.getOffset(), rawMatch); + assertEquals(rawMatch.length(), event.getLength(), rawMatch); + } + + private static final class CollectingMatchListener implements IPatternMatchListener { + + private final List events; + + CollectingMatchListener(List events) { + this.events = events; + } + + @Override + public void connect(TextConsole console) { + // nothing to do + } + + @Override + public void disconnect() { + // nothing to do + } + + @Override + public void matchFound(PatternMatchEvent event) { + events.add(event); + } + + @Override + public String getPattern() { + return FILE_LINK_PATTERN; + } + + @Override + public int getCompilerFlags() { + return 0; + } + + @Override + public String getLineQualifier() { + return null; + } + } +} diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java index 639d5b5df07..57f5ada50e1 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java @@ -169,6 +169,30 @@ public void testBufferedOutputStreamMonitor() throws Exception { binaryListener.assertNoExceptions(); } + /** + * A multibyte character split across two reads must not be corrupted when + * getContents() is called after each read without flushing in between. + */ + @Test + public void testBufferedContentsWithSplitCharacterAndNoFlush() throws Exception { + String input = "o\u00F6O"; + byte[] byteInput = input.getBytes(StandardCharsets.UTF_8); + BinaryListener binaryListener = new BinaryListener(); + monitor.addBinaryListener(binaryListener); + + sysout.write(byteInput, 0, 2); + sysout.flush(); + monitor.startMonitoring(); + binaryListener.waitForBytes(2); + assertThat(monitor.getContents()).isEqualTo(input.substring(0, 1)); + + sysout.write(byteInput, 2, byteInput.length - 2); + sysout.flush(); + binaryListener.waitForBytes(byteInput.length); + assertThat(monitor.getContents()).isEqualTo(input); + binaryListener.assertNoExceptions(); + } + /** * Simple test for output stream monitor. Test listeners without buffering. */ diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java index ce480ec3ef8..b8b55eb98eb 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java @@ -619,6 +619,71 @@ public void testInputFromFileSendsEof() throws Exception { assertThat(receivedInput).as("received input").isEqualTo(input); } + /** + * Test that a process reads its standard input from a file set on its launch + * when it has no launch configuration. + */ + @Test + public void testInputFromLaunchAttribute() throws Exception { + byte[] input = "from launch\n".getBytes(StandardCharsets.US_ASCII); + String consoleEncoding = StandardCharsets.UTF_8.name(); + + final File inFile = createTmpFile("testinput-launch.txt"); + Files.write(inFile.toPath(), input); + final MockProcess mockProcess = new MockProcess(MockProcess.RUN_FOREVER); + try { + final IProcess process = mockProcess.toRuntimeProcess("inputFromLaunch"); + process.getLaunch().setAttribute(IDebugUIConstants.ATTR_CAPTURE_STDIN_FILE, inFile.getCanonicalPath()); + final ProcessConsole console = new ProcessConsole(process, new ConsoleColorProvider(), consoleEncoding); + try { + console.initialize(); + waitWhile(() -> !mockProcess.isStdinClosed(), () -> "Process stdin was not closed after input file was read."); + } finally { + console.destroy(); + } + } finally { + mockProcess.destroy(); + } + + assertThat(mockProcess.getReceivedInput()).as("received input").isEqualTo(input); + } + + /** + * Test that an input file set on the launch is supplied instead of the input + * file of its launch configuration. + */ + @Test + public void testInputFromLaunchAttributeOverridesConfiguration() throws Exception { + byte[] launchInput = "from launch\n".getBytes(StandardCharsets.US_ASCII); + byte[] configurationInput = "from configuration\n".getBytes(StandardCharsets.US_ASCII); + String consoleEncoding = StandardCharsets.UTF_8.name(); + + final File launchFile = createTmpFile("testinput-launch.txt"); + Files.write(launchFile.toPath(), launchInput); + final File configurationFile = createTmpFile("testinput-configuration.txt"); + Files.write(configurationFile.toPath(), configurationInput); + final MockProcess mockProcess = new MockProcess(MockProcess.RUN_FOREVER); + try { + Map launchConfigAttributes = new HashMap<>(); + launchConfigAttributes.put(DebugPlugin.ATTR_CONSOLE_ENCODING, consoleEncoding); + launchConfigAttributes.put(IDebugUIConstants.ATTR_CAPTURE_STDIN_FILE, configurationFile.getCanonicalPath()); + launchConfigAttributes.put(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, false); + final IProcess process = mockProcess.toRuntimeProcess("inputFromLaunchOverride", launchConfigAttributes); + process.getLaunch().setAttribute(IDebugUIConstants.ATTR_CAPTURE_STDIN_FILE, launchFile.getCanonicalPath()); + final ProcessConsole console = new ProcessConsole(process, new ConsoleColorProvider(), consoleEncoding); + try { + console.initialize(); + waitWhile(() -> !mockProcess.isStdinClosed(), () -> "Process stdin was not closed after input file was read."); + } finally { + console.destroy(); + } + } finally { + mockProcess.destroy(); + } + + assertThat(mockProcess.getReceivedInput()).as("received input").isEqualTo(launchInput); + } + /** * Test that console name updates (elapsed time) only happen for visible * consoles. Hidden consoles should not update their name. When a hidden diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/TextConsoleViewerTest.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/StyleRangeUtilTest.java similarity index 96% rename from debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/TextConsoleViewerTest.java rename to debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/StyleRangeUtilTest.java index ad4d6c0ad1a..f90a62fe089 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/TextConsoleViewerTest.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/StyleRangeUtilTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019 Paul Pazderski and others. + * Copyright (c) 2019, 2026 Paul Pazderski and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -25,16 +25,15 @@ import org.eclipse.debug.tests.DebugTestExtension; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.graphics.Color; -import org.eclipse.ui.console.TextConsoleViewer; +import org.eclipse.ui.internal.console.StyleRangeUtil; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; /** - * Not really a test for {@link TextConsoleViewer} yet since it only test one - * private method of it. + * Test for the style range override helper in {@link StyleRangeUtil}. */ @ExtendWith(DebugTestExtension.class) -public class TextConsoleViewerTest { +public class StyleRangeUtilTest { /** * Test override of existing styles with a new style. Typically used to @@ -48,7 +47,7 @@ public void testStyleOverride() throws Throwable { Color colorK = null; Color colorW = null; try { - final Method method = TextConsoleViewer.class.getDeclaredMethod("overrideStyleRange", List.class, StyleRange.class); + final Method method = StyleRangeUtil.class.getDeclaredMethod("overrideStyleRange", List.class, StyleRange.class); method.setAccessible(true); assertTrue(Modifier.isStatic(method.getModifiers()), "Required method <\" + method + \"> is not static.\""); diff --git a/debug/org.eclipse.debug.ui/META-INF/MANIFEST.MF b/debug/org.eclipse.debug.ui/META-INF/MANIFEST.MF index 7450db8d962..de3ee2b89c7 100644 --- a/debug/org.eclipse.debug.ui/META-INF/MANIFEST.MF +++ b/debug/org.eclipse.debug.ui/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.debug.ui; singleton:=true -Bundle-Version: 3.22.100.qualifier +Bundle-Version: 3.23.0.qualifier Bundle-Activator: org.eclipse.debug.internal.ui.DebugUIPlugin Bundle-Vendor: %providerName Bundle-Localization: plugin diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/LaunchShortcutAction.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/LaunchShortcutAction.java index b509f23e126..64d205df8a5 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/LaunchShortcutAction.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/LaunchShortcutAction.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 @@ -25,10 +25,12 @@ import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; +import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.internal.ui.DebugUIPlugin; import org.eclipse.debug.internal.ui.TerminateToggleValue; import org.eclipse.debug.internal.ui.contextlaunching.LaunchingResourceManager; import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationManager; +import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationsMessages; import org.eclipse.debug.internal.ui.launchConfigurations.LaunchShortcutExtension; import org.eclipse.debug.internal.ui.stringsubstitution.SelectedResourceManager; import org.eclipse.debug.ui.DebugUITools; @@ -50,7 +52,6 @@ public class LaunchShortcutAction extends Action { private final LaunchShortcutExtension fShortcut; private ILaunchConfiguration configuration; - /** * @param mode the mode to launch in * @param shortcut the underlying shortcut @@ -104,46 +105,95 @@ private void runInternal(boolean isShift) { @Override public void runWithEvent(Event event) { if ((event.stateMask & SWT.MOD1) > 0) { - Set types = fShortcut.getAssociatedConfigurationTypes(); - if(!types.isEmpty()) { - LaunchingResourceManager lrm = DebugUIPlugin.getDefault().getLaunchingResourceManager(); - IStructuredSelection selection = SelectedResourceManager.getDefault().getCurrentSelection(); - ArrayList shortcuts = new ArrayList<>(); - shortcuts.add(fShortcut); - IResource resource = SelectedResourceManager.getDefault().getSelectedResource(); - if(resource == null) { - resource = lrm.getLaunchableResource(shortcuts, selection); - } - List configs = lrm.getParticipatingLaunchConfigurations(selection, resource, shortcuts, fMode); - LaunchConfigurationManager lcm = DebugUIPlugin.getDefault().getLaunchConfigurationManager(); - ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType((String) types.toArray()[0]); - String groupid = null; - ILaunchGroup group = lcm.getLaunchGroup(type, fMode); - if(group != null) { - groupid = group.getIdentifier(); - } - ILaunchConfiguration config = lcm.getMRUConfiguration(configs, group, resource); - if(config == null) { - if(configs.size() > 0) { - config = configs.get(0); + openConfigurationDialog(); + } + else { + runInternal(((event.stateMask & SWT.SHIFT) > 0) ? true : false); + } + } + + private void openConfigurationDialog() { + Set types = fShortcut.getAssociatedConfigurationTypes(); + if (!types.isEmpty()) { + LaunchingResourceManager lrm = DebugUIPlugin.getDefault().getLaunchingResourceManager(); + IStructuredSelection selection = SelectedResourceManager.getDefault().getCurrentSelection(); + ArrayList shortcuts = new ArrayList<>(); + shortcuts.add(fShortcut); + IResource resource = SelectedResourceManager.getDefault().getSelectedResource(); + if (resource == null) { + resource = lrm.getLaunchableResource(shortcuts, selection); + } + List configs = lrm.getParticipatingLaunchConfigurations(selection, resource, + shortcuts, fMode); + LaunchConfigurationManager lcm = DebugUIPlugin.getDefault().getLaunchConfigurationManager(); + // Keep only configs whose type belongs to this shortcut + List ownedConfigs = new ArrayList<>(); + try { + for (ILaunchConfiguration c : configs) { + if (types.contains(c.getType().getIdentifier())) { + ownedConfigs.add(c); } } - if(config != null) { - selection = new StructuredSelection(config); - } - else { - if(type != null) { - selection = new StructuredSelection(type); + } catch (CoreException e) { + DebugUIPlugin.log(e); + return; + } + ILaunchConfiguration config = null; + ILaunchConfigurationType type = null; + try { + if (!ownedConfigs.isEmpty()) { + ILaunchGroup mruGroup = lcm.getLaunchGroup(ownedConfigs.get(0).getType(), fMode); + config = lcm.getMRUConfiguration(ownedConfigs, mruGroup, resource); + if (config == null) { + config = ownedConfigs.get(0); + } + type = config.getType(); + } else { + // No existing config: pick the first type this shortcut declares + // that supports the current mode. Shortcuts virtually always declare + // exactly one type, so no disambiguation dialog is needed. + for (String id : types) { + ILaunchConfigurationType candidate = DebugPlugin.getDefault().getLaunchManager() + .getLaunchConfigurationType(id); + if (candidate != null && candidate.supportsMode(fMode)) { + type = candidate; + break; + } + } + if (type == null) { + return; } } - DebugUITools.openLaunchConfigurationDialogOnGroup(DebugUIPlugin.getShell(), selection, groupid); + } catch (CoreException e) { + DebugUIPlugin.log(e); + return; } - else { - run(); + String groupid = null; + ILaunchGroup group = lcm.getLaunchGroup(type, fMode); + if (group != null) { + groupid = group.getIdentifier(); } - } - else { - runInternal(((event.stateMask & SWT.SHIFT) > 0) ? true : false); + if (config == null) { + try { + String baseName = resource != null + ? resource.getFullPath().removeFileExtension().lastSegment() : null; + if (baseName == null || baseName.isEmpty()) { + baseName = LaunchConfigurationsMessages.CreateLaunchConfigurationAction_New_configuration_2; + } + String name = DebugPlugin.getDefault().getLaunchManager() + .generateLaunchConfigurationName(baseName); + ILaunchConfigurationWorkingCopy wc = type.newInstance(null, name); + DebugUIPlugin.openLaunchConfigurationsDialog(DebugUIPlugin.getShell(), + new StructuredSelection(wc), groupid, true); + } catch (CoreException e) { + DebugUIPlugin.log(e); + } + return; + } + selection = new StructuredSelection(config); + DebugUITools.openLaunchConfigurationDialogOnGroup(DebugUIPlugin.getShell(), selection, groupid); + } else { + run(); } } diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/expressions/WatchExpressionDialog.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/expressions/WatchExpressionDialog.java index 695c96550e7..3efeafbc1d3 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/expressions/WatchExpressionDialog.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/actions/expressions/WatchExpressionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 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,15 @@ import java.text.MessageFormat; +import java.util.Optional; +import org.eclipse.core.runtime.Adapters; import org.eclipse.debug.core.model.IWatchExpression; import org.eclipse.debug.internal.ui.IDebugHelpContextIds; import org.eclipse.debug.internal.ui.actions.ActionMessages; import org.eclipse.debug.internal.ui.actions.StatusInfo; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.IWatchExpressionCellEditorFactory; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.bindings.keys.IKeyLookup; import org.eclipse.jface.bindings.keys.KeyLookupFactory; @@ -103,10 +107,18 @@ protected Control createDialogArea(Composite parent) { label.setFont(font); fSnippetViewer = new SourceViewer(container, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.LEFT_TO_RIGHT); - fSnippetViewer.setInput(this); IDocument document = new Document(); - fSnippetViewer.configure(new SourceViewerConfiguration()); + Optional factory = getFactory(); + if (factory.isPresent()) { + IWatchExpressionCellEditorFactory f = factory.get(); + f.prepareDocument(document); + fSnippetViewer.setInput(document); + f.configureSourceViewer(fSnippetViewer); + } else { + fSnippetViewer.setInput(this); + fSnippetViewer.configure(new SourceViewerConfiguration()); + } fSnippetViewer.setEditable(true); fSnippetViewer.setDocument(document); document.addDocumentListener(new IDocumentListener() { @@ -207,4 +219,12 @@ private void checkValues() { updateStatus(status); } + /** + * Returns an {@link Optional} containing the {@link IWatchExpressionCellEditorFactory} + * from the active debug context, or an empty {@link Optional} if none is available. + */ + private Optional getFactory() { + return Optional.ofNullable(Adapters.adapt(DebugUITools.getDebugContext(), IWatchExpressionCellEditorFactory.class)); + } + } diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/importexport/breakpoints/EmbeddedBreakpointsViewer.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/importexport/breakpoints/EmbeddedBreakpointsViewer.java index def1d69f1e5..6eee4579db6 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/importexport/breakpoints/EmbeddedBreakpointsViewer.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/importexport/breakpoints/EmbeddedBreakpointsViewer.java @@ -16,7 +16,9 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.Vector; import org.eclipse.core.runtime.Assert; @@ -66,8 +68,11 @@ public class EmbeddedBreakpointsViewer { private BreakpointsContentProvider fProvider = null; private Tree fTree = null; private BreakpointsViewer fViewer = null; - private final ICheckStateListener fCheckListener = event -> updateCheckedState(event.getElement(), - event.getChecked()); + private final Set fCheckedBreakpoints = new HashSet<>(); + private final ICheckStateListener fCheckListener = event -> { + updateCheckedState(event.getElement(), event.getChecked()); + updateCheckedBreakpointsSet(event.getElement(), event.getChecked()); + }; private Text filterText; private BreakpointPatternFilter fFilter; @@ -119,6 +124,7 @@ private void createControl(Composite parent, Object input, IStructuredSelection filterText.addModifyListener(e -> { fFilter.setPattern(filterText.getText()); fViewer.refresh(); + restoreCheckedState(); }); BreakpointsLabelProvider labelprovider = new BreakpointsLabelProvider(); if(view != null) { @@ -178,6 +184,7 @@ public boolean select(Viewer viewer, Object parentElement, Object element) { private void initViewerState() { fViewer.setGrayedElements(); fViewer.setCheckedElements(new Object[] {}); + fCheckedBreakpoints.clear(); ArrayList list = new ArrayList<>(); for (Object item : fSelection.toArray()) { IBreakpoint breakpoint = (IBreakpoint)DebugPlugin.getAdapter(item, IBreakpoint.class); @@ -190,6 +197,49 @@ else if (item instanceof IBreakpointContainer) { } for (IBreakpoint element : list) { updateCheckedState(element, true); + fCheckedBreakpoints.add(element); + } + } + + /** + * Updates the tracked set of checked breakpoints when the user changes check state. + */ + private void updateCheckedBreakpointsSet(Object obj, boolean checked) { + IBreakpoint breakpoint = (IBreakpoint) DebugPlugin.getAdapter(obj, IBreakpoint.class); + if (breakpoint != null) { + if (checked) { + fCheckedBreakpoints.add(breakpoint); + } else { + fCheckedBreakpoints.remove(breakpoint); + } + } else if (obj instanceof IBreakpointContainer container) { + for (IBreakpoint bp : container.getBreakpoints()) { + if (checked) { + fCheckedBreakpoints.add(bp); + } else { + fCheckedBreakpoints.remove(bp); + } + } + } + } + + /** + * Restores the checked state from the tracked set after a viewer refresh. + */ + private void restoreCheckedState() { + for (TreeItem root : fTree.getItems()) { + uncheckAll(root); + } + for (IBreakpoint bp : fCheckedBreakpoints) { + updateCheckedState(bp, true); + } + } + + private void uncheckAll(TreeItem item) { + item.setChecked(false); + item.setGrayed(false); + for (TreeItem child : item.getItems()) { + uncheckAll(child); } } diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/launchConfigurations/LaunchConfigurationsDialog.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/launchConfigurations/LaunchConfigurationsDialog.java index a5386fae947..cebb77e32d5 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/launchConfigurations/LaunchConfigurationsDialog.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/launchConfigurations/LaunchConfigurationsDialog.java @@ -253,6 +253,23 @@ public static void setCurrentlyVisibleLaunchConfigurationDialog(ILaunchConfigura */ private boolean fSettingInput = false; + /** + * Set while an unsaved-changes prompt triggered by a tree selection change is + * pending or showing + */ + private boolean fHandlingSelectionChange; + + /** + * Whether a mouse button is currently pressed in the launch configuration tree. + */ + private boolean fTreeMouseDown; + + /** + * Work to run as soon as the mouse button is released in the launch + * configuration tree. + */ + private Runnable fRunAfterTreeMouseUp; + /** * Constructs a new launch configuration dialog on the given * parent shell. @@ -608,6 +625,14 @@ else if(status == IDialogConstants.NO_ID) { getLinkPrototypeAction().setConfirmationRequestor(requestor); getUnlinkPrototypeAction().setConfirmationRequestor(requestor); getResetWithPrototypeValuesAction().setConfirmationRequestor(requestor); + viewer.getControl().addListener(SWT.MouseDown, e -> { + // a new press means a pending prompt must not wait for a release we never saw + listenerAction(e); + }); + viewer.getControl().addListener(SWT.MouseUp, e -> { + fTreeMouseDown = false; + listenerAction(e); + }); ((StructuredViewer) viewer).addPostSelectionChangedListener(event -> { handleLaunchConfigurationSelectionChanged(event); getNewAction().setEnabled(getNewAction().isEnabled()); @@ -622,6 +647,15 @@ else if(status == IDialogConstants.NO_ID) { return comp; } + private void listenerAction(Event e) { + Runnable pending = fRunAfterTreeMouseUp; + fRunAfterTreeMouseUp = null; + if (pending != null) { + e.display.asyncExec(pending); + } + fTreeMouseDown = true; + } + /** * Create the filters to be initially applied to the viewer. * The initial filters are based on the persisted preferences @@ -1018,12 +1052,13 @@ protected void handleClosePressed() { * @param event selection changed event */ protected void handleLaunchConfigurationSelectionChanged(SelectionChangedEvent event) { + if (fHandlingSelectionChange) { + // a prompt for the previous change is pending/showing, or we are restoring the old selection + return; + } Object input = fTabViewer.getInput(); - Object newInput = null; IStructuredSelection selection = event.getStructuredSelection(); - if (selection.size() == 1) { - newInput = selection.getFirstElement(); - } + Object newInput = selection.size() == 1 ? selection.getFirstElement() : null; if (!isEqual(input, newInput)) { ILaunchConfiguration original = fTabViewer.getOriginal(); if (original != null && newInput == null && getLaunchManager().getMovedTo(original) != null) { @@ -1037,49 +1072,86 @@ protected void handleLaunchConfigurationSelectionChanged(SelectionChangedEvent e if (newInput instanceof ILaunchConfiguration) { renamed = getLaunchManager().getMovedFrom((ILaunchConfiguration)newInput) != null; } - try { - fSettingInput = true; - if (fTabViewer.canSave() && fTabViewer.isDirty() && !deleted && !renamed) { - if(fLaunchConfigurationView != null) { - fLaunchConfigurationView.setAutoSelect(false); - } - int ret = showUnsavedChangesDialog(); - if(ret == IDialogConstants.YES_ID) { - fTabViewer.handleApplyPressed(); - ILaunchConfigurationTab[] tabs = getTabs(); - if (tabs != null) { - for (ILaunchConfigurationTab tab : tabs) { - tab.postApply(); - } + if (fTabViewer.canSave() && fTabViewer.isDirty() && !deleted && !renamed) { + fHandlingSelectionChange = true; + Runnable prompt = () -> { + try { + Shell shell = getShell(); + if (shell != null && !shell.isDisposed()) { + promptAndSwitchInput(input, newInput); } - fTabViewer.setInput(newInput); - } - else if(ret == IDialogConstants.NO_ID) { - fTabViewer.handleRevertPressed(); - fTabViewer.setInput(newInput); + } finally { + fHandlingSelectionChange = false; } - else { - fLaunchConfigurationView.getViewer().setSelection(new StructuredSelection(input)); - } - fLaunchConfigurationView.setAutoSelect(true); + }; + if (fTreeMouseDown) { + fRunAfterTreeMouseUp = prompt; + } else { + prompt.run(); } - else { - fTabViewer.setInput(newInput); - if(fTabViewer.isDirty()) { - fTabViewer.handleApplyPressed(); - } + return; + } + try { + fSettingInput = true; + fTabViewer.setInput(newInput); + if(fTabViewer.isDirty()) { + fTabViewer.handleApplyPressed(); } } finally { fSettingInput = false; updateButtons(); updateMessage(); } - if(getShell() != null && getShell().isVisible()) { + Shell shell = getShell(); + if (shell != null && shell.isVisible()) { resize(); } } } + /** + * Asks how to handle unsaved changes before switching inputs, or restores the + * selection if cancelled. + * + * @param oldInput input currently shown in the tab viewer + * @param newInput newly selected input + */ + private void promptAndSwitchInput(Object oldInput, Object newInput) { + if (fLaunchConfigurationView != null) { + fLaunchConfigurationView.setAutoSelect(false); + } + try { + fSettingInput = true; + int ret = showUnsavedChangesDialog(); + if (ret == IDialogConstants.YES_ID) { + fTabViewer.handleApplyPressed(); + ILaunchConfigurationTab[] tabs = getTabs(); + if (tabs != null) { + for (ILaunchConfigurationTab tab : tabs) { + tab.postApply(); + } + } + fTabViewer.setInput(newInput); + } else if (ret == IDialogConstants.NO_ID) { + fTabViewer.handleRevertPressed(); + fTabViewer.setInput(newInput); + } else if (fLaunchConfigurationView != null && oldInput != null) { + fLaunchConfigurationView.getViewer().setSelection(new StructuredSelection(oldInput), true); + } + } finally { + fSettingInput = false; + if (fLaunchConfigurationView != null) { + fLaunchConfigurationView.setAutoSelect(true); + } + updateButtons(); + updateMessage(); + } + Shell shell = getShell(); + if (shell != null && !shell.isDisposed() && shell.isVisible()) { + resize(); + } + } + /** * Notification the 'launch' button has been pressed. Save and launch. */ diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/ExpressionManagerContentProvider.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/ExpressionManagerContentProvider.java index a789c0cecc2..db61343a592 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/ExpressionManagerContentProvider.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/ExpressionManagerContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2013 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 @@ -14,6 +14,9 @@ *******************************************************************************/ package org.eclipse.debug.internal.ui.model.elements; +import java.util.Optional; + +import org.eclipse.core.runtime.Adapters; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugPlugin; @@ -31,6 +34,7 @@ import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugUIConstants; +import org.eclipse.debug.ui.IWatchExpressionCellEditorFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ICellModifier; @@ -85,7 +89,9 @@ private void updateLabel(ILabelUpdate update, int columnIndex) { @Override public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - return new TextCellEditor(parent); + return Optional.ofNullable(Adapters.adapt(DebugUITools.getDebugContext(), IWatchExpressionCellEditorFactory.class)) + .flatMap(factory -> factory.createCellEditor(parent)) + .orElseGet(() -> new TextCellEditor(parent)); } @Override diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/WatchExpressionEditor.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/WatchExpressionEditor.java index d9b8009c8f0..e301734644b 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/WatchExpressionEditor.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/model/elements/WatchExpressionEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010 Wind River Systems and others. + * Copyright (c) 2010, 2026 Wind River Systems and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -10,16 +10,25 @@ * * Contributors: * Wind River Systems - initial API and implementation + * IBM Corporation - Add content assist support *******************************************************************************/ package org.eclipse.debug.internal.ui.model.elements; +import java.util.Optional; + +import org.eclipse.core.runtime.Adapters; +import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.internal.ui.elements.adapters.WatchExpressionCellModifier; import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor; import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext; +import org.eclipse.debug.ui.DebugUITools; +import org.eclipse.debug.ui.IWatchExpressionCellEditorFactory; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ICellModifier; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchPartSite; /** * @since 3.6 @@ -28,7 +37,9 @@ public class WatchExpressionEditor implements IElementEditor { @Override public CellEditor getCellEditor(IPresentationContext context, String columnId, Object element, Composite parent) { - return new TextCellEditor(parent); + return Optional.ofNullable(Adapters.adapt(getDebugContext(context), IWatchExpressionCellEditorFactory.class)) + .flatMap(factory -> factory.createCellEditor(parent)) + .orElseGet(() -> new TextCellEditor(parent)); } @Override @@ -36,4 +47,19 @@ public ICellModifier getCellModifier(IPresentationContext context, Object elemen return new WatchExpressionCellModifier(); } + /** + * Returns the active debug context associated with the given presentation + * context, or {@code null} if there is none. + */ + private IAdaptable getDebugContext(IPresentationContext context) { + IWorkbenchPart part = context.getPart(); + if (part != null) { + IWorkbenchPartSite site = part.getSite(); + if (site != null) { + return DebugUITools.getPartDebugContext(site); + } + } + return DebugUITools.getDebugContext(); + } + } diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.java index 17ff5e5f2d9..0657315e6a1 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.java @@ -157,6 +157,17 @@ public class DebugPreferencesMessages extends NLS { public static String SimpleVariablePreferencePage_7; public static String SimpleVariablePreferencePage_8; public static String SimpleVariablePreferencePage_9; + public static String SimpleVariablePreferencePage_Preview; + public static String StringVariablePreviewDialog_Title; + public static String StringVariablePreviewDialog_Name; + public static String StringVariablePreviewDialog_Value; + public static String StringVariablePreviewDialog_Description; + public static String StringVariablePreviewDialog_ReadOnly; + public static String StringVariablePreviewDialog_Contributed; + public static String StringVariablePreviewDialog_ContributedBy; + public static String StringVariablePreviewDialog_Yes; + public static String StringVariablePreviewDialog_No; + public static String StringVariablePreviewDialog_Close; public static String SimpleVariablePreferencePage_10; public static String SimpleVariablePreferencePage_11; public static String SimpleVariablePreferencePage_12; diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.properties b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.properties index 164f2766ece..f1ef446d8fa 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.properties +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/DebugPreferencesMessages.properties @@ -132,6 +132,17 @@ SimpleVariablePreferencePage_6=&Create and configure string substitution variabl SimpleVariablePreferencePage_7=&New... SimpleVariablePreferencePage_8=&Edit... SimpleVariablePreferencePage_9=&Remove +SimpleVariablePreferencePage_Preview=&Preview... +StringVariablePreviewDialog_Title=Variable Preview +StringVariablePreviewDialog_Name=Name +StringVariablePreviewDialog_Value=Value +StringVariablePreviewDialog_Description=Description +StringVariablePreviewDialog_ReadOnly=Read-only +StringVariablePreviewDialog_Contributed=Contributed +StringVariablePreviewDialog_ContributedBy=Contributed by +StringVariablePreviewDialog_Yes=Yes +StringVariablePreviewDialog_No=No +StringVariablePreviewDialog_Close=&Close SimpleVariablePreferencePage_10=&Name: SimpleVariablePreferencePage_11=&Value: SimpleVariablePreferencePage_12=&Description: diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreferencePage.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreferencePage.java index 877962313bb..75b83ad430d 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreferencePage.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2018 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 @@ import java.text.MessageFormat; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; @@ -75,6 +74,7 @@ public class StringVariablePreferencePage extends PreferencePage implements IWor protected Button envAddButton; protected Button envEditButton; protected Button envRemoveButton; + private Button envPreviewButton; protected SimpleVariableContentProvider variableContentProvider= new SimpleVariableContentProvider(); @@ -247,6 +247,22 @@ public void widgetSelected(SelectionEvent event) { } }); envRemoveButton.setEnabled(false); + envPreviewButton = SWTFactory.createPushButton(buttonComposite, DebugPreferencesMessages.SimpleVariablePreferencePage_Preview, null); + envPreviewButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handlePreviewButtonPressed(); + } + }); + envPreviewButton.setEnabled(false); + } + + private void handlePreviewButtonPressed() { + IStructuredSelection selection = variableTable.getStructuredSelection(); + if (selection.size() != 1) { + return; + } + new StringVariablePreviewDialog(getShell(), (VariableWrapper) selection.getFirstElement()).open(); } private void handleAddButtonPressed() { @@ -290,9 +306,7 @@ private boolean addVariable(String name, String description, String value) { return false; } List editedVariables = variableContentProvider.getWorkingSetVariables(); - Iterator iter = editedVariables.iterator(); - while (iter.hasNext()) { - VariableWrapper currentVariable = iter.next(); + for (VariableWrapper currentVariable : editedVariables) { if (!currentVariable.isRemoved()) { String currentName = currentVariable.getName(); if (currentName.equals(name)) { @@ -360,9 +374,7 @@ private void handleRemoveButtonPressed() { IStructuredSelection selection = variableTable.getStructuredSelection(); List variablesToRemove = selection.toList(); StringBuilder contributedVariablesToRemove= new StringBuilder(); - Iterator iter = variablesToRemove.iterator(); - while (iter.hasNext()) { - VariableWrapper variable = iter.next(); + for (VariableWrapper variable : variablesToRemove) { if (variable.isContributed()) { contributedVariablesToRemove.append('\t').append(variable.getName()).append('\n'); } @@ -387,6 +399,7 @@ private void handleRemoveButtonPressed() { protected void handleTableSelectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (event.getStructuredSelection()); VariableWrapper variable= (VariableWrapper) selection.getFirstElement(); + envPreviewButton.setEnabled(selection.size() == 1); if (variable == null || variable.isReadOnly()) { envEditButton.setEnabled(false); envRemoveButton.setEnabled(false); @@ -503,11 +516,9 @@ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { */ public void saveChanges() { IStringVariableManager manager = getVariableManager(); - Iterator iterator = fWorkingSet.iterator(); List remove = new ArrayList<>(); List add = new ArrayList<>(); - while (iterator.hasNext()) { - VariableWrapper variable = iterator.next(); + for (VariableWrapper variable : fWorkingSet) { if (!variable.isReadOnly()) { IValueVariable underlyingVariable = variable.getUnderlyingVariable(); if (variable.isRemoved()) { diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreviewDialog.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreviewDialog.java new file mode 100644 index 00000000000..1c0bd873ffc --- /dev/null +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/preferences/StringVariablePreviewDialog.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * 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.debug.internal.ui.preferences; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.variables.VariablesPlugin; +import org.eclipse.debug.internal.ui.preferences.StringVariablePreferencePage.VariableWrapper; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +class StringVariablePreviewDialog extends Dialog { + + private final VariableWrapper fVariable; + + StringVariablePreviewDialog(Shell parentShell, VariableWrapper variable) { + super(parentShell); + fVariable = variable; + setShellStyle(SWT.RESIZE | getShellStyle()); + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(DebugPreferencesMessages.StringVariablePreviewDialog_Title); + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + createButton(parent, IDialogConstants.CANCEL_ID, DebugPreferencesMessages.StringVariablePreviewDialog_Close, + false); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite comp = (Composite) super.createDialogArea(parent); + + StringBuilder text = new StringBuilder(); + List styles = new ArrayList<>(); + appendDetail(text, styles, DebugPreferencesMessages.StringVariablePreviewDialog_Name, fVariable.getName()); + appendDetail(text, styles, DebugPreferencesMessages.StringVariablePreviewDialog_Value, fVariable.getValue()); + appendDetail(text, styles, DebugPreferencesMessages.StringVariablePreviewDialog_Description, + fVariable.getDescription()); + appendDetail(text, styles, DebugPreferencesMessages.StringVariablePreviewDialog_ReadOnly, + yesNo(fVariable.isReadOnly())); + appendDetail(text, styles, DebugPreferencesMessages.StringVariablePreviewDialog_Contributed, + yesNo(fVariable.isContributed())); + if (fVariable.isContributed()) { + appendDetail(text, styles, DebugPreferencesMessages.StringVariablePreviewDialog_ContributedBy, + VariablesPlugin.getDefault().getStringVariableManager() + .getContributingPluginId(fVariable.getUnderlyingVariable())); + } + + StyledText styledText = new StyledText(comp, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY); + GridData gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = convertHeightInCharsToPixels(22); + gd.widthHint = convertWidthInCharsToPixels(120); + styledText.setLayoutData(gd); + styledText.setText(text.toString()); + styledText.setStyleRanges(styles.toArray(new StyleRange[0])); + return comp; + } + + private static String yesNo(boolean flag) { + return flag ? DebugPreferencesMessages.StringVariablePreviewDialog_Yes + : DebugPreferencesMessages.StringVariablePreviewDialog_No; + } + + /** + * Appends a bold title followed by its value on the next line; skipped if the + * value is null. + */ + private static void appendDetail(StringBuilder text, List styles, String title, String value) { + if (value == null) { + return; + } + if (text.length() > 0) { + text.append("\n\n"); //$NON-NLS-1$ + } + styles.add(new StyleRange(text.length(), title.length(), null, null, SWT.BOLD)); + text.append(title).append('\n').append(value); + } +} diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/views/console/ProcessConsole.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/views/console/ProcessConsole.java index 7ae8c565346..55f129d14c7 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/views/console/ProcessConsole.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/internal/ui/views/console/ProcessConsole.java @@ -183,15 +183,21 @@ public ProcessConsole(IProcess process, IConsoleColorProvider colorProvider, Str ILaunchConfiguration configuration = process.getLaunch().getLaunchConfiguration(); String file = null; boolean append = false; - if (configuration != null) { + // an input file set on the launch overrides the one of its configuration + fStdInFile = process.getLaunch().getAttribute(IDebugUIConstants.ATTR_CAPTURE_STDIN_FILE); + if (configuration != null || fStdInFile != null) { try { - file = configuration.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_FILE, (String) null); - fStdInFile = configuration.getAttribute(IDebugUIConstants.ATTR_CAPTURE_STDIN_FILE, (String) null); + if (configuration != null) { + file = configuration.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_FILE, (String) null); + append = configuration.getAttribute(IDebugUIConstants.ATTR_APPEND_TO_FILE, false); + if (fStdInFile == null) { + fStdInFile = configuration.getAttribute(IDebugUIConstants.ATTR_CAPTURE_STDIN_FILE, (String) null); + } + } if (file != null || fStdInFile != null) { IStringVariableManager stringVariableManager = VariablesPlugin.getDefault().getStringVariableManager(); if (file != null) { file = stringVariableManager.performStringSubstitution(file); - append = configuration.getAttribute(IDebugUIConstants.ATTR_APPEND_TO_FILE, false); } if (fStdInFile != null) { @@ -248,7 +254,7 @@ public ProcessConsole(IProcess process, IConsoleColorProvider colorProvider, Str } fFileOutputStream = outputStream; InputStream inputStream = null; - if (fStdInFile != null && configuration != null) { + if (fStdInFile != null) { String message = null; try { inputStream = new FileInputStream(new File(fStdInFile)); diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IDebugUIConstants.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IDebugUIConstants.java index c52ff715bca..cdf2de12416 100644 --- a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IDebugUIConstants.java +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IDebugUIConstants.java @@ -970,6 +970,13 @@ public interface IDebugUIConstants { /** * Launch configuration attribute to specifying a file whose content is supplied * to the launched process input stream. Default value is null. + *

+ * The attribute may also be set on the {@link org.eclipse.debug.core.ILaunch} + * before its processes are created, for example by an + * {@link org.eclipse.debug.core.ILaunchListener} when the launch is added. A + * file set on the launch is supplied instead of the one of its launch + * configuration. + *

* * @since 3.11 */ diff --git a/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IWatchExpressionCellEditorFactory.java b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IWatchExpressionCellEditorFactory.java new file mode 100644 index 00000000000..fbd2b01f08c --- /dev/null +++ b/debug/org.eclipse.debug.ui/ui/org/eclipse/debug/ui/IWatchExpressionCellEditorFactory.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * 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.debug.ui; + +import java.util.Optional; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.source.SourceViewerConfiguration; +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.swt.widgets.Composite; + +/** + * Factory for creating a cell editor with content assist for the Expressions + * view and for configuring the source viewer in the Add/Edit Watch Expression + * dialog. + *

+ * Clients may implement this interface. Debug-context elements that support + * language-aware watch expression editing should adapt to this interface. + *

+ * + * @since 3.23 + */ +public interface IWatchExpressionCellEditorFactory { + + /** + * Creates and returns a new cell editor suitable for editing a watch expression + * in the Expressions view. The returned editor may provide language-specific + * content assist and must use {@link String} as its value type. + * + * @param parent the composite to use as the parent of the cell editor's control + * @return an {@link Optional} containing the cell editor, or an empty {@link Optional} + * if this factory cannot provide one in the current state + */ + Optional createCellEditor(Composite parent); + + /** + * Configures the given source viewer for language-aware editing of a watch + * expression, typically inside the Add/Edit Watch Expression dialog. + * + * @param viewer the source viewer to configure; never {@code null} + * @since 3.23 + */ + default void configureSourceViewer(SourceViewer viewer) { + viewer.configure(new SourceViewerConfiguration()); + } + + /** + * Prepares the given document for language-aware editing + * + * @param document the document to prepare; never {@code null} + * @since 3.23 + */ + default void prepareDocument(IDocument document) { + // nothing by default + } +} diff --git a/debug/org.eclipse.ui.console/src/org/eclipse/ui/console/TextConsoleViewer.java b/debug/org.eclipse.ui.console/src/org/eclipse/ui/console/TextConsoleViewer.java index ef499c1529e..565eed56007 100644 --- a/debug/org.eclipse.ui.console/src/org/eclipse/ui/console/TextConsoleViewer.java +++ b/debug/org.eclipse.ui.console/src/org/eclipse/ui/console/TextConsoleViewer.java @@ -35,6 +35,7 @@ import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.JFaceTextUtil; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.SourceViewer; @@ -65,6 +66,9 @@ import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.internal.console.ConsoleDocumentAdapter; import org.eclipse.ui.internal.console.ConsoleHyperlinkPosition; +import org.eclipse.ui.internal.console.StyleRangeUtil; +import org.eclipse.ui.internal.console.ansi.preferences.AnsiConsolePreferenceUtils; +import org.eclipse.ui.internal.console.ansi.utils.AnsiClipboardUtils; import org.eclipse.ui.progress.WorkbenchJob; /** @@ -394,7 +398,7 @@ public void lineGetStyle(LineStyleEvent event) { for (Position position : overlap) { StyleRange linkRange = new StyleRange(position.offset, position.length, color, null); linkRange.underline = true; - overrideStyleRange(ranges, linkRange); + StyleRangeUtil.overrideStyleRange(ranges, linkRange); } } } catch (BadPositionCategoryException e) { @@ -406,86 +410,6 @@ public void lineGetStyle(LineStyleEvent event) { } } - /** - * Apply new style range to list of existing style ranges. If the new style - * range overlaps with any of the existing style ranges the new style overrides - * the existing one in the affected range by splitting/adjusting the existing - * ones. - * - * @param ranges list of existing style ranges (will contain the new style - * range when finished) - * @param newRange new style range which should be combined with the existing - * ranges - */ - private static void overrideStyleRange(List ranges, StyleRange newRange) { - final int overrideStart = newRange.start; - final int overrideEnd = overrideStart + newRange.length; - int insertIndex = ranges.size(); - for (int i = ranges.size() - 1; i >= 0; i--) { - final StyleRange existingRange = ranges.get(i); - final int existingStart = existingRange.start; - final int existingEnd = existingStart + existingRange.length; - - // Find first position to insert where offset of new range is smaller then all - // offsets before. This way the list is still sorted by offset after insert if - // it was sorted before and it will not fail if list was not sorted. - if (overrideStart <= existingStart) { - insertIndex = i; - } - - // adjust the existing range if required - if (overrideStart <= existingStart) { // new range starts before or with existing - if (overrideEnd < existingStart) { - // new range lies before existing range. No overlapping. - // new range: ++++_________ - // existing : ________===== - // . result : ++++____===== - // nothing to do - } else if (overrideEnd < existingEnd) { - // new range overlaps start of existing. - // new range: ++++++++_____ - // existing : _____======== - // . result : ++++++++===== - final int overlap = overrideEnd - existingStart; - existingRange.start += overlap; - existingRange.length -= overlap; - } else { - // new range completely overlaps existing. - // new range: ___++++++++++ - // existing : ___======____ - // . result : ___++++++++++ - ranges.remove(i); - } - } else { // new range starts inside or after existing - if (existingEnd < overrideStart) { - // new range lies after existing range. No overlapping. - // new range: _________++++ - // existing : =====________ - // . result : =====____++++ - // nothing to do - } else if (overrideEnd >= existingEnd) { - // new range overlaps end of existing. - // new range: _____++++++++ - // existing : ========_____ - // . result : =====++++++++ - existingRange.length -= existingEnd - overrideStart; - } else { - // new range lies inside existing range but not overrides all of it - // (and does not touch first or last offset of existing) - // new range: ____+++++____ - // existing : ============= - // . result : ====+++++==== - final StyleRange clonedRange = (StyleRange) existingRange.clone(); - existingRange.length = overrideStart - existingStart; - clonedRange.start = overrideEnd; - clonedRange.length = existingEnd - overrideEnd; - ranges.add(i + 1, clonedRange); - } - } - } - ranges.add(insertIndex, newRange); - } - /** * Binary search for the positions overlapping the given range * @@ -736,6 +660,20 @@ public void setConsoleWidth(int width) { } } + @Override + public void doOperation(int operationCode) { + if (operationCode == ITextOperationTarget.COPY && AnsiConsolePreferenceUtils.isAnsiConsoleEnabled()) { + StyledText styledText = getTextWidget(); + if (styledText != null && !styledText.isDisposed()) { + // The widget text still contains the raw ANSI escape sequences + // (they are only hidden visually), so strip them on copy. + AnsiClipboardUtils.textToClipboard(styledText, true); + return; + } + } + super.doOperation(operationCode); + } + @Override protected void handleDispose() { IDocument document = getDocument(); diff --git a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ConsolePatternMatcher.java b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ConsolePatternMatcher.java index 61e0ebadda7..1a73b5f92a6 100644 --- a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ConsolePatternMatcher.java +++ b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ConsolePatternMatcher.java @@ -15,6 +15,7 @@ package org.eclipse.ui.internal.console; import java.util.ArrayList; +import java.util.Arrays; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -31,6 +32,7 @@ import org.eclipse.ui.console.IPatternMatchListener; import org.eclipse.ui.console.PatternMatchEvent; import org.eclipse.ui.console.TextConsole; +import org.eclipse.ui.internal.console.ansi.AnsiConsoleUtils; public class ConsolePatternMatcher implements IDocumentListener { @@ -62,7 +64,7 @@ private class MatchJob extends Job { @Override protected IStatus run(IProgressMonitor monitor) { IDocument doc = fConsole.getDocument(); - String text = null; + StrippedText stripped = null; int prevBaseOffset = -1; if (doc != null && !monitor.isCanceled()) { int endOfSearch = doc.getLength(); @@ -93,12 +95,16 @@ protected IStatus run(IProgressMonitor monitor) { if (lengthToSearch > 0) { try { if (prevBaseOffset != baseOffset) { - // reuse the text string if possible - text = doc.get(baseOffset, lengthToSearch); + // reuse the stripped text if possible + String rawText = doc.get(baseOffset, lengthToSearch); + stripped = StrippedText.of(rawText); } - if(text == null) { + if (stripped == null) { continue; } + String text = stripped.text; + int[] cleanToRaw = stripped.cleanToRaw; + int cleanLength = text.length(); Matcher reg = notifier.pattern.matcher(text); Matcher quick = null; if (notifier.qualifier != null) { @@ -107,38 +113,44 @@ protected IStatus run(IProgressMonitor monitor) { int startOfNextSearch = 0; int endOfLastMatch = -1; int lineOfLastMatch = -1; - while ((startOfNextSearch < lengthToSearch) && !monitor.isCanceled()) { + while ((startOfNextSearch < cleanLength) && !monitor.isCanceled()) { if (quick != null) { if (quick.find(startOfNextSearch)) { // start searching on the beginning // of the line where the potential // match was found, or after the // last match on the same line - int matchLine = doc.getLineOfOffset(baseOffset + quick.start()); + int matchLine = doc.getLineOfOffset(baseOffset + cleanToRaw(cleanToRaw, quick.start())); if (lineOfLastMatch == matchLine) { startOfNextSearch = endOfLastMatch; } else { - startOfNextSearch = doc.getLineOffset(matchLine) - baseOffset; + startOfNextSearch = rawToClean(cleanToRaw, cleanLength, doc.getLineOffset(matchLine) - baseOffset); } } else { - startOfNextSearch = lengthToSearch; + startOfNextSearch = cleanLength; } } if (startOfNextSearch < 0) { startOfNextSearch = 0; } - if (startOfNextSearch < lengthToSearch) { + if (startOfNextSearch < cleanLength) { if (reg.find(startOfNextSearch)) { endOfLastMatch = reg.end(); - lineOfLastMatch = doc.getLineOfOffset(baseOffset + endOfLastMatch - 1); - int regStart = reg.start(); + lineOfLastMatch = doc.getLineOfOffset(baseOffset + cleanToRaw(cleanToRaw, endOfLastMatch) - 1); + + int rawStart = baseOffset + cleanToRaw(cleanToRaw, reg.start()); + // map the raw end to just after the last matched character so + // that escapes inside the match are included while escapes + // following the match are not + int rawEnd = baseOffset + cleanToRaw(cleanToRaw, endOfLastMatch - 1) + 1; + IPatternMatchListener listener = notifier.listener; if (listener != null && !monitor.isCanceled()) { - listener.matchFound(new PatternMatchEvent(fConsole, baseOffset + regStart, endOfLastMatch - regStart)); + listener.matchFound(new PatternMatchEvent(fConsole, rawStart, rawEnd - rawStart)); } startOfNextSearch = endOfLastMatch; } else { - startOfNextSearch = lengthToSearch; + startOfNextSearch = cleanLength; } } } @@ -148,7 +160,7 @@ protected IStatus run(IProgressMonitor monitor) { // line that // was last searched if (lastLineToSearch == lineOfLastMatch) { - notifier.end = baseOffset + endOfLastMatch; + notifier.end = baseOffset + cleanToRaw(cleanToRaw, endOfLastMatch); } else { notifier.end = offsetOfLastLineToSearch; } @@ -179,6 +191,59 @@ public boolean belongsTo(Object family) { } + private static int cleanToRaw(int[] cleanToRaw, int cleanIndex) { + return cleanToRaw == null ? cleanIndex : cleanToRaw[cleanIndex]; + } + + private static int rawToClean(int[] cleanToRaw, int cleanLength, int rawOffset) { + if (cleanToRaw == null) { + return rawOffset; + } + if (rawOffset <= 0) { + return 0; + } + int index = Arrays.binarySearch(cleanToRaw, 0, cleanLength + 1, rawOffset); + return index >= 0 ? index : Math.max(0, -index - 2); + } + + private static final class StrippedText { + final String text; + final int[] cleanToRaw; + + private StrippedText(String text, int[] cleanToRaw) { + this.text = text; + this.cleanToRaw = cleanToRaw; + } + + private static StrippedText of(String raw) { + Matcher matcher = AnsiConsoleUtils.ESCAPE_SEQUENCE_REGEX_TXT.matcher(raw); + if (!matcher.find()) { + return new StrippedText(raw, null); + } + StringBuilder text = new StringBuilder(raw.length()); + int[] cleanToRaw = new int[raw.length() + 1]; + int rawIndex = 0; + int cleanIndex = 0; + do { + cleanIndex = append(text, raw, rawIndex, matcher.start(), cleanToRaw, cleanIndex); + rawIndex = matcher.end(); + } while (matcher.find()); + cleanIndex = append(text, raw, rawIndex, raw.length(), cleanToRaw, cleanIndex); + cleanToRaw[cleanIndex] = raw.length(); + return new StrippedText(text.toString(), cleanToRaw); + } + + private static int append(StringBuilder text, String raw, int from, int to, int[] cleanToRaw, int cleanIndex) { + int cleanPos = cleanIndex; + for (int rawPos = from; rawPos < to; rawPos++) { + text.append(raw.charAt(rawPos)); + cleanToRaw[cleanPos] = rawPos; + cleanPos++; + } + return cleanPos; + } + } + private static class CompiledPatternMatchListener { Pattern pattern; diff --git a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/StyleRangeUtil.java b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/StyleRangeUtil.java new file mode 100644 index 00000000000..65462c389ae --- /dev/null +++ b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/StyleRangeUtil.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2026 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.internal.console; + +import java.util.List; + +import org.eclipse.swt.custom.StyleRange; + +public final class StyleRangeUtil { + + private StyleRangeUtil() { + } + + /** + * Apply new style range to list of existing style ranges. If the new style + * range overlaps with any of the existing style ranges the new style overrides + * the existing one in the affected range by splitting/adjusting the existing + * ones. + * + * @param ranges list of existing style ranges (will contain the new style + * range when finished) + * @param newRange new style range which should be combined with the existing + * ranges + */ + public static void overrideStyleRange(List ranges, StyleRange newRange) { + final int overrideStart = newRange.start; + final int overrideEnd = overrideStart + newRange.length; + int insertIndex = ranges.size(); + for (int i = ranges.size() - 1; i >= 0; i--) { + final StyleRange existingRange = ranges.get(i); + final int existingStart = existingRange.start; + final int existingEnd = existingStart + existingRange.length; + + // Find first position to insert where offset of new range is smaller then all + // offsets before. This way the list is still sorted by offset after insert if + // it was sorted before and it will not fail if list was not sorted. + if (overrideStart <= existingStart) { + insertIndex = i; + } + + // adjust the existing range if required + if (overrideStart <= existingStart) { // new range starts before or with existing + if (overrideEnd < existingStart) { + // new range lies before existing range. No overlapping. + // new range: ++++_________ + // existing : ________===== + // . result : ++++____===== + // nothing to do + } else if (overrideEnd < existingEnd) { + // new range overlaps start of existing. + // new range: ++++++++_____ + // existing : _____======== + // . result : ++++++++===== + final int overlap = overrideEnd - existingStart; + existingRange.start += overlap; + existingRange.length -= overlap; + } else { + // new range completely overlaps existing. + // new range: ___++++++++++ + // existing : ___======____ + // . result : ___++++++++++ + ranges.remove(i); + } + } else { // new range starts inside or after existing + if (existingEnd < overrideStart) { + // new range lies after existing range. No overlapping. + // new range: _________++++ + // existing : =====________ + // . result : =====____++++ + // nothing to do + } else if (overrideEnd >= existingEnd) { + // new range overlaps end of existing. + // new range: _____++++++++ + // existing : ========_____ + // . result : =====++++++++ + existingRange.length -= existingEnd - overrideStart; + } else { + // new range lies inside existing range but not overrides all of it + // (and does not touch first or last offset of existing) + // new range: ____+++++____ + // existing : ============= + // . result : ====+++++==== + final StyleRange clonedRange = (StyleRange) existingRange.clone(); + existingRange.length = overrideStart - existingStart; + clonedRange.start = overrideEnd; + clonedRange.length = existingEnd - overrideEnd; + ranges.add(i + 1, clonedRange); + } + } + } + ranges.add(insertIndex, newRange); + } +} diff --git a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/AnsiConsoleUtils.java b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/AnsiConsoleUtils.java index 2f538f25b20..063ac1dc254 100644 --- a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/AnsiConsoleUtils.java +++ b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/AnsiConsoleUtils.java @@ -10,6 +10,7 @@ *******************************************************************************/ package org.eclipse.ui.internal.console.ansi; +import java.util.regex.Matcher; import java.util.regex.Pattern; public class AnsiConsoleUtils { @@ -22,6 +23,31 @@ public class AnsiConsoleUtils { public static final char ESCAPE_SGR = 'm'; + /** + * Removes all ANSI escape sequences from the given text. + * + * @param text the text to clean, may be null + * @return the text without ANSI escape sequences, or the original text if it + * is null, empty or contains no escape sequence + */ + public static String removeAnsiSequences(String text) { + if (text == null || text.isEmpty()) { + return text; + } + Matcher matcher = ESCAPE_SEQUENCE_REGEX_TXT.matcher(text); + if (!matcher.find()) { + return text; + } + StringBuilder result = new StringBuilder(text.length()); + int last = 0; + do { + result.append(text, last, matcher.start()); + last = matcher.end(); + } while (matcher.find()); + result.append(text, last, text.length()); + return result.toString(); + } + private AnsiConsoleUtils() { // Utility class, should not be instantiated } diff --git a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/participants/AnsiConsoleStyleListener.java b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/participants/AnsiConsoleStyleListener.java index 18a40c1c3f6..f82fb697d45 100644 --- a/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/participants/AnsiConsoleStyleListener.java +++ b/debug/org.eclipse.ui.console/src/org/eclipse/ui/internal/console/ansi/participants/AnsiConsoleStyleListener.java @@ -32,6 +32,7 @@ import org.eclipse.swt.graphics.GlyphMetrics; import org.eclipse.ui.internal.console.ansi.AnsiConsoleUtils; import org.eclipse.ui.internal.console.ansi.preferences.AnsiConsolePreferenceUtils; +import org.eclipse.ui.internal.console.StyleRangeUtil; import org.eclipse.ui.internal.console.ansi.utils.AnsiConsoleAttributes; import org.eclipse.ui.internal.console.ansi.utils.AnsiConsoleColorPalette; @@ -117,11 +118,6 @@ public void lineGetStyle(LineStyleEvent event) { final int eventOffset = event.lineOffset; final int eventLength = event.lineText.length(); - final List cachedRanges = offsetToStyleRangeCache.get(eventOffset); - if (cachedRanges != null) { - event.styles = cachedRanges.toArray(new StyleRange[0]); - return; - } if (event.styles == null) { // It looks that in some cases this comes in as null event.styles = new StyleRange[0]; } @@ -141,17 +137,54 @@ public void lineGetStyle(LineStyleEvent event) { return; } - final Color errorColor = AnsiConsolePreferenceUtils.getDebugConsoleErrorColor(); - Color foregroundColor = AnsiConsolePreferenceUtils.getDebugConsoleFgColor(); - if (AnsiConsolePreferenceUtils.tryPreservingStdErrColor()) { + List ranges = offsetToStyleRangeCache.get(eventOffset); + if (ranges == null) { + Color foregroundColor = AnsiConsolePreferenceUtils.getDebugConsoleFgColor(); + if (AnsiConsolePreferenceUtils.tryPreservingStdErrColor()) { + Color errorColor = AnsiConsolePreferenceUtils.getDebugConsoleErrorColor(); + for (StyleRange range : event.styles) { + if (errorColor.equals(range.foreground)) { + foregroundColor = errorColor; + break; + } + } + } + ranges = calculateAnsiRanges(positions, eventOffset, eventLength, foregroundColor); + if (!ranges.isEmpty()) { + offsetToStyleRangeCache.put(eventOffset, ranges); + } + } + + if (!ranges.isEmpty()) { + // Copy the links that might already exist. + List merged = new ArrayList<>(ranges.size()); + for (StyleRange range : ranges) { + merged.add((StyleRange) range.clone()); + } for (StyleRange range : event.styles) { - if (errorColor.equals(range.foreground)) { - foregroundColor = errorColor; - break; + if (range.foreground != null) { + if (range.foreground.equals(AnsiConsolePreferenceUtils.getHyperlinkColor())) { + StyleRangeUtil.overrideStyleRange(merged, range); + } + // We preserve the C/C++ build console colors (all except regular output) + if (isCdtBuildConsole && !range.foreground.equals(AnsiConsolePreferenceUtils.getCdtOutputStreamColor())) { + StyleRangeUtil.overrideStyleRange(merged, range); + } + } + } + // A hyperlink (or other overriding) range may span escape sequences that + // are part of the matched text. Re-apply the zero-width metrics so those + // escape sequences stay hidden instead of showing up as raw text. + for (StyleRange range : ranges) { + if (range.metrics != null) { + StyleRangeUtil.overrideStyleRange(merged, (StyleRange) range.clone()); } } + event.styles = merged.toArray(new StyleRange[0]); } + } + private List calculateAnsiRanges(Position[] positions, int eventOffset, int eventLength, Color foregroundColor) { final List ranges = new ArrayList<>(); AnsiConsoleAttributes prevAttr = lastVisibleAttribute; int prevPos = eventOffset; @@ -175,23 +208,7 @@ public void lineGetStyle(LineStyleEvent event) { } } addRange(ranges, prevPos, eventOffset + eventLength - prevPos, prevAttr, foregroundColor, false); - - if (!ranges.isEmpty()) { - // Copy the links that might already exist - for (StyleRange range : event.styles) { - if (range.foreground != null) { - if (range.foreground.equals(AnsiConsolePreferenceUtils.getHyperlinkColor())) { - ranges.add(range); - } - // We preserve the C/C++ build console colors (all except regular output) - if (isCdtBuildConsole && !range.foreground.equals(AnsiConsolePreferenceUtils.getCdtOutputStreamColor())) { - ranges.add(range); - } - } - } - offsetToStyleRangeCache.put(eventOffset, ranges); - event.styles = ranges.toArray(new StyleRange[0]); - } + return ranges; } private static List findPositions(int offset, String currentText) { diff --git a/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/META-INF/MANIFEST.MF b/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/META-INF/MANIFEST.MF index c87b4505a56..6931428e8f8 100644 --- a/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/META-INF/MANIFEST.MF +++ b/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %fragmentName Bundle-SymbolicName: org.eclipse.core.filesystem.linux.x86_64; singleton:=true -Bundle-Version: 1.2.500.qualifier +Bundle-Version: 1.2.600.qualifier Bundle-Vendor: %providerName Fragment-Host: org.eclipse.core.filesystem;bundle-version="[1.11.500,2.0.0)" Bundle-Localization: fragment diff --git a/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/os/linux/x86_64/libfastlinuxfile_1_0_0.so b/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/os/linux/x86_64/libfastlinuxfile_1_0_0.so index 8246930cd6a..ea56e3c1eba 100644 Binary files a/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/os/linux/x86_64/libfastlinuxfile_1_0_0.so and b/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/os/linux/x86_64/libfastlinuxfile_1_0_0.so differ diff --git a/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/pom.xml b/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/pom.xml index c44e07f8d4b..656c1f67019 100644 --- a/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/pom.xml +++ b/resources/bundles/org.eclipse.core.filesystem.linux.x86_64/pom.xml @@ -18,7 +18,7 @@ ../../ org.eclipse.core.filesystem.linux.x86_64 - 1.2.500-SNAPSHOT + 1.2.600-SNAPSHOT eclipse-plugin diff --git a/resources/bundles/org.eclipse.core.filesystem/natives/unix/fastlinux/fastlinuxfile.c b/resources/bundles/org.eclipse.core.filesystem/natives/unix/fastlinux/fastlinuxfile.c index 6bc4238134a..98d3b70f9be 100644 --- a/resources/bundles/org.eclipse.core.filesystem/natives/unix/fastlinux/fastlinuxfile.c +++ b/resources/bundles/org.eclipse.core.filesystem/natives/unix/fastlinux/fastlinuxfile.c @@ -481,7 +481,7 @@ JNIEXPORT jobjectArray JNICALL Java_org_eclipse_core_internal_filesystem_local_l /* Follow symlink and update stat for further processing. */ if (fstatat(directoryFd, entry->d_name, &st, 0) != 0) { - memset(&st, 0, sizeof(st)); + /* Keep lstat data from the symlink itself for dangling links. */ statErrno = errno; } diff --git a/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFile.java b/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFile.java index 3ba4b2561c2..bb01cc0ec21 100644 --- a/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFile.java +++ b/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFile.java @@ -18,6 +18,7 @@ *******************************************************************************/ package org.eclipse.core.internal.filesystem.local; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -541,17 +542,40 @@ public InputStream openInputStream(int options, IProgressMonitor monitor) throws try { return new FileInputStream(file); } catch (FileNotFoundException e) { + IFileInfo info = fetchInfo(); + if (isBrokenSymbolicLink(info)) { + // If the file is a symbolic link and the target is set but does not exist, return an empty + // stream instead of throwing an exception + return new ByteArrayInputStream(new byte[0]); + } handleReadIOException(e); return null; } } + /** + * @param info the file info to check + * @return true if the file is a broken symbolic link, false otherwise + */ + private static boolean isBrokenSymbolicLink(IFileInfo info) { + // Historically, file info for a broken symbolic links reported that it doesn't exist + // if the target didn't existed as a file, which is actually incorrect. + // We can check for the existence of the target by checking if the link target attribute is set. + return !info.exists() && info.getAttribute(EFS.ATTRIBUTE_SYMLINK) && info.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET) != null; + } + /** @see #openInputStream(int, IProgressMonitor) */ @Override public byte[] readAllBytes(int options, IProgressMonitor monitor) throws CoreException { try { return Files.readAllBytes(file.toPath()); } catch (IOException e) { + IFileInfo info = fetchInfo(); + if (isBrokenSymbolicLink(info)) { + // If the file is a symbolic link and the target is set but does not exist, return an empty + // stream instead of throwing an exception + return new byte[0]; + } handleReadIOException(e); return null; } diff --git a/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/linux/LinuxFileNatives.java b/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/linux/LinuxFileNatives.java index ab0de0e924a..799911fd7b6 100644 --- a/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/linux/LinuxFileNatives.java +++ b/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/linux/LinuxFileNatives.java @@ -121,10 +121,15 @@ public static FileInfo fetchFileInfo(String fileName) { info = new FileInfo(); } else if ((stat.st_mode & S_IFMT) == S_IFLNK) { // it's a link! LinuxStructStat targetStat = new LinuxStructStat(); - if (stat(name, targetStat) == 0) { // get the information about the file the link points to + if (stat(name, targetStat) == 0 && targetStat.errno == 0) { // get the information about the file the link points to info = targetStat.toFileInfo(); // store the target file stats in info } else { // invalid link target - info = new FileInfo(); + // Keep symlink metadata (permissions/timestamp) from lstat for dangling links. + info = stat.toFileInfo(); + if (targetStat.errno == ENOENT) { + // Preserve historical "broken target" semantics while still providing link attributes. + info.setExists(false); + } if (targetStat.errno != ENOENT) { info.setError(IFileInfo.IO_ERROR); } diff --git a/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/nio/PosixHandler.java b/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/nio/PosixHandler.java index 7320a307944..c4a7762ae72 100644 --- a/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/nio/PosixHandler.java +++ b/resources/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/nio/PosixHandler.java @@ -57,14 +57,21 @@ public FileInfo fetchFileInfo(String fileName, int options) { try { PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + info.setExists(true); if (attrs.isSymbolicLink()) { info.setAttribute(EFS.ATTRIBUTE_SYMLINK, true); info.setStringAttribute(EFS.ATTRIBUTE_LINK_TARGET, Files.readSymbolicLink(path).toString()); - attrs = Files.readAttributes(path, PosixFileAttributes.class); + try { + attrs = Files.readAttributes(path, PosixFileAttributes.class); + } catch (NoSuchFileException e) { + // The link target does not exist, so we cannot read its attributes. + // Keep symlink metadata (permissions/timestamp) for dangling links. + // Preserve historical "broken target" semantics while still providing link attributes. + info.setExists(false); + } } - info.setExists(true); info.setLastModified(attrs.lastModifiedTime().toMillis()); info.setLength(attrs.size()); info.setDirectory(attrs.isDirectory()); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java index bc0abe739cc..e6c18509a0b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java @@ -334,7 +334,7 @@ public ResourceAttributes attributes(IResource resource) { } catch (CoreException e) { return null; } - if (!fileInfo.exists()) { + if (!fileInfo.exists() && !fileInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK)) { return null; } return FileUtil.fileInfoToAttributes(fileInfo); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java index 5c6de678e21..8c0b434317f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java @@ -15,7 +15,9 @@ package org.eclipse.core.internal.localstore; import java.util.Iterator; -import org.eclipse.core.filesystem.*; +import org.eclipse.core.filesystem.EFS; +import org.eclipse.core.filesystem.IFileInfo; +import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.internal.resources.Resource; import org.eclipse.core.resources.IResource; @@ -41,7 +43,7 @@ public UnifiedTreeNode(UnifiedTree tree, IResource resource, IFileStore store, I } public boolean existsInFileSystem() { - return fileInfo != null && fileInfo.exists(); + return fileInfo != null && (fileInfo.exists() || fileInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK)); } /** diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java index b9499e72345..f696f8c1ff7 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java @@ -320,7 +320,8 @@ private boolean internalDeleteFile(IFile file, int flags, IProgressMonitor monit // If the file doesn't exist on disk then signal to the workspace to delete the // file and return. IFileStore fileStore = localManager.getStore(file); - boolean localExists = fileStore.exists(); + IFileInfo localFileInfo = fileStore.fetchInfo(); + boolean localExists = localFileInfo.exists() || localFileInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK); if (!localExists) { deletedFile(file); // Indicate that the delete was successful. diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java index 5ed949138e7..5e330d58877 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/SymlinkTest.java @@ -35,6 +35,10 @@ import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFileAttributes; import java.util.function.Consumer; import java.util.function.Function; import org.eclipse.core.filesystem.EFS; @@ -50,6 +54,18 @@ import org.junit.jupiter.api.extension.RegisterExtension; public class SymlinkTest { + + public static final boolean SUPPORT_BROKEN_SYMLINKS = Platform.OS.isLinux() + && Platform.ARCH_X86_64.equals(Platform.getOSArch()); + + /** + * Tolerance in milliseconds applied when comparing a file's last modified time against a + * timestamp captured via {@link System#currentTimeMillis()}. The file system last modified + * time may be provided by a finer-resolution native (JNI) source, so rounding/truncation can + * make it appear a few milliseconds earlier than the wall-clock value. + */ + private static final long TIMESTAMP_TOLERANCE_MS = 1000; + /** * Symbolic links on Windows behave differently compared to Unix-based systems. Symbolic links * on Windows have their own set of attributes independent from the attributes of the link's @@ -57,7 +73,9 @@ public class SymlinkTest { * existence of the symbolic link itself, not its target. */ private static final boolean SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES = Platform.OS_WIN32 - .equals(Platform.getOS()) ? true : false; + .equals(Platform.getOS()); + + private static String specialCharName = "äöüß ƄƖƜ àÀâ µ²³úÔ"; //$NON-NLS-1$ protected IFileStore aDir, aFile; //actual Dir, File @@ -109,7 +127,11 @@ protected void mkLink(IFileStore dir, String src, String tgt) throws IOException @Test public void testBrokenSymlinkAttributes() throws Exception { - long testStartTime = System.currentTimeMillis(); + // Use a tolerance because getLastModified() may originate from a finer-resolution + // native (JNI) timer than System.currentTimeMillis(). Truncation/rounding can make + // the reported modification time appear a few milliseconds before testStartTime even + // though the file was created afterwards. + long testStartTime = System.currentTimeMillis() - TIMESTAMP_TOLERANCE_MS; makeLinkStructure(); //break links by removing actual dir and file ensureDoesNotExist(aDir); @@ -124,22 +146,39 @@ public void testBrokenSymlinkAttributes() throws Exception { assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES, ilDir.isDirectory()); assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES, illDir.exists()); assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES, illDir.isDirectory()); - if (SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES) { + if (SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES || SUPPORT_BROKEN_SYMLINKS) { // Symlinks on Windows have their own modification time. - assertTrue(ilFile.getLastModified() >= testStartTime); - assertTrue(ilDir.getLastModified() >= testStartTime); - assertTrue(illFile.getLastModified() >= testStartTime); - assertTrue(illDir.getLastModified() >= testStartTime); + assertTrue(ilFile.getLastModified() >= testStartTime, + "getLastModified()=" + ilFile.getLastModified() + " testStartTime=" + testStartTime); + assertTrue(ilDir.getLastModified() >= testStartTime, + "getLastModified()=" + ilDir.getLastModified() + " testStartTime=" + testStartTime); + assertTrue(illFile.getLastModified() >= testStartTime, + "getLastModified()=" + illFile.getLastModified() + " testStartTime=" + testStartTime); + assertTrue(illDir.getLastModified() >= testStartTime, + "getLastModified()=" + illDir.getLastModified() + " testStartTime=" + testStartTime); } else { assertEquals(0, ilFile.getLastModified()); assertEquals(0, ilDir.getLastModified()); assertEquals(0, illFile.getLastModified()); assertEquals(0, illDir.getLastModified()); } - assertEquals(0, ilFile.getLength()); - assertEquals(0, ilDir.getLength()); - assertEquals(0, illFile.getLength()); - assertEquals(0, illDir.getLength()); + + if (SUPPORT_BROKEN_SYMLINKS) { + PosixFileAttributes ilFileAttrs = posixAttributess(lFile); + PosixFileAttributes illFileAttrs = posixAttributess(llFile); + PosixFileAttributes ilDirAttrs = posixAttributess(lDir); + PosixFileAttributes illDirAttrs = posixAttributess(llDir); + + assertEquals(ilFileAttrs.size(), ilFile.getLength()); + assertEquals(ilDirAttrs.size(), ilDir.getLength()); + assertEquals(illFileAttrs.size(), illFile.getLength()); + assertEquals(illDirAttrs.size(), illDir.getLength()); + } else { + assertEquals(0, ilFile.getLength()); + assertEquals(0, ilDir.getLength()); + assertEquals(0, illFile.getLength()); + assertEquals(0, illDir.getLength()); + } assertTrue(ilFile.getAttribute(EFS.ATTRIBUTE_SYMLINK)); assertEquals(ilFile.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "aFile"); @@ -151,6 +190,11 @@ public void testBrokenSymlinkAttributes() throws Exception { assertEquals(illDir.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET), "lDir"); } + private static PosixFileAttributes posixAttributess(IFileStore store) throws IOException { + return Files.readAttributes(Paths.get(store.toURI()), PosixFileAttributes.class, + LinkOption.NOFOLLOW_LINKS); + } + // Moving a broken symlink is possible. @Test public void testBrokenSymlinkMove() throws Exception { @@ -213,7 +257,7 @@ public void testRecursiveSymlink() throws Exception { mkLink(baseStore, "l2", "l1"); IFileStore l1 = baseStore.getChild("l1"); IFileInfo i1 = l1.fetchInfo(); - assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES, i1.exists()); + assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES || SUPPORT_BROKEN_SYMLINKS, i1.exists()); assertFalse(i1.isDirectory()); assertTrue(i1.getAttribute(EFS.ATTRIBUTE_SYMLINK)); @@ -231,7 +275,13 @@ public void testRecursiveSymlink() throws Exception { // ignored until the FIXME above is resolved } i1 = l1.fetchInfo(); - assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES, i1.exists()); + boolean fixMeFixed = false; + if (fixMeFixed) { + //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links + assertTrue(exceptionThrown); + assertTrue(i1.getAttribute(EFS.ATTRIBUTE_READ_ONLY)); + } + assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES || SUPPORT_BROKEN_SYMLINKS, i1.exists()); i1.setLastModified(12345); try { @@ -240,7 +290,10 @@ public void testRecursiveSymlink() throws Exception { // ignored until the FIXME above is resolved } i1 = l1.fetchInfo(); - assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES, i1.exists()); + //FIXME bug: putInfo neither sets attributes nor throws an exception for broken symbolic links + //assertTrue(exceptionThrown); + //assertEquals(i1.getLastModified(), 12345); + assertEquals(SYMLINKS_ARE_FIRST_CLASS_FILES_OR_DIRECTORIES || SUPPORT_BROKEN_SYMLINKS, i1.exists()); l1.delete(EFS.NONE, getMonitor()); infos = baseStore.childInfos(EFS.NONE, getMonitor()); diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SymlinkResourceTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SymlinkResourceTest.java index cb9f21984f3..37d2b14534a 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SymlinkResourceTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SymlinkResourceTest.java @@ -22,23 +22,36 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForRefresh; 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 static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Set; import org.eclipse.core.filesystem.EFS; +import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.internal.localstore.UnifiedTree; +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.IResourceVisitor; import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.ResourceAttributes; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Platform.OS; +import org.eclipse.core.tests.filesystem.SymlinkTest; import org.eclipse.core.tests.resources.util.WorkspaceResetExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -244,4 +257,125 @@ public void testBug358830(boolean useAdvancedLinkCheck) throws Exception { } } + @Test + public void testBrokenSymlinkSeenAsIFileChild() throws Exception { + assumeTrue(canCreateSymLinks() && supportsBrokenSymlinks(), + "only relevant for platforms supporting symbolic links"); + + IProject project = getWorkspace().getRoot().getProject("testBrokenSymlinkSeenAsIFileChild"); + createInWorkspace(project); + + IFileStore folderStore = EFS.getStore(project.getLocationURI()).getChild("parent"); + folderStore.mkdir(EFS.NONE, createTestMonitor()); + mkLink(folderStore, "broken.txt", "missing.txt", false); + + project.refreshLocal(IResource.DEPTH_INFINITE, createTestMonitor()); + + IFolder parent = project.getFolder("parent"); + IFile brokenLink = project.getFile("parent/broken.txt"); + assertTrue(parent.exists()); + assertTrue(brokenLink.exists()); + assertEquals(IResource.FILE, brokenLink.getType()); + + try (InputStream contents = brokenLink.getContents()) { + assertNotNull(contents); + assertEquals(0, contents.readAllBytes().length); + } + + // A broken symlink is exposed as an empty file. All read-oriented IFile + // API must handle it gracefully (empty content / sensible defaults) + // rather than fail. + try (InputStream forcedContents = brokenLink.getContents(true)) { + assertNotNull(forcedContents); + assertEquals(0, forcedContents.readAllBytes().length); + } + assertEquals(0, brokenLink.readAllBytes().length); + assertEquals(0, brokenLink.readNBytes(1024).length); + assertEquals(0, brokenLink.readAllChars().length); + assertEquals("", brokenLink.readString()); + + // Charset / encoding lookups must not fail for a broken link. + assertNotNull(brokenLink.getCharset()); + assertNotNull(brokenLink.getCharset(true)); + // getCharset(false) may return null when no charset was explicitly set; + // it just must not throw. + assertNull(brokenLink.getCharset(false)); + + // Content description of an empty file must be obtainable without + // throwing (the value itself may be null when no type can be inferred). + brokenLink.getContentDescription(); + + // Line separator lookup must not fail. + assertNotNull(brokenLink.getLineSeparator(true)); + + // A broken link has no local history and is not content-restricted. + assertEquals(0, brokenLink.getHistory(createTestMonitor()).length); + assertFalse(brokenLink.isContentRestricted()); + + IFileStore fileStore = EFS.getStore(brokenLink.getLocationURI()); + IFileInfo info = fileStore.fetchInfo(); + + ResourceAttributes resourceAttributes = brokenLink.getResourceAttributes(); + assertNotNull(resourceAttributes); + assertTrue(resourceAttributes.isSymbolicLink()); + assertFalse(resourceAttributes.isReadOnly()); + assertTrue(resourceAttributes.isExecutable()); + assertFalse(resourceAttributes.isHidden()); + assertFalse(resourceAttributes.isArchive()); + + // java.io.File follows symlinks and thus has no data for broken links. + // Use java.nio.file with NOFOLLOW_LINKS (lstat semantics) to obtain the + // symlink's own metadata and validate the attributes reported by EFS. + Path linkPath = brokenLink.getLocation().toFile().toPath(); + assertTrue(Files.isSymbolicLink(linkPath)); + PosixFileAttributes linkAttributes = Files.readAttributes(linkPath, PosixFileAttributes.class, + LinkOption.NOFOLLOW_LINKS); + + // symlink attribute and link target + assertTrue(info.getAttribute(EFS.ATTRIBUTE_SYMLINK)); + assertEquals(Files.readSymbolicLink(linkPath).toString(), info.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET)); + + // length and modification time come from the link node itself + assertEquals(linkAttributes.size(), info.getLength()); + assertEquals(linkAttributes.lastModifiedTime().toMillis() / 1000, info.getLastModified() / 1000); + + // permissions come from the link node itself + Set permissions = linkAttributes.permissions(); + assertEquals(permissions.contains(PosixFilePermission.OWNER_READ), + info.getAttribute(EFS.ATTRIBUTE_OWNER_READ)); + assertEquals(permissions.contains(PosixFilePermission.OWNER_WRITE), + info.getAttribute(EFS.ATTRIBUTE_OWNER_WRITE)); + assertEquals(permissions.contains(PosixFilePermission.OWNER_EXECUTE), + info.getAttribute(EFS.ATTRIBUTE_OWNER_EXECUTE)); + assertEquals(permissions.contains(PosixFilePermission.GROUP_READ), + info.getAttribute(EFS.ATTRIBUTE_GROUP_READ)); + assertEquals(permissions.contains(PosixFilePermission.GROUP_WRITE), + info.getAttribute(EFS.ATTRIBUTE_GROUP_WRITE)); + assertEquals(permissions.contains(PosixFilePermission.GROUP_EXECUTE), + info.getAttribute(EFS.ATTRIBUTE_GROUP_EXECUTE)); + assertEquals(permissions.contains(PosixFilePermission.OTHERS_READ), + info.getAttribute(EFS.ATTRIBUTE_OTHER_READ)); + assertEquals(permissions.contains(PosixFilePermission.OTHERS_WRITE), + info.getAttribute(EFS.ATTRIBUTE_OTHER_WRITE)); + assertEquals(permissions.contains(PosixFilePermission.OTHERS_EXECUTE), + info.getAttribute(EFS.ATTRIBUTE_OTHER_EXECUTE)); + + boolean foundAsIFileChild = false; + for (IResource member : parent.members()) { + if ("broken.txt".equals(member.getName())) { + foundAsIFileChild = true; + assertTrue(member instanceof IFile); + assertEquals(IResource.FILE, member.getType()); + assertTrue(member.exists()); + assertNotNull(member.getResourceAttributes()); + assertTrue(member.getResourceAttributes().isSymbolicLink()); + } + } + assertTrue(foundAsIFileChild, "Expected parent folder to contain broken symlink as child IFile"); + } + + private boolean supportsBrokenSymlinks() { + return SymlinkTest.SUPPORT_BROKEN_SYMLINKS; + } + } diff --git a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java index 9a49be9ddc3..467bb3c736f 100644 --- a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java +++ b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.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 @@ -106,6 +106,11 @@ public class CompareEditor extends EditorPart private Control emptyPage; private volatile int state = UNINITIALIZED; + /** + * Set when the initialization job is canceled while the contents are being + * created. + */ + private boolean canceledWhileCreating; private HashSet knownSaveables; private final EditorCompareContainer fContainer = new EditorCompareContainer(); @@ -364,7 +369,8 @@ protected IStatus run(final IProgressMonitor monitor) { newState[0] = CANCELED; } Display.getDefault().syncExec(() -> { - if (fPageBook.isDisposed()) { + // The job of a replaced input must not change the state of the current one + if (fPageBook.isDisposed() || getEditorInput() != cei) { return; } // we need to register the saveable if we had a previous input or if @@ -373,6 +379,18 @@ protected IStatus run(final IProgressMonitor monitor) { if (hadPreviousInput || (knownSaveables != null && !isAllSaveablesKnown())) { registerSaveable(); } + // Check if the contents are being created right now, e.g. by the "still + // initializing" timer, with this syncExec dispatched by the event loop of + // the first diff. Creating them again would leave a second, orphaned + // content tree, whose viewer later diffs against a disposed input. + if (CompareEditor.this.getState() == CREATING_CONTROL) { + // Don't lose a cancellation: it is handled once the + // contents being created are complete. + if (newState[0] == CANCELED) { + canceledWhileCreating = true; + } + return; + } setState(newState[0]); createCompareControl(); }); @@ -454,6 +472,7 @@ private void createCompareControl() { } // Set the state in case this method gets called again setState(CREATING_CONTROL); + canceledWhileCreating = false; if (getSite().getSelectionProvider() == null) { getSite().setSelectionProvider(new CompareEditorSelectionProvider()); } @@ -466,6 +485,17 @@ private void createCompareControl() { return; } } + if (canceledWhileCreating) { + setState(CANCELED); + // Close later: this can run while the editor itself is still being created + IEditorInput canceledInput = getEditorInput(); + fPageBook.getDisplay().asyncExec(() -> { + if (!fPageBook.isDisposed() && getEditorInput() == canceledInput) { + closeEditor(); + } + }); + return; + } fPageBook.showPage(fControl); if (PlatformUI.isWorkbenchRunning()) { diff --git a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/UnifiedDiff.java b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/UnifiedDiff.java index 2b8180867d5..01c8851cb37 100644 --- a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/UnifiedDiff.java +++ b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/UnifiedDiff.java @@ -57,6 +57,24 @@ public static Builder create(ITextEditor editor, String source, UnifiedDiffMode return new Builder(editor, source, mode); } + /** + * Removes the unified diff display from the given editor without changing its + * document or computing another diff. Clears diff annotations and code minings, + * disposes diff toolbars and listeners, removes diff folds, restores the editor's + * navigation actions, and prevents a pending diff computation from restoring the display. + * Annotations unrelated to the diff are preserved. + *

+ * Must be called on the editor's UI thread. Has no effect when the editor has no + * unified diff or no live text viewer. A new diff can be opened afterwards. + * + * @param editor the text editor whose unified diff display is removed + * @throws NullPointerException if the editor is null + * @since 3.13 + */ + public static void dispose(ITextEditor editor) { + UnifiedDiffManager.dispose(Objects.requireNonNull(editor, "Editor cannot be null")); //$NON-NLS-1$ + } + /** * Identifies a built-in action of a unified diff toolbar, so that its text or * image can be replaced. Which actions are shown depends on the diff --git a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffCodeMiningProvider.java b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffCodeMiningProvider.java index 31301de43df..d37a47bd0b3 100644 --- a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffCodeMiningProvider.java +++ b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffCodeMiningProvider.java @@ -79,6 +79,7 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PlatformUI; @@ -174,10 +175,26 @@ public CompletableFuture> provideCodeMinings(ITextVi if (viewer instanceof ISourceViewer sv) { List attached = attachedMiningsOf(sv, diffs); if (attached != null) { + List replacements = new ArrayList<>(); + for (ICodeMining mining : attached) { + if (mining instanceof UnifiedDiffLineHeaderCodeMining header) { + Position position = header.getPosition(); + try { + replacements.add(new UnifiedDiffLineHeaderCodeMining(new Position(position.offset, position.length), + this, header.getUnifiedDiff(), header.getTabWidth(), deletionBackgroundColor, + detailedDiffColor, borderColor, viewer)); + } catch (BadLocationException e) { + error(e); + } + } else if (mining instanceof UnifiedDiffFooterCodeMining footer) { + replacements.add(new UnifiedDiffFooterCodeMining(sv.getDocument(), this, footer.getUnifiedDiff(), + footer.getTabWidth(), deletionBackgroundColor, detailedDiffColor, borderColor, viewer)); + } + } // the expander minings are recreated instead of reused so that they // reflect the current expansion state of the folds - createFoldRegionCodeMinings(viewer, attached); - return CompletableFuture.completedFuture(attached); + createFoldRegionCodeMinings(viewer, replacements); + return CompletableFuture.completedFuture(replacements); } } @@ -514,6 +531,7 @@ interface IUnifiedDiffCodeMining { UnifiedDiff getUnifiedDiff(); String getLabel(); String getRawLabel(); + int getRowHeight(StyledText textWidget); } private record CodeMiningLabel(String raw, String expanded, String layout, boolean trailingCarriageReturn, @@ -590,18 +608,21 @@ public void setCodeMining(IUnifiedDiffCodeMining mining) { @Override public void accept(MouseEvent t) { - if (mining == null || viewer == null || mining.getLastRectangle() == null) { + if (mining == null || viewer == null) { return; } + Rectangle bounds = mining.getLastRectangle(); StyledText st = viewer.getTextWidget(); + if (bounds == null || st == null || st.isDisposed()) { + return; + } TextViewer overlayViewer = new TextViewer(st, SWT.NONE); // Allow selecting and copying the mining text without modifying it. overlayViewer.setEditable(false); StyledText overlay = overlayViewer.getTextWidget(); - overlay.setBounds(mining.getLastRectangle()); + overlay.setBounds(bounds); overlay.setFont(st.getFont()); overlay.setBackground(mining.getDeletionBackgroundColor()); - overlay.setLineSpacing(st.getLineSpacing()); overlay.setTabs(mining.getTabWidth()); String txt = mining.getRawLabel(); overlayViewer.setDocument(new Document(txt)); @@ -610,6 +631,18 @@ public void accept(MouseEvent t) { List foregrounds = computeStyleRanges(viewer, mining.getUnifiedDiff(), txt); List ranges = mergeStyleRanges(backgrounds, foregrounds); overlay.setStyleRanges(ranges.toArray(new StyleRange[] {})); + int rowHeight = mining.getRowHeight(st); + if (rowHeight <= 0) { + overlay.dispose(); + return; + } + overlay.setLineSpacing(0); + overlay.computeSize(SWT.DEFAULT, SWT.DEFAULT); + int[] lineSpacing = new int[overlay.getLineCount()]; + for (int line = 0; line < lineSpacing.length; line++) { + lineSpacing[line] = Math.max(0, rowHeight - overlay.getLineHeight(overlay.getOffsetAtLine(line))); + } + overlay.setLineSpacingProvider(line -> line >= 0 && line < lineSpacing.length ? lineSpacing[line] : 0); installWhitespacePainter(overlayViewer); overlay.setFocus(); openOverlay(overlay, viewer); @@ -690,6 +723,21 @@ public static class UnifiedDiffFooterCodeMining extends DocumentFooterCodeMining private final HashMap> styledFonts = new HashMap<>(); private Rectangle lastRectangle; private Font cachedFont; + private final MiningLayout miningLayout = new MiningLayout(); + private boolean disposed; + + @Override + public synchronized int getRowHeight(StyledText textWidget) { + if (disposed) { + return 0; + } + List ranges = styleRanges(unifiedDiffLabel); + if (disposed) { + return 0; + } + return miningLayout.lineHeight(textWidget, layoutLabel, ranges, styledFonts) + + textWidget.getLineSpacing(); + } public UnifiedDiffFooterCodeMining(IDocument document, ICodeMiningProvider provider, UnifiedDiff diff, int tabWidth, Color deletionBackgroundColor, Color detailedDiffColor, @@ -739,8 +787,15 @@ public UnifiedDiff getUnifiedDiff() { } @Override - public String getLabel() { - return this.layoutLabel; + public synchronized String getLabel() { + StyledText textWidget = viewer != null ? viewer.getTextWidget() : null; + if (!disposed && Display.getCurrent() != null && textWidget != null && !textWidget.isDisposed()) { + List ranges = styleRanges(unifiedDiffLabel); + if (!disposed) { + return miningLayout.label(textWidget, layoutLabel, ranges, styledFonts); + } + } + return miningLayout.reservedLabel == null ? layoutLabel : miningLayout.reservedLabel; } @Override @@ -750,6 +805,7 @@ public String getRawLabel() { @Override public synchronized void dispose() { + disposed = true; styleRanges = null; lastRectangle = null; cachedFont = null; @@ -771,6 +827,9 @@ private List styleRanges(String label) { @Override public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + if (disposed) { + return new Point(0, 0); + } gc.setBackground(this.deletionBackgroundColor); Color c = textWidget.getForeground(); gc.setForeground(c); @@ -782,21 +841,28 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, clearStyledFonts(); } cachedFont = font; - // first run to get width and height for label - // change from https://github.com/eclipse-platform/eclipse.platform.ui/pull/3651 - // is required so that background correctly drawn with line spacing > 0 - Point result = super.draw(gc, textWidget, color, x, y); + List ranges = styleRanges; + Point result = miningLayout.extent(gc, textWidget, layoutLabel, ranges == null ? List.of() : ranges, styledFonts); lastRectangle = new Rectangle(x, y, result.x, result.y); + ranges = styleRanges(this.unifiedDiffLabel); + if (disposed) { + ranges = List.of(); + } + if (lastRectangle != null) { + result = miningLayout.extent(gc, textWidget, layoutLabel, ranges, styledFonts); + lastRectangle = new Rectangle(x, y, result.x, result.y); + } + int lineHeight = miningLayout.lineHeight; // draw background // vs code is drawing the background to the top right of the editor - we do here // the same! gc.fillRectangle(0, y, textWidget.getBounds().width /* result.x */, result.y); String label = this.unifiedDiffLabel; - List ranges = styleRanges(label); if (ranges.isEmpty()) { // no syntax coloring available; fall back to plain rendering - result = super.draw(gc, textWidget, color, x, y); + drawStyleRanges(gc, textWidget, ranges, label, rawLabel, styledFonts, x, y, null, + readWhitespaceConfig(tabWidth), trailingCarriageReturn, trailingLineFeed, lineHeight); drawBandBorder(gc, this.borderColor, y, textWidget.getBounds().width, result.y, this.bandBorder); return result; @@ -805,10 +871,10 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, // paint the word-level detailed-diff backgrounds first, then draw the // syntax-colored text transparently on top - same order as the header band WhitespaceConfig whitespace = readWhitespaceConfig(tabWidth); - fillDetailedDiffBackgrounds(gc, textWidget, label, ranges, whitespace, x, y); + fillDetailedDiffBackgrounds(gc, textWidget, label, ranges, whitespace, x, y, lineHeight); gc.setFont(font); drawStyleRanges(gc, textWidget, ranges, label, rawLabel, styledFonts, x, y, null, - whitespace, trailingCarriageReturn, trailingLineFeed); + whitespace, trailingCarriageReturn, trailingLineFeed, lineHeight); // Syntax-coloring callbacks can dispose the mining and clear lastRectangle. // Use the size measured by this draw call rather than the invalidated cache. drawBandBorder(gc, this.borderColor, y, textWidget.getBounds().width, result.y, @@ -822,11 +888,10 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, * paint a range background itself. */ private void fillDetailedDiffBackgrounds(GC gc, StyledText textWidget, String label, List ranges, - WhitespaceConfig whitespace, int x, int y) { + WhitespaceConfig whitespace, int x, int y, int lineHeight) { if (detailedDiffRanges.isEmpty()) { return; } - int lineHeight = textWidget.getLineHeight(); int lineSpacing = textWidget.getLineSpacing(); gc.setBackground(this.detailedDiffColor); for (DetailedDiffRange detailedDiff : detailedDiffRanges) { @@ -1174,6 +1239,104 @@ private static WhitespaceConfig readWhitespaceConfigUncached() { -1 /* tabWidth stamped in per call by readWhitespaceConfig */); } + /** Measures fallback glyphs as well as the editor's base font. */ + private static int miningLineHeight(GC gc, StyledText textWidget, String label, List ranges, + HashMap> styledFonts) { + TextLayout layout = new TextLayout(gc.getDevice()); + try { + Font font = textWidget.getFont(); + layout.setFont(font); + var metrics = layout.getLineMetrics(0); + layout.setAscent(metrics.getAscent() + metrics.getLeading()); + layout.setDescent(metrics.getDescent()); + layout.setText(label); + for (StyleRange range : ranges) { + if (range.length > 0) { + layout.setStyle(transformFontStyleToFont(styledFonts, font, range), range.start, + range.start + range.length - 1); + } + } + int height = textWidget.getLineHeight(); + for (int line = 0; line < layout.getLineCount(); line++) { + height = Math.max(height, layout.getLineBounds(line).height); + } + return height; + } finally { + layout.dispose(); + } + } + + private static int reservedHeight(StyledText textWidget, int height) { + int baseRowHeight = textWidget.getLineHeight() + textWidget.getLineSpacing(); + return Math.ceilDiv(height, baseRowHeight) * baseRowHeight; + } + + /** + * JFace reserves base-height rows from the label, independently of draw(). Extra + * invisible layout rows reserve the glyph-aware band height without changing + * the raw text painted or copied by the overlay. + */ + private static final class MiningLayout { + private Font font; + private int baseHeight; + private int lineHeight; + private int lineSpacing = -1; + private List styleRanges; + private String reservedLabel; + private boolean labelInvalid = true; + + private boolean matches(StyledText textWidget, List ranges) { + return font != null && !font.isDisposed() && font.equals(textWidget.getFont()) + && baseHeight == textWidget.getLineHeight() && styleRanges == ranges; + } + + private int lineHeight(GC gc, StyledText textWidget, String label, List ranges, + HashMap> styledFonts) { + if (!matches(textWidget, ranges)) { + lineHeight = miningLineHeight(gc, textWidget, label, ranges, styledFonts); + font = textWidget.getFont(); + baseHeight = textWidget.getLineHeight(); + styleRanges = ranges; + labelInvalid = true; + } + return lineHeight; + } + + private int lineHeight(StyledText textWidget, String label, List ranges, + HashMap> styledFonts) { + if (matches(textWidget, ranges)) { + return lineHeight; + } + GC gc = new GC(textWidget); + try { + return lineHeight(gc, textWidget, label, ranges, styledFonts); + } finally { + gc.dispose(); + } + } + + private Point extent(GC gc, StyledText textWidget, String label, List ranges, + HashMap> styledFonts) { + int height = lineHeight(gc, textWidget, label, ranges, styledFonts); + return new Point(gc.stringExtent(label).x, + reservedHeight(textWidget, countLines(label) * (height + textWidget.getLineSpacing()))); + } + + private String label(StyledText textWidget, String label, List ranges, + HashMap> styledFonts) { + int height = lineHeight(textWidget, label, ranges, styledFonts); + int spacing = textWidget.getLineSpacing(); + if (labelInvalid || spacing != lineSpacing) { + int rows = countLines(label); + int reservedRows = reservedHeight(textWidget, rows * (height + spacing)) / (baseHeight + spacing); + reservedLabel = label + ("\n" + EMPTY_LINE_LAYOUT_MARKER).repeat(reservedRows - rows); //$NON-NLS-1$ + lineSpacing = spacing; + labelInvalid = false; + } + return reservedLabel; + } + } + /** * Draws the syntax-colored label using the given style ranges, advancing the * cursor position range by range. The {@code onForeground} consumer is called @@ -1199,8 +1362,18 @@ private static void drawStyleRanges(GC gc, StyledText textWidget, List> styledFonts, int x, int y, Consumer onForeground, WhitespaceConfig whitespace, boolean trailingCarriageReturn, boolean trailingLineFeed) { + drawStyleRanges(gc, textWidget, ranges, label, rawLabel, styledFonts, x, y, onForeground, whitespace, + trailingCarriageReturn, trailingLineFeed, miningLineHeight(gc, textWidget, label, ranges, styledFonts)); + } + + private static void drawStyleRanges(GC gc, StyledText textWidget, List ranges, String label, + String rawLabel, HashMap> styledFonts, int x, int y, + Consumer onForeground, WhitespaceConfig whitespace, boolean trailingCarriageReturn, + boolean trailingLineFeed, int textWidgetLineHeight) { Font font = gc.getFont(); - int textWidgetLineHeight = textWidget.getLineHeight(); + if (ranges.isEmpty()) { + ranges = List.of(new StyleRange(0, label.length(), null, null)); + } int cx = x; int cy = y; for (StyleRange range : ranges) { @@ -1505,7 +1678,10 @@ private static List computeStyleRanges(ITextViewer v, UnifiedDiff di } return result; } catch (BadLocationException e) { - return result; + return List.of(); + } catch (RuntimeException e) { + error(e); + return List.of(); } } @@ -1597,6 +1773,22 @@ public static class UnifiedDiffLineHeaderCodeMining extends LineHeaderCodeMining private List styleRanges; private Font cachedFont; private WhitespaceConfig cachedWhitespace; + private int cachedRowHeight; + private final MiningLayout miningLayout = new MiningLayout(); + private boolean disposed; + + @Override + public synchronized int getRowHeight(StyledText textWidget) { + if (disposed) { + return 0; + } + List ranges = styleRanges(unifiedDiffLabel); + if (disposed) { + return 0; + } + return miningLayout.lineHeight(textWidget, layoutLabel, ranges, styledFonts) + + textWidget.getLineSpacing(); + } private final HashMap> styledFonts = new HashMap<>(); public UnifiedDiffLineHeaderCodeMining(Position position, ICodeMiningProvider provider, UnifiedDiff diff, @@ -1622,8 +1814,15 @@ public UnifiedDiffLineHeaderCodeMining(Position position, ICodeMiningProvider pr } @Override - public String getLabel() { - return this.layoutLabel; + public synchronized String getLabel() { + StyledText textWidget = viewer != null ? viewer.getTextWidget() : null; + if (!disposed && Display.getCurrent() != null && textWidget != null && !textWidget.isDisposed()) { + List ranges = styleRanges(unifiedDiffLabel); + if (!disposed) { + return miningLayout.label(textWidget, layoutLabel, ranges, styledFonts); + } + } + return miningLayout.reservedLabel == null ? layoutLabel : miningLayout.reservedLabel; } @Override @@ -1670,6 +1869,7 @@ private List styleRanges(String label) { @Override public synchronized void dispose() { + disposed = true; cleanCachedData(); styleRanges = null; super.dispose(); @@ -1696,6 +1896,9 @@ private void clearStyledFonts() { @Override public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { + if (disposed) { + return new Point(0, 0); + } gc.setBackground(this.deletionBackgroundColor); Color c = textWidget.getForeground(); gc.setForeground(c); @@ -1710,6 +1913,16 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, cleanCachedData(); } cachedFont = font; + List ranges = styleRanges(this.unifiedDiffLabel); + if (disposed) { + return new Point(0, 0); + } + int lineHeight = miningLayout.lineHeight(gc, textWidget, layoutLabel, ranges, styledFonts); + if (cachedRowHeight != lineHeight + textWidget.getLineSpacing()) { + cleanCachedData(); + cachedFont = font; + cachedRowHeight = lineHeight + textWidget.getLineSpacing(); + } if (lastRectangle != null && backgrounds != null && foregrounds != null) { boolean fontIsDisposed = false; // draw background @@ -1771,7 +1984,7 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, } } // first run to get width and height for label - Point result = super.draw(gc, textWidget, color, x, y); + Point result = miningLayout.extent(gc, textWidget, layoutLabel, ranges, styledFonts); lastRectangle = new Rectangle(x, y, result.x, result.y); // draw background @@ -1780,7 +1993,6 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, gc.fillRectangle(0, y, textWidget.getBounds().width /* result.x */, result.y); String label = this.unifiedDiffLabel; - List ranges = styleRanges(label); // draw darker background for detailed diff gc.setBackground(this.detailedDiffColor); @@ -1796,7 +2008,7 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, try { var rangeInfo = new RangeInfo(-1, -1, null); if (fromLine == toLine) { - int starty = getYForLine(fromLine - 1, y, gc, textWidget); + int starty = getYForLine(fromLine - 1, y); Point start = getPositionForOffset(textWidget, gc, detailedDiffStart, diffStr, ranges, rangeInfo); Point curr = getPositionForOffset(textWidget, gc, detailedDiffStart + detailedDiffLength, @@ -1818,7 +2030,7 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, diffStrDoc = new Document(diffStr); } String firstLine = diffLines[fromLine - 1]; - int starty = getYForLine(fromLine - 1, y, gc, textWidget); + int starty = getYForLine(fromLine - 1, y); int idx = getOffsetAtLine(diffStr, detailedDiffStart); int fromLineOffset; try { @@ -1852,7 +2064,7 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, } // all the lines between first and last line for (int middleLine = fromLine + 1; middleLine < toLine; middleLine++) { - starty = getYForLine(middleLine - 1, y, gc, textWidget); + starty = getYForLine(middleLine - 1, y); try { int currentLineEndOffset = diffStrDoc.getLineOffset(middleLine - 1) + diffStrDoc.getLineLength(middleLine - 1) @@ -1874,9 +2086,9 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, } } // last line - starty = getYForLine(toLine - 1, y, gc, textWidget); + starty = getYForLine(toLine - 1, y); int rectWidth = 0; - int rectHeight = textWidget.getLineHeight(); + int rectHeight = lineHeight; if (range.coversTrailingDelimiter() && detailedDiffStart + detailedDiffLength == diffStr.length()) { String marker = lineDelimiterMarker(whitespace, trailingCarriageReturn, trailingLineFeed); @@ -1904,11 +2116,8 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, } // draw foreground again if (ranges.size() == 0) { - // no syntax coloring available (e.g. plain-text editor without a - // presentation reconciler); fall back to super.draw() so the label is - // still rendered. backgrounds/foregrounds are intentionally left unset - // so the next paint takes the full slow path again. - result = super.draw(gc, textWidget, color, x, y); + drawStyleRanges(gc, textWidget, ranges, label, rawLabel, styledFonts, x, y, null, whitespace, + trailingCarriageReturn, trailingLineFeed, lineHeight); drawBandBorder(gc, this.borderColor, y, textWidget.getBounds().width, result.y, this.bandBorder); return result; } @@ -1916,7 +2125,7 @@ public synchronized Point draw(GC gc, StyledText textWidget, Color color, int x, cachedWhitespace = whitespace; gc.setFont(cachedFont); drawStyleRanges(gc, textWidget, ranges, label, rawLabel, styledFonts, x, y, foregrounds::add, whitespace, - trailingCarriageReturn, trailingLineFeed); + trailingCarriageReturn, trailingLineFeed, lineHeight); drawBandBorder(gc, this.borderColor, y, textWidget.getBounds().width, lastRectangle.height, this.bandBorder); return result; @@ -1947,7 +2156,10 @@ public Point getPositionForOffset(StyledText tw, GC gc, int offset, String str, String sub = str.substring(0, offset); Point result = null; var before = gc.getFont(); - int twLineHeight = tw.getLineHeight(); + int twLineHeight = cachedRowHeight - tw.getLineSpacing(); + if (twLineHeight <= 0) { + twLineHeight = miningLineHeight(gc, tw, str, ranges, styledFonts); + } try { int i = 0; if (rangeInfo.rangeIndex != -1 && offset >= rangeInfo.offset) { @@ -2049,10 +2261,8 @@ private int getOffsetAtLine(String str, int off) { return -1; } - private int getYForLine(int line, int y, GC gc, StyledText textWidget) { - int textWidgetLineHeight = textWidget.getLineHeight(); - y += line * (textWidgetLineHeight + textWidget.getLineSpacing()); - return y; + private int getYForLine(int line, int y) { + return y + line * cachedRowHeight; } } diff --git a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffManager.java b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffManager.java index 12f96a1134b..e4a2fddba07 100644 --- a/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffManager.java +++ b/team/bundles/org.eclipse.compare/compare/org/eclipse/compare/unifieddiff/internal/UnifiedDiffManager.java @@ -209,7 +209,8 @@ private static ToolbarActionPresentations toolbarActionPresentations(ITextViewer * model, so the one installed on the viewer is used. */ public static IAnnotationModel annotationModelOf(ITextEditor editor) { - IAnnotationModel model = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); + var provider = editor.getDocumentProvider(); + IAnnotationModel model = provider != null ? provider.getAnnotationModel(editor.getEditorInput()) : null; if (model != null) { return model; } @@ -218,6 +219,28 @@ public static IAnnotationModel annotationModelOf(ITextEditor editor) { : null; } + public static void dispose(ITextEditor editor) { + ITextViewer viewer = editor.getAdapter(ITextViewer.class); + if (viewer == null) { + return; + } + StyledText textWidget = viewer.getTextWidget(); + if (textWidget == null || textWidget.isDisposed()) { + return; + } + // Invalidate computations that yield to the UI event loop before installing + // their result, even when no diff has been displayed yet. + textWidget.setData(OPEN_REQUEST_KEY, null); + IAnnotationModel model = annotationModelOf(editor); + if (model != null) { + clearAll(viewer, model); + } + disposeUnifiedDiff(viewer, model, textWidget); + textWidget.setData(TOOLBAR_ACTION_PRESENTATIONS_KEY, null); + viewer.invalidateTextPresentation(); + textWidget.redraw(); + } + /** * Installs an annotation model on the viewer of an editor whose document * provider has none, so that the diffs have somewhere to be shown. @@ -266,7 +289,7 @@ public static IStatus open(ITextEditor editor, String source, UnifiedDiffMode mo IStatus status = open(viewer, leftDocument, model, file, source, mode, additionalActions, tokenComparatorFactory, ignoreWhitespaceContributorFactory, compareFilters, leftContributor, rightContributor, ignoreWhiteSpace, foldContextLines, toolbarActionPresentations, eventListener); - if (status.isOK()) { + if (status.isOK() && get(viewer) != null) { registerCommandHandlers(editor, viewer, model); } return status; @@ -2565,28 +2588,24 @@ public void paintControl(PaintEvent e) { } else { endLineBounds = this.w.getTextBounds(endLineOffset, endLineOffset); } - endLineBounds.height += this.w.getLineSpacing(); - if (line.length() == 0) { - // this.w.getTextBounds seems not to work for empty lines containing only \n in - // a document with \r\n as line delimeter - int nextLineY = this.w.getLinePixel(lineNr + 1); - if (endLineBounds.y + endLineBounds.height < nextLineY) { - endLineBounds.height = nextLineY - endLineBounds.y; - } - } - e.gc.fillRectangle(endLineBounds.x + endLineBounds.width, endLineBounds.y, - bounds.width - (endLineBounds.x + endLineBounds.width), endLineBounds.height); - - // annotation painter is not taking line spacing into account - we therefore - // need to draw it by our own - e.gc.fillRectangle(2, endLineBounds.y + endLineBounds.height - this.w.getLineSpacing(), - endLineBounds.x + endLineBounds.width, this.w.getLineSpacing()); + int rowTop = this.w.getLinePixel(lineNr) + this.w.getLineVerticalIndent(lineNr); + int rowBottom = this.w.getLinePixel(lineNr + 1); + int rowHeight = Math.max(0, rowBottom - rowTop); + e.gc.fillRectangle(endLineBounds.x + endLineBounds.width, rowTop, + bounds.width - (endLineBounds.x + endLineBounds.width), rowHeight); + Rectangle textBounds = line.isEmpty() ? endLineBounds + : this.w.getTextBounds(this.w.getOffsetAtLine(lineNr), endLineOffset - 1); + int textTop = Math.clamp(textBounds.y, rowTop, Math.max(rowTop, rowBottom)); + int textBottom = Math.clamp(textBounds.y + textBounds.height, rowTop, Math.max(rowTop, rowBottom)); + e.gc.fillRectangle(2, rowTop, endLineBounds.x + endLineBounds.width, Math.max(0, textTop - rowTop)); + e.gc.fillRectangle(2, textBottom, endLineBounds.x + endLineBounds.width, + Math.max(0, rowBottom - textBottom)); // The addition-area background fill above paints over the ¶/¤ markers the // editor's own whitespace painter drew at the line end, so redraw them here. drawLineDelimiter(e, endLineOffset, showCarriageReturn, showLineFeed, whitespaceAlpha, details); // The marker background must not overwrite the band's shared edge. - drawBandBorder(e.gc, bounds.width, endLineBounds.y, endLineBounds.height, + drawBandBorder(e.gc, bounds.width, rowTop, rowHeight, lineNr == hunkFirstLine, lineNr == lastLine); e.gc.setBackground(this.additionBackgroundColor); } diff --git a/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/AllCompareTests.java b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/AllCompareTests.java index 9fed2f0de76..08b006db14a 100644 --- a/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/AllCompareTests.java +++ b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/AllCompareTests.java @@ -38,10 +38,12 @@ RangeDifferencerThreeWayDiffTest.class, RangeDifferencerMonitorTest.class, CompareUIPluginTest.class, + CompareEditorReuseTest.class, CompareOpenEfficiencyTest.class, UnifiedDiffOpenTest.class, StructureCreatorTest.class, - CompareFileRevisionEditorInputTest.class}) + CompareFileRevisionEditorInputTest.class, + CompareEditorOpenRaceTest.class}) public class AllCompareTests { // test suite } diff --git a/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/CompareEditorOpenRaceTest.java b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/CompareEditorOpenRaceTest.java new file mode 100644 index 00000000000..dbda8d2236b --- /dev/null +++ b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/CompareEditorOpenRaceTest.java @@ -0,0 +1,151 @@ +/******************************************************************************* + * Copyright (c) 2026 Luise Ravnskjaer 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: + * Eclipse contributors - initial API and implementation + *******************************************************************************/ +package org.eclipse.compare.tests; + +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 java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.eclipse.compare.CompareConfiguration; +import org.eclipse.compare.CompareEditorInput; +import org.eclipse.compare.CompareUI; +import org.eclipse.compare.internal.ComparePreferencePage; +import org.eclipse.compare.internal.CompareUIPlugin; +import org.eclipse.compare.structuremergeviewer.DiffNode; +import org.eclipse.compare.structuremergeviewer.Differencer; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.preference.IPreferenceStore; +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.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that the contents of a compare editor input are created only once when + * the initialization job finishes while the "still initializing" timer is + * already creating them. + *

+ * The input holds its job until {@code createContents} has started and then + * runs the event loop from inside {@code createContents}, so that the job's UI + * callback is dispatched re-entrantly. See + * https://github.com/eclipse-platform/eclipse.platform/issues/123 + *

+ */ +public class CompareEditorOpenRaceTest { + + private static final long TIMEOUT_MILLIS = 30_000; + + private boolean originalUnifiedDiff; + + @BeforeEach + void setUp() { + assertNotNull(Display.getCurrent(), "tests require a UI thread / Display"); //$NON-NLS-1$ + originalUnifiedDiff = store().getBoolean(ComparePreferencePage.UNIFIED_DIFF); + store().setValue(ComparePreferencePage.UNIFIED_DIFF, false); + } + + @AfterEach + void tearDown() { + store().setValue(ComparePreferencePage.UNIFIED_DIFF, originalUnifiedDiff); + IWorkbenchPage page = activePage(); + if (page != null) { + page.closeAllEditors(false); + } + DisplayUtils.processQueuedEvents(); + } + + @Test + void testContentsCreatedOnceWhenJobFinishesDuringCreation() { + RaceInput input = new RaceInput(false); + CompareUI.openCompareEditor(input); + DisplayUtils.pumpUntil(() -> input.created > 0 && Job.getJobManager().find(input).length == 0, + "compare editor did not finish opening", TIMEOUT_MILLIS); //$NON-NLS-1$ + + assertFalse(input.raceMissed, "contents were not created while the job was held"); //$NON-NLS-1$ + assertEquals(1, input.created, "the contents of an input must be created once"); //$NON-NLS-1$ + } + + @Test + void testEditorClosedWhenJobIsCanceledDuringCreation() { + RaceInput input = new RaceInput(true); + CompareUI.openCompareEditor(input); + DisplayUtils.pumpUntil(() -> input.created > 0 && Job.getJobManager().find(input).length == 0, + "compare editor did not finish opening", TIMEOUT_MILLIS); //$NON-NLS-1$ + + assertFalse(input.raceMissed, "contents were not created while the job was held"); //$NON-NLS-1$ + DisplayUtils.pumpUntil(() -> activePage().findEditor(input) == null, "a canceled compare editor must be closed", //$NON-NLS-1$ + TIMEOUT_MILLIS); + } + + private static final class RaceInput extends CompareEditorInput { + + private final CountDownLatch creating = new CountDownLatch(1); + private final boolean cancel; + private volatile boolean raceMissed; + private int created; + + RaceInput(boolean cancel) { + super(new CompareConfiguration()); + this.cancel = cancel; + setTitle("Race compare"); //$NON-NLS-1$ + } + + @Override + public void run(IProgressMonitor monitor) throws InterruptedException, InvocationTargetException { + super.run(monitor); // the compare result is set from here on + raceMissed = !creating.await(10, TimeUnit.SECONDS); + if (cancel) { + monitor.setCanceled(true); + } + } + + @Override + public Control createContents(Composite parent) { + if (++created == 1 && !raceMissed) { + creating.countDown(); // lets the job go on to its syncExec + DisplayUtils.pumpUntil(() -> Job.getJobManager().find(this).length == 0, + "the initialization job did not finish", TIMEOUT_MILLIS); //$NON-NLS-1$ + } + return new Composite(parent, SWT.NONE); + } + + @Override + protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + return new DiffNode(Differencer.CHANGE); + } + + @Override + public boolean canRunAsJob() { + return true; + } + } + + private static IWorkbenchPage activePage() { + return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + } + + private static IPreferenceStore store() { + return CompareUIPlugin.getDefault().getPreferenceStore(); + } +} diff --git a/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/CompareEditorReuseTest.java b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/CompareEditorReuseTest.java new file mode 100644 index 00000000000..9f2a2abf2d9 --- /dev/null +++ b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/CompareEditorReuseTest.java @@ -0,0 +1,155 @@ +/******************************************************************************* + * Copyright (c) 2026 Lars Vogel 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: + * Eclipse contributors - initial API and implementation + *******************************************************************************/ +package org.eclipse.compare.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; + +import org.eclipse.compare.CompareConfiguration; +import org.eclipse.compare.CompareEditorInput; +import org.eclipse.compare.CompareUI; +import org.eclipse.compare.internal.ComparePreferencePage; +import org.eclipse.compare.internal.CompareUIPlugin; +import org.eclipse.compare.structuremergeviewer.DiffNode; +import org.eclipse.compare.structuremergeviewer.Differencer; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.preference.IPreferenceStore; +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.ui.IEditorPart; +import org.eclipse.ui.IReusableEditor; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that the initialization job of a replaced input leaves a reused compare + * editor alone. + */ +public class CompareEditorReuseTest { + + private static final long TIMEOUT_MILLIS = 30_000; + + private boolean originalUnifiedDiff; + private final HeldInput first = new HeldInput(); + private final HeldInput second = new HeldInput(); + + @BeforeEach + void setUp() { + assertNotNull(Display.getCurrent(), "tests require a UI thread / Display"); //$NON-NLS-1$ + originalUnifiedDiff = store().getBoolean(ComparePreferencePage.UNIFIED_DIFF); + store().setValue(ComparePreferencePage.UNIFIED_DIFF, false); + } + + @AfterEach + void tearDown() { + first.release.countDown(); + second.release.countDown(); + store().setValue(ComparePreferencePage.UNIFIED_DIFF, originalUnifiedDiff); + activePage().closeAllEditors(false); + } + + @Test + void testCanceledJobOfReplacedInputDoesNotCloseEditor() { + CompareUI.openCompareEditor(first); + // A job that has not started yet is discarded by the cancel and never calls back + pumpUntil(() -> first.started, "the job of the first input did not start"); //$NON-NLS-1$ + IEditorPart editor = activePage().findEditor(first); + assertNotNull(editor, "no compare editor for the first input"); //$NON-NLS-1$ + + CompareUI.reuseCompareEditor(second, (IReusableEditor) editor); + pumpUntil(() -> second.started, "the job of the second input did not start"); //$NON-NLS-1$ + first.release.countDown(); + pumpUntil(() -> Job.getJobManager().find(first).length == 0, "the job of the first input did not finish"); //$NON-NLS-1$ + + assertSame(editor, activePage().findEditor(second), + "the canceled job of the replaced input must not close the editor"); //$NON-NLS-1$ + + second.release.countDown(); + pumpUntil(() -> second.created > 0, "the contents of the second input were not created"); //$NON-NLS-1$ + assertEquals(0, first.created, "contents created for the replaced input"); //$NON-NLS-1$ + assertEquals(1, second.created, "the contents of the second input must be created once"); //$NON-NLS-1$ + } + + /** An input whose job waits in {@code prepareInput} until it is released. */ + private static final class HeldInput extends CompareEditorInput { + + private final CountDownLatch release = new CountDownLatch(1); + private volatile boolean started; + private int created; + + HeldInput() { + super(new CompareConfiguration()); + setTitle("Held compare"); //$NON-NLS-1$ + } + + @Override + protected Object prepareInput(IProgressMonitor monitor) throws InterruptedException { + started = true; + release.await(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + return new DiffNode(Differencer.CHANGE); + } + + @Override + public Control createContents(Composite parent) { + created++; + return new Composite(parent, SWT.NONE); + } + + @Override + public boolean canRunAsJob() { + return true; + } + } + + private static void pumpUntil(BooleanSupplier condition, String failMessage) { + Display display = Display.getCurrent(); + long deadline = System.currentTimeMillis() + TIMEOUT_MILLIS; + // Keeps the loop waking so that the deadline holds while blocked in sleep() + Runnable[] wake = new Runnable[1]; + wake[0] = () -> display.timerExec(50, wake[0]); + display.timerExec(50, wake[0]); + try { + while (!condition.getAsBoolean()) { + if (System.currentTimeMillis() > deadline) { + fail(failMessage + " within " + TIMEOUT_MILLIS + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } + if (!display.readAndDispatch()) { + display.sleep(); + } + } + } finally { + display.timerExec(-1, wake[0]); + } + } + + private static IWorkbenchPage activePage() { + return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + } + + private static IPreferenceStore store() { + return CompareUIPlugin.getDefault().getPreferenceStore(); + } +} diff --git a/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/DisplayUtils.java b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/DisplayUtils.java new file mode 100644 index 00000000000..0ca953e7c0a --- /dev/null +++ b/team/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/DisplayUtils.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * Copyright (c) 2026 Lars Vogel 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: + * Eclipse contributors - initial API and implementation + *******************************************************************************/ +package org.eclipse.compare.tests; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.function.BooleanSupplier; + +import org.eclipse.swt.widgets.Display; + +/** + * Helpers for tests that need to drive the SWT event loop. + */ +public class DisplayUtils { + + /** + * Runs the event loop of the current display until the given condition holds, + * and fails the test if it does not hold within the timeout. + *

+ * Must be called on the UI thread. + *

+ * + * @param condition checked before each dispatch; the method returns as soon + * as it yields {@code true} + * @param failMessage start of the failure message if the timeout expires + * @param timeoutMillis time in milliseconds after which the test fails + */ + public static void pumpUntil(BooleanSupplier condition, String failMessage, long timeoutMillis) { + Display display = Display.getCurrent(); + long deadline = System.currentTimeMillis() + timeoutMillis; + // A self-rescheduling timer keeps the loop waking so the deadline is + // enforced even while blocked in Display.sleep(). + Runnable[] wake = new Runnable[1]; + wake[0] = () -> display.timerExec(50, wake[0]); + display.timerExec(50, wake[0]); + try { + while (!condition.getAsBoolean()) { + if (System.currentTimeMillis() > deadline) { + fail(failMessage + " within " + timeoutMillis + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } + if (!display.readAndDispatch()) { + display.sleep(); + } + } + } finally { + display.timerExec(-1, wake[0]); + } + } + + /** + * Dispatches all events currently queued on the current display and returns + * once the queue is empty. Unlike {@link #pumpUntil}, it does not wait for + * anything that has not been queued yet. + *

+ * Must be called on the UI thread. + *

+ */ + public static void processQueuedEvents() { + Display display = Display.getCurrent(); + while (display.readAndDispatch()) { + // drain the event queue + } + } +} diff --git a/team/tests/org.eclipse.team.tests.core/build.properties b/team/tests/org.eclipse.team.tests.core/build.properties index 39ddad70e88..6d75953d4e0 100644 --- a/team/tests/org.eclipse.team.tests.core/build.properties +++ b/team/tests/org.eclipse.team.tests.core/build.properties @@ -19,7 +19,8 @@ bin.includes = about.html,\ .,\ test.xml,\ META-INF/,\ - plugin.properties + plugin.properties,\ + testdata/ # Maven/Tycho pom model adjustments. The bundle name does not end in .tests, so # the pomless build would treat it as a plain bundle and never run its tests. diff --git a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffCodeMiningProviderTest.java b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffCodeMiningProviderTest.java index e36ffb98a35..6769e22aadb 100644 --- a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffCodeMiningProviderTest.java +++ b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffCodeMiningProviderTest.java @@ -18,11 +18,14 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; 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 static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; @@ -42,9 +45,11 @@ import org.eclipse.compare.unifieddiff.internal.UnifiedDiffCodeMiningProvider.UnifiedDiffLineHeaderCodeMining; import org.eclipse.compare.unifieddiff.internal.UnifiedDiffManager; import org.eclipse.compare.unifieddiff.internal.UnifiedDiffManager.UnifiedDiff; +import org.eclipse.core.runtime.ILogListener; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Platform; import org.eclipse.jface.internal.text.codemining.CodeMiningLineHeaderAnnotation; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; @@ -86,6 +91,7 @@ import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; @@ -1163,6 +1169,501 @@ public void testHeaderMiningRendersTrailingBlankLineDelimiters() throws Exceptio } } + @Test + public void testTallerEmojiMiningReservesSpaceAboveNumberedSourceLines() throws Exception { + String editorSource = numberedLines(50).get(); + String comparedSource = editorSource.replace("line 9\n", "new replacement\n") + .replace("line 41\nline 42\nline 43\n", "new section\n" + "\tšŸ˜€ new entry\n".repeat(25)); + switchToDocument(new Document(editorSource)); + Font font = emojiTestFont(9); + viewer.getTextWidget().setFont(font); + viewer.getTextWidget().setLineSpacing(3); + viewer.getTextWidget().setSize(800, 1200); + installCodeMinings(provider); + Image image = new Image(display, 800, 1200); + GC gc = new GC(image); + try { + assumeTrue(emojiLineHeight(font) > viewer.getTextWidget().getLineHeight(), + "the available font must render emoji taller than the editor's base line height"); + assertTrue(open(comparedSource).isOK()); + List diffs = UnifiedDiffManager.get(viewer); + assertThat(diffs).hasSize(2); + waitForAttachedMinings(diffs, allRegions().size()); + UnifiedDiff lastDiff = diffs.get(1); + CodeMiningLineHeaderAnnotation annotation = assertInstanceOf(CodeMiningLineHeaderAnnotation.class, + attachedMiningAnnotationOf(lastDiff)); + List minings = provide(); + ICodeMining mining = minings.stream().filter(candidate -> candidate instanceof UnifiedDiffLineHeaderCodeMining header + && header.getUnifiedDiff() == lastDiff).findFirst().orElseThrow(); + int widgetOffset = viewer.modelOffset2WidgetOffset(mining.getPosition().offset); + int reservedHeight = annotation.getHeight(gc); + int sourceY = viewer.getTextWidget().getLocationAtOffset(widgetOffset).y; + Point painted = mining.draw(gc, viewer.getTextWidget(), null, 0, sourceY - reservedHeight); + assertThat(reservedHeight).as("the framework reserves taller rows for emoji") + .isGreaterThan(26 * (viewer.getTextWidget().getLineHeight() + viewer.getTextWidget().getLineSpacing())); + assertEquals(reservedHeight, painted.y, "the painted band stops above the numbered source line"); + assertEquals(reservedHeight, annotation.getHeight(), "layout without a GC reserves the same height"); + assertEquals(editorSource, document.get(), "rendering leaves the numbered source unchanged"); + minings.forEach(ICodeMining::dispose); + } finally { + gc.dispose(); + image.dispose(); + viewer.getTextWidget().setFont(null); + font.dispose(); + } + } + + @Test + public void testEmojiHeaderHeightMatchesClickOverlay() throws Exception { + assertEmojiMiningHeight(false, false, 3); + } + + @Test + public void testEmojiLayoutCacheRefreshesWhenFontOrLineSpacingChanges() throws Exception { + switchToDocument(new Document("old replacement")); + String label = "new replacement\nšŸ˜€\nnew final"; + List container = new ArrayList<>(); + UnifiedDiff diff = new UnifiedDiff(document, 0, document.getLength(), document.get(), new Document(label), + 0, label.length(), label, container, MODE); + container.add(diff); + Color color = display.getSystemColor(SWT.COLOR_GREEN); + Font small = emojiTestFont(9); + Font large = emojiTestFont(14); + List minings = List.of( + new UnifiedDiffLineHeaderCodeMining(new Position(0, document.getLength()), provider, diff, 4, + color, color, null, viewer), + new UnifiedDiffFooterCodeMining(document, provider, diff, 4, color, color, null, viewer)); + Image image = new Image(display, 500, 300); + GC gc = new GC(image); + try { + for (ICodeMining mining : minings) { + viewer.getTextWidget().setFont(small); + viewer.getTextWidget().setLineSpacing(0); + String initial = mining.getLabel(); + Point initialExtent = mining.draw(gc, viewer.getTextWidget(), null, 0, 0); + assertSame(initial, mining.getLabel(), "painting reuses the measured reservation label"); + assertSame(initial, CompletableFuture.supplyAsync(mining::getLabel).get(10, TimeUnit.SECONDS), + "background callers use cached metrics without touching SWT"); + viewer.getTextWidget().setLineSpacing(3); + String spaced = mining.getLabel(); + assertNotSame(initial, spaced, "line spacing invalidates reservation rounding"); + Point spacedExtent = mining.draw(gc, viewer.getTextWidget(), null, 0, 0); + assertThat(spacedExtent.y).isGreaterThanOrEqualTo(initialExtent.y); + assertSame(spaced, mining.getLabel()); + viewer.getTextWidget().setFont(large); + String resized = mining.getLabel(); + assertNotSame(spaced, resized, "font changes invalidate glyph metrics"); + Point resizedExtent = mining.draw(gc, viewer.getTextWidget(), null, 0, 0); + assertThat(resizedExtent.y).isGreaterThanOrEqualTo(spacedExtent.y); + assertSame(resized, mining.getLabel()); + mining.dispose(); + assertSame(resized, mining.getLabel(), "disposed minings do not allocate new layout resources"); + } + } finally { + minings.forEach(ICodeMining::dispose); + gc.dispose(); + image.dispose(); + viewer.getTextWidget().setFont(null); + small.dispose(); + large.dispose(); + } + } + + @Test + public void testEmojiMiningLabelAndClickIgnoreUnavailableWidget() throws Exception { + class ClosingViewer extends ProjectionViewer { + boolean unavailable; + + ClosingViewer() { + super(shell, null, null, false, SWT.V_SCROLL); + } + + @Override + public StyledText getTextWidget() { + return unavailable ? null : super.getTextWidget(); + } + } + ClosingViewer closingViewer = new ClosingViewer(); + closingViewer.setDocument(document); + String label = "šŸ˜€ new replacement"; + List container = new ArrayList<>(); + UnifiedDiff diff = new UnifiedDiff(document, 0, document.getLength(), document.get(), new Document(label), + 0, label.length(), label, container, MODE); + container.add(diff); + Color color = display.getSystemColor(SWT.COLOR_GREEN); + List minings = List.of( + new UnifiedDiffLineHeaderCodeMining(new Position(0, document.getLength()), provider, diff, 4, + color, color, null, closingViewer), + new UnifiedDiffFooterCodeMining(document, provider, diff, 4, color, color, null, closingViewer)); + StyledText textWidget = closingViewer.getTextWidget(); + GC gc = new GC(textWidget); + try { + for (ICodeMining mining : minings) { + String cached = mining.getLabel(); + mining.draw(gc, textWidget, null, 0, 0); + closingViewer.unavailable = true; + assertSame(cached, mining.getLabel()); + mining.getAction().accept(null); + assertEquals(0, textWidget.getChildren().length, "a stale click does not create an overlay"); + closingViewer.unavailable = false; + } + gc.dispose(); + textWidget.dispose(); + for (ICodeMining mining : minings) { + assertNotNull(mining.getLabel()); + mining.getAction().accept(null); + } + } finally { + closingViewer.unavailable = false; + minings.forEach(ICodeMining::dispose); + if (!gc.isDisposed()) { + gc.dispose(); + } + } + } + + @Test + public void testEmojiMiningUsesPlainLayoutWhenSyntaxHighlightingHasBadLocations() throws Exception { + ProjectionViewer failingViewer = new ProjectionViewer(shell, null, null, false, SWT.V_SCROLL) { + @Override + public List computeStyleRanges(IDocument syntaxDocument, IRegion region) throws BadLocationException { + throw new BadLocationException(); + } + }; + failingViewer.setDocument(document); + String label = "šŸ˜€ new replacement\nnew final"; + List container = new ArrayList<>(); + UnifiedDiff diff = new UnifiedDiff(document, 7, document.getLength() - 7, document.get(7, document.getLength() - 7), + new Document(label), 0, label.length(), label, container, MODE); + container.add(diff); + Color color = display.getSystemColor(SWT.COLOR_GREEN); + List minings = List.of( + new UnifiedDiffLineHeaderCodeMining(new Position(7, document.getLength() - 7), provider, diff, 4, + color, color, null, failingViewer), + new UnifiedDiffFooterCodeMining(document, provider, diff, 4, color, color, null, failingViewer)); + document.set(""); + GC gc = new GC(failingViewer.getTextWidget()); + try { + for (ICodeMining mining : minings) { + assertNotNull(mining.getLabel(), "stale offsets and failed highlighting leave a usable plain label"); + Point extent = mining.draw(gc, failingViewer.getTextWidget(), null, 0, 0); + assertThat(extent.y).isGreaterThanOrEqualTo(2 * failingViewer.getTextWidget().getLineHeight()); + } + } finally { + minings.forEach(ICodeMining::dispose); + gc.dispose(); + } + } + + @Test + public void testHighlightingRuntimeFailuresAreLoggedOnceAndUseCachedPlainLayout() throws Exception { + for (boolean invalidPresentation : new boolean[] { false, true }) { + List failures = new ArrayList<>(); + int[] calls = { 0 }; + RuntimeException failure = new IllegalArgumentException("synthetic highlighting failure"); + ILogListener listener = (status, unused) -> { + if (status.getException() == failure || status.getException() instanceof IllegalStateException + && "Invalid presentation with style range starting before source offset".equals(status.getMessage())) { + failures.add(status); + } + }; + ProjectionViewer failingViewer = new ProjectionViewer(shell, null, null, false, SWT.V_SCROLL) { + @Override + public List computeStyleRanges(IDocument syntaxDocument, IRegion region) { + calls[0]++; + if (invalidPresentation) { + return List.of(new StyleRange(region.getOffset() - 1, 1, null, null)); + } + throw failure; + } + }; + failingViewer.setDocument(document); + String label = "šŸ˜€ new replacement"; + List container = new ArrayList<>(); + UnifiedDiff diff = new UnifiedDiff(document, 7, document.getLength() - 7, document.get(7, document.getLength() - 7), + new Document(label), 0, label.length(), label, container, MODE); + container.add(diff); + Color color = display.getSystemColor(SWT.COLOR_GREEN); + List minings = List.of( + new UnifiedDiffLineHeaderCodeMining(new Position(7, document.getLength() - 7), provider, diff, 4, + color, color, null, failingViewer), + new UnifiedDiffFooterCodeMining(document, provider, diff, 4, color, color, null, failingViewer)); + GC gc = new GC(failingViewer.getTextWidget()); + Platform.addLogListener(listener); + try { + for (ICodeMining mining : minings) { + String cached = mining.getLabel(); + assertNotNull(cached); + assertSame(cached, mining.getLabel()); + mining.draw(gc, failingViewer.getTextWidget(), null, 0, 0); + assertSame(cached, mining.getLabel(), "failed highlighting is cached rather than retried during painting"); + } + assertEquals(2, calls[0], "highlighting is attempted only once per mining"); + assertEquals(2, failures.size(), "each mining logs its failure once"); + } finally { + Platform.removeLogListener(listener); + minings.forEach(ICodeMining::dispose); + gc.dispose(); + } + } + } + + @Test + public void testDisposalDuringHighlightingCannotAllocateNewMiningFonts() throws Exception { + for (boolean footer : new boolean[] { false, true }) { + for (String operation : List.of("label", "rowHeight", "draw")) { + ICodeMining[] mining = new ICodeMining[1]; + int[] calls = { 0 }; + ProjectionViewer disposingViewer = new ProjectionViewer(shell, null, null, false, SWT.V_SCROLL) { + @Override + public List computeStyleRanges(IDocument syntaxDocument, IRegion region) { + calls[0]++; + mining[0].dispose(); + return List.of(new StyleRange(region.getOffset(), region.getLength(), null, null, SWT.BOLD)); + } + }; + disposingViewer.setDocument(document); + String label = "šŸ˜€ new replacement"; + List container = new ArrayList<>(); + UnifiedDiff diff = new UnifiedDiff(document, 0, document.getLength(), document.get(), new Document(label), + 0, label.length(), label, container, MODE); + container.add(diff); + Color color = display.getSystemColor(SWT.COLOR_GREEN); + mining[0] = footer + ? new UnifiedDiffFooterCodeMining(document, provider, diff, 4, color, color, null, disposingViewer) + : new UnifiedDiffLineHeaderCodeMining(new Position(0, document.getLength()), provider, diff, 4, + color, color, null, disposingViewer); + StyledText textWidget = disposingViewer.getTextWidget(); + GC gc = new GC(textWidget); + try { + switch (operation) { + case "label" -> assertNotNull(mining[0].getLabel()); + case "rowHeight" -> assertEquals(0, miningRowHeight(mining[0], textWidget)); + case "draw" -> mining[0].draw(gc, textWidget, null, 0, 0); + default -> fail("unknown operation"); + } + assertEquals(1, calls[0]); + assertNotNull(mining[0].getLabel()); + assertEquals(0, miningRowHeight(mining[0], textWidget)); + assertEquals(new Point(0, 0), mining[0].draw(gc, textWidget, null, 0, 0)); + assertEquals(1, calls[0], "disposed minings do not invoke highlighting again"); + var fonts = mining[0].getClass().getDeclaredField("styledFonts"); + fonts.setAccessible(true); + assertThat((Map) fonts.get(mining[0])).as("no fonts are allocated after disposal").isEmpty(); + assertNull(footer ? ((UnifiedDiffFooterCodeMining) mining[0]).getLastRectangle() + : ((UnifiedDiffLineHeaderCodeMining) mining[0]).getLastRectangle()); + } finally { + mining[0].dispose(); + gc.dispose(); + } + } + } + } + + private int miningRowHeight(ICodeMining mining, StyledText textWidget) { + return mining instanceof UnifiedDiffFooterCodeMining footer ? footer.getRowHeight(textWidget) + : ((UnifiedDiffLineHeaderCodeMining) mining).getRowHeight(textWidget); + } + + @Test + public void testRefreshingMiningsReplacesInstancesDisposedByTheFramework() throws Exception { + switchToDocument(new Document("old replacement\ncommon\n")); + installCodeMinings(provider); + assertTrue(open("šŸ˜€ new replacement\ncommon\n").isOK()); + List diffs = UnifiedDiffManager.get(viewer); + waitForAttachedMinings(diffs, allRegions().size()); + ICodeMining original = attachedMinings().get(0); + GC gc = new GC(viewer.getTextWidget()); + try { + assertThat(original.draw(gc, viewer.getTextWidget(), null, 0, 0).y).isGreaterThan(0); + viewer.updateCodeMinings(); + waitUntil(() -> !attachedMinings().isEmpty() && attachedMinings().get(0) != original, + () -> "a refresh replaces the framework-owned mining"); + ICodeMining replacement = attachedMinings().get(0); + assertEquals(new Point(0, 0), original.draw(gc, viewer.getTextWidget(), null, 0, 0), + "the framework disposed the original mining"); + assertThat(replacement.draw(gc, viewer.getTextWidget(), null, 0, 0).y).isGreaterThan(0); + viewer.updateCodeMinings(); + waitUntil(() -> !attachedMinings().isEmpty() && attachedMinings().get(0) != replacement, + () -> "a second refresh also leaves a live mining"); + assertThat(attachedMinings().get(0).draw(gc, viewer.getTextWidget(), null, 0, 0).y).isGreaterThan(0); + } finally { + gc.dispose(); + } + } + + @Test + public void testEmojiFooterHeightMatchesClickOverlay() throws Exception { + assertEmojiMiningHeight(true, false, 3); + } + + @Test + public void testPlainTextEmojiMiningHeightMatchesClickOverlay() throws Exception { + assertEmojiMiningHeight(false, true, 3); + } + + @Test + public void testEmojiMiningHeightMatchesClickOverlayWithoutLineSpacing() throws Exception { + assertEmojiMiningHeight(false, false, 0); + assertEmojiMiningHeight(true, false, 0); + } + + private void assertEmojiMiningHeight(boolean footer, boolean plainText, int lineSpacing) throws Exception { + if (plainText) { + viewer.unconfigure(); + viewer.configure(new SourceViewerConfiguration()); + } + switchToDocument(new Document("old replacement")); + String label = "new replacement\nšŸ˜€šŸ˜ŽāŒ\nnew final\n\n"; + List container = new ArrayList<>(); + UnifiedDiff diff = new UnifiedDiff(document, 0, document.getLength(), document.get(), new Document(label), + 0, label.length(), label, container, MODE); + container.add(diff); + int finalStart = label.indexOf("final"); + diff.detailedDiffs.add(new UnifiedDiff(document, 0, 0, "", new Document(label), finalStart, finalStart + 5, + "final", container, MODE)); + Font font = emojiTestFont(9); + Color deletionColor = new Color(display, 11, 22, 33); + Color detailedDiffColor = new Color(display, 44, 55, 66); + ICodeMining mining = footer + ? new UnifiedDiffFooterCodeMining(document, provider, diff, 4, deletionColor, detailedDiffColor, null, viewer) + : new UnifiedDiffLineHeaderCodeMining(new Position(0, document.getLength()), provider, diff, 4, + deletionColor, detailedDiffColor, null, viewer); + Image image = new Image(display, 500, 300); + GC gc = new GC(image); + try { + viewer.getTextWidget().setFont(font); + viewer.getTextWidget().setLineSpacing(lineSpacing); + int baseHeight = viewer.getTextWidget().getLineHeight(); + Point extent = mining.draw(gc, viewer.getTextWidget(), null, 0, 0); + assertEquals(extent, mining.draw(gc, viewer.getTextWidget(), null, 0, 0), "cached paint keeps its height"); + mining.getAction().accept(null); + StyledText overlay = (StyledText) viewer.getTextWidget().getChildren()[0]; + int rowHeight = extent.y / overlay.getLineCount(); + if (!plainText) { + int zoom = display.getPrimaryMonitor().getZoom(); + assertThat(lastColumnWithInBand(image.getImageData(zoom), detailedDiffColor.getRGB(), + 2 * rowHeight * zoom / 100, 3 * rowHeight * zoom / 100)) + .as("the detailed background follows the taller emoji row").isGreaterThanOrEqualTo(0); + } + assertEquals(4, overlay.getLineCount(), "the final blank row remains visible"); + rowHeight = overlay.getLocationAtOffset(overlay.getOffsetAtLine(1)).y; + assertThat(extent.y - overlay.getLinePixel(overlay.getLineCount())) + .as("only sub-row rounding space remains below the overlay") + .isGreaterThanOrEqualTo(0).isLessThan(baseHeight + lineSpacing); + for (int line = 0; line < overlay.getLineCount(); line++) { + assertEquals(line * rowHeight, overlay.getLocationAtOffset(overlay.getOffsetAtLine(line)).y, + "clicking does not change the row positions"); + } + assertThat(overlay.getLineHeight()).as("the uniform row accommodates the overlay's fallback glyphs") + .isLessThanOrEqualTo(rowHeight); + } finally { + for (Control child : viewer.getTextWidget().getChildren()) { + child.dispose(); + } + gc.dispose(); + image.dispose(); + mining.dispose(); + viewer.getTextWidget().setFont(null); + font.dispose(); + deletionColor.dispose(); + detailedDiffColor.dispose(); + } + } + + @Test + public void testSanitizedManualSourcesReserveEmojiMiningsAtSmallFontSizes() throws Exception { + String editorSource = manualFixture("editor"); + String comparedSource = manualFixture("compared"); + for (int fontSize : new int[] { 9, 14 }) { + assertManualSourcesReserveMinings(editorSource, comparedSource, fontSize); + } + } + + private Font emojiTestFont(int size) { + String family = display.getFontList("Monaco", true).length > 0 + ? "Monaco" : viewer.getTextWidget().getFont().getFontData()[0].getName(); + return new Font(display, family, size, SWT.NORMAL); + } + + private int emojiLineHeight(Font font) { + TextLayout layout = new TextLayout(display); + try { + layout.setFont(font); + var metrics = layout.getLineMetrics(0); + layout.setAscent(metrics.getAscent() + metrics.getLeading()); + layout.setDescent(metrics.getDescent()); + layout.setText("šŸ˜€"); + return layout.getLineBounds(0).height; + } finally { + layout.dispose(); + } + } + + private String manualFixture(String side) throws Exception { + try (var stream = getClass().getResourceAsStream("/testdata/unifieddiff-" + side + ".txt")) { + assertNotNull(stream, "the sanitized comparison fixture is packaged with the tests"); + String source = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + if (source.endsWith("\n")) { + source = source.substring(0, source.length() - 1); + } + return source.replace("\r\n", "\n").replace("\n", "\r\n"); + } + } + + private void assertManualSourcesReserveMinings(String editorSource, String comparedSource, int fontSize) throws Exception { + switchToDocument(new Document(editorSource)); + Font font = emojiTestFont(fontSize); + viewer.getTextWidget().setFont(font); + viewer.getTextWidget().setSize(800, 1200); + installCodeMinings(provider); + Image image = new Image(display, 800, 1200); + GC gc = new GC(image); + List minings = List.of(); + try { + IStatus status = UnifiedDiffManager.open(viewer, document, model, null, comparedSource, + UnifiedDiffMode.OVERLAY_MODE, null, null, null, null, MergeViewerContentProvider.LEFT_CONTRIBUTOR, + MergeViewerContentProvider.RIGHT_CONTRIBUTOR, true, -1); + assertTrue(status.isOK()); + List diffs = UnifiedDiffManager.get(viewer); + assertThat(diffs).hasSize(5); + assertEquals(editorSource, document.get(), "overlay mode must not change the editor source"); + waitForAttachedMinings(List.of(diffs.get(0), diffs.get(1), diffs.get(2), diffs.get(4)), 0); + minings = provide(); + for (ICodeMining mining : minings) { + if (!(mining instanceof UnifiedDiffLineHeaderCodeMining header)) { + continue; + } + CodeMiningLineHeaderAnnotation annotation = assertInstanceOf(CodeMiningLineHeaderAnnotation.class, + attachedMiningAnnotationOf(header.getUnifiedDiff())); + int widgetOffset = viewer.modelOffset2WidgetOffset(mining.getPosition().offset); + int widgetLine = viewer.getTextWidget().getLineAtOffset(widgetOffset); + int height = annotation.getHeight(gc); + viewer.getTextWidget().setLineVerticalIndent(widgetLine, height); + for (int topLine : new int[] { 0, widgetLine }) { + viewer.getTextWidget().setTopIndex(topLine); + int sourceY = viewer.getTextWidget().getLocationAtOffset(widgetOffset).y; + Point painted = mining.draw(gc, viewer.getTextWidget(), null, 0, sourceY - height); + assertEquals(height, painted.y, "the mining must end before its numbered source line"); + assertEquals(height, annotation.getHeight(), "reservation must also work without a GC"); + } + header.getAction().accept(null); + StyledText overlay = (StyledText) viewer.getTextWidget().getChildren()[0]; + assertEquals(header.getRawLabel(), overlay.getText(), "invisible layout rows must not enter copied text"); + assertThat(overlay.getLinePixel(overlay.getLineCount())).isLessThanOrEqualTo(height); + overlay.dispose(); + } + assertEquals(43, document.getLineOfOffset(diffs.get(3).leftStart) + 1, "the removed line stays at 43"); + assertEquals("", diffs.get(4).leftStr, "the final block is an insertion above the unchanged closing brace"); + } finally { + minings.forEach(ICodeMining::dispose); + gc.dispose(); + image.dispose(); + viewer.getTextWidget().setFont(null); + font.dispose(); + } + } + @Test public void testClickOverlayIsReadOnlyAndUsesWhitespaceCharacterPainter() throws Exception { switchToDocument(new Document("line 0\nline 1 changed")); diff --git a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffManagerTest.java b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffManagerTest.java index c03c6e3ad7c..d095dfe711b 100644 --- a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffManagerTest.java +++ b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffManagerTest.java @@ -368,6 +368,63 @@ public void testDelimiterCharactersUseTheirOwnDetailedRange() throws BadLocation } } + @Test + public void testDiffBackgroundFillsFullSourceRowsWithoutPaintingMiningIndent() throws BadLocationException { + for (UnifiedDiffMode mode : List.of(UnifiedDiffMode.REVERT_MODE, UnifiedDiffMode.OVERLAY_READ_ONLY_MODE)) { + setEditorContent("common\nold first\n\nold final\nunchanged"); + assertTrue(UnifiedDiff.create(editor, "common\nnew first\nnew middle\nnew final\nunchanged", mode) + .ignoreWhiteSpace(false).open().isOK()); + StyledText textWidget = viewer().getTextWidget(); + Point originalSize = textWidget.getSize(); + int originalSpacing = textWidget.getLineSpacing(); + textWidget.setSize(800, 600); + textWidget.setLineSpacingProvider(line -> 9 + line % 3); + textWidget.setLineVerticalIndent(2, 30); + Image image = new Image(textWidget.getDisplay(), 800, 600); + GC gc = new GC(image); + try { + gc.setFont(textWidget.getFont()); + gc.setBackground(textWidget.getBackground()); + gc.fillRectangle(image.getBounds()); + List listeners = textWidget.getTypedListeners(SWT.Paint, PaintListener.class) + .filter(listener -> listener.getClass().getEnclosingClass() == UnifiedDiffManager.class + && !listener.getClass().isAnonymousClass()).toList(); + assertThat(listeners).hasSize(1); + firePaint(textWidget, gc, listeners); + int zoom = textWidget.getMonitor().getZoom(); + ImageData pixels = image.getImageData(zoom); + int sampleX = 700 * zoom / 100; + int firstTop = textWidget.getLinePixel(1) + textWidget.getLineVerticalIndent(1); + RGB background = pixels.palette.getRGB(pixels.getPixel(sampleX, (firstTop + 2) * zoom / 100)); + assertFalse(background.equals(textWidget.getBackground().getRGB()), "the diff background is painted"); + for (int line = 1; line <= 3; line++) { + int top = textWidget.getLinePixel(line) + textWidget.getLineVerticalIndent(line); + int bottom = textWidget.getLinePixel(line + 1); + for (int pixelY = (top + 1) * zoom / 100; pixelY < (bottom - 1) * zoom / 100; pixelY++) { + assertEquals(background, pixels.palette.getRGB(pixels.getPixel(sampleX, pixelY)), + "the right-side background covers the entire row, including per-line spacing"); + } + int gapY = (bottom - 2) * zoom / 100; + assertEquals(background, pixels.palette.getRGB(pixels.getPixel(3 * zoom / 100, gapY)), + "extra height beneath the text is filled across the row"); + } + int miningY = (textWidget.getLinePixel(2) + 15) * zoom / 100; + assertEquals(textWidget.getBackground().getRGB(), pixels.palette.getRGB(pixels.getPixel(sampleX, miningY)), + "a separate mining row is excluded from the source background"); + assertEquals(textWidget.getBackground().getRGB(), + pixels.palette.getRGB(pixels.getPixel(3 * zoom / 100, miningY)), + "an empty source line does not fill the mining indent at the left edge"); + } finally { + gc.dispose(); + image.dispose(); + textWidget.setLineSpacingProvider(null); + textWidget.setLineSpacing(originalSpacing); + textWidget.setLineVerticalIndent(2, 0); + textWidget.setSize(originalSize); + } + } + } + private void assertDelimiterDetailedRange(UnifiedDiffMode mode, String delimiter, int start, int length) throws BadLocationException { IPreferenceStore store = EditorsUI.getPreferenceStore(); @@ -977,6 +1034,112 @@ private static void await(CountDownLatch latch, String message) { } } + @Test + public void testDisposeClearsDisplayAndAllowsReopening() throws Exception { + IAnnotationModel model = annotationModel(); + Annotation unrelated = new Annotation("test.annotation", false, "Keep this annotation"); //$NON-NLS-1$ //$NON-NLS-2$ + model.addAnnotation(unrelated, new Position(0, 4)); + var actionBars = editor.getEditorSite().getActionBars(); + var previousNext = actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId()); + var previousPrevious = actionBars.getGlobalActionHandler(ActionFactory.PREVIOUS.getId()); + StyledText tw = viewer().getTextWidget(); + for (UnifiedDiffMode mode : List.of(UnifiedDiffMode.OVERLAY_MODE, UnifiedDiffMode.OVERLAY_READ_ONLY_MODE, + UnifiedDiffMode.REVERT_MODE, UnifiedDiffMode.REPLACE_MODE)) { + setEditorContent(LEFT); + assertTrue(UnifiedDiff.create(editor, RIGHT, mode).open().isOK()); + assertNotSame(previousNext, actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId())); + assertNotNull(waitForLineHeaderAnnotation()); + firePaint(tw); + var diff = UnifiedDiffManager.get(viewer()).get(0); + int miningLine = tw.getLineAtOffset(lineHeaderMiningFor(diff).getPosition().offset); + assertTrue(tw.getLineVerticalIndent(miningLine) > 0, "the diff mining must reserve height before disposal"); + int diffLine = tw.getLineAtOffset(diff.leftStart); + fireMouseMove(tw, tw.getLinePixel(diffLine) + 2); + processEvents(); + Composite allToolbar = (Composite) tw.getData(TOOLBAR_COMPOSITE_FOR_ALL_DIFFS_KEY); + Composite oneToolbar = (Composite) tw.getData(TOOLBAR_COMPOSITE_FOR_ONE_DIFF_KEY); + assertNotNull(allToolbar); + assertNotNull(oneToolbar); + String contentBeforeDispose = document().get(); + boolean dirtyBeforeDispose = editor.isDirty(); + + UnifiedDiff.dispose(editor); + processEvents(); + firePaint(tw); + + assertNull(UnifiedDiffManager.get(viewer()), "disposal must release the manager state"); + assertTrue(allToolbar.isDisposed()); + assertTrue(oneToolbar.isDisposed()); + assertEquals(0, tw.getLineVerticalIndent(miningLine), "disposal must clear the mining's reserved height"); + assertEquals(contentBeforeDispose, document().get(), "disposal must preserve the current document"); + assertEquals(dirtyBeforeDispose, editor.isDirty(), "disposal must preserve the editor's dirty state"); + assertNotNull(model.getPosition(unrelated)); + assertEquals(List.of(unrelated), annotations(model, "test.annotation")); //$NON-NLS-1$ + assertEquals(0, countUnifiedDiffAnnotations(model)); + assertSame(previousNext, actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId())); + assertSame(previousPrevious, actionBars.getGlobalActionHandler(ActionFactory.PREVIOUS.getId())); + assertEquals(0, tw.getTypedListeners(SWT.Paint, PaintListener.class) + .filter(listener -> listener.getClass().getName() + .equals(UnifiedDiffManager.class.getName() + "$UnifiedDiffPaintListener")).count()); //$NON-NLS-1$ + assertEquals(0, tw.getTypedListeners(SWT.MouseMove, MouseMoveListener.class) + .filter(listener -> listener.getClass().getName() + .equals(UnifiedDiffManager.class.getName() + "$UnifiedDiffMouseMoveListener")).count()); //$NON-NLS-1$ + UnifiedDiff.dispose(editor); + } + } + + private static int countUnifiedDiffAnnotations(IAnnotationModel model) { + int count = 0; + for (Iterator it = model.getAnnotationIterator(); it.hasNext();) { + String type = it.next().getType(); + if (type != null && type.startsWith("org.eclipse.compare.unifieddiff.")) { //$NON-NLS-1$ + count++; + } + } + return count; + } + + @Test + public void testDisposePreventsPendingComputationFromRestoringDisplay() { + CountDownLatch disposed = new CountDownLatch(1); + AtomicBoolean firstComparison = new AtomicBoolean(true); + var actionBars = editor.getEditorSite().getActionBars(); + var previousNext = actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId()); + IStatus status = UnifiedDiff.create(editor, RIGHT, UnifiedDiffMode.REPLACE_MODE) + .tokenComparatorFactory(text -> { + if (firstComparison.compareAndSet(true, false)) { + Display.getDefault().asyncExec(() -> { + UnifiedDiff.dispose(editor); + disposed.countDown(); + }); + await(disposed, "disposal must run while the diff computation is blocked"); + } + return new CaseInsensitiveTokenComparator(text); + }).open(); + + assertTrue(status.isOK(), "the superseded open must return normally"); + assertEquals(0, disposed.getCount()); + processEvents(); + assertNull(UnifiedDiffManager.get(viewer())); + assertEquals(0, countUnifiedDiffAnnotations(annotationModel())); + assertNull(viewer().getTextWidget().getData(TOOLBAR_COMPOSITE_FOR_ALL_DIFFS_KEY)); + assertSame(previousNext, actionBars.getGlobalActionHandler(ActionFactory.NEXT.getId()), + "the superseded open must not reinstall navigation handlers"); + assertEquals(LEFT, document().get(), "the superseded replace-mode open must not change the document"); + } + + @Test + public void testDisposeWithoutDiffAndAfterClosingEditor() { + assertThrows(NullPointerException.class, () -> UnifiedDiff.dispose(null)); + UnifiedDiff.dispose(editor); + UnifiedDiff.dispose(editor); + assertEquals(LEFT, document().get()); + assertNull(UnifiedDiffManager.get(viewer())); + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(editor, false); + UnifiedDiff.dispose(editor); + editor = null; + } + /** * Opening a second diff on the same editor must replace the first one instead * of stacking annotations and diffs on top of each other. diff --git a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffShadowedFoldsTest.java b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffShadowedFoldsTest.java index d61b2972b7b..822a6e791a0 100644 --- a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffShadowedFoldsTest.java +++ b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/UnifiedDiffShadowedFoldsTest.java @@ -13,10 +13,12 @@ *******************************************************************************/ package org.eclipse.team.tests.ui; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -28,6 +30,7 @@ import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModel; @@ -37,6 +40,7 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.texteditor.ITextEditor; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -105,6 +109,34 @@ public void testAFoldComesBackWhenTheRegionIsExpanded() throws Exception { "the fold of the editor must be usable again once nothing hides its first line"); } + @Test + public void testDisposeRemovesDiffFoldsAndRestoresEditorFoldsWithoutProviderModel() throws Exception { + IDocument document = numberedLines(100); + ProjectionAnnotationModel projectionModel = openViewer(document); + ProjectionAnnotation foldOfTheEditor = addFoldOfTheEditor(projectionModel, document, 10, 70); + UnifiedDiffManager.foldUnchangedRegions(viewer, document, List.of(changeOnLine(document, 60)), MODE, 3); + assertFalse(isInModel(projectionModel, foldOfTheEditor)); + assertTrue(projectionModel.getAnnotationIterator().hasNext()); + // An editor with no provider model uses the model installed on its viewer. + ITextEditor editor = (ITextEditor) Proxy.newProxyInstance(ITextEditor.class.getClassLoader(), + new Class[] { ITextEditor.class }, (unused, method, args) -> { + if (method.getName().equals("getAdapter") && args[0] == ITextViewer.class) { //$NON-NLS-1$ + return viewer; + } + return null; + }); + String originalText = document.get(); + + org.eclipse.compare.unifieddiff.UnifiedDiff.dispose(editor); + waitForPendingWork(); + + assertTrue(isInModel(projectionModel, foldOfTheEditor), "disposal must restore the editor's own folds"); + var remaining = projectionModel.getAnnotationIterator(); + assertEquals(foldOfTheEditor, remaining.next()); + assertFalse(remaining.hasNext(), "only the editor's own fold must remain"); + assertEquals(originalText, document.get()); + } + /** * A fold whose first line stays visible works as it always did and must be left * alone. diff --git a/team/tests/org.eclipse.team.tests.core/testdata/unifieddiff-compared.txt b/team/tests/org.eclipse.team.tests.core/testdata/unifieddiff-compared.txt new file mode 100644 index 00000000000..c8d95afb6e5 --- /dev/null +++ b/team/tests/org.eclipse.team.tests.core/testdata/unifieddiff-compared.txt @@ -0,0 +1,192 @@ +@Scope:[#VIEW, #ENTITY, #ELEMENT] +@CompatibilityContract: { + c0: { + usageAllowed: true, + allowedChanges. annotation: [#ANY] + }, + c1: { + usageAllowed: false, + allowedChanges: { + annotation: [#NONE], + value: [#REMOVE] + } + } +} +@MetadataExtension.usageAllowed : true +@API. state: [ #RELEASED_FOR_KEY_USER_APPS ] +define annotation ExampleAnnotation { + + @Scope:[#VIEW, #EXTEND_VIEW, #ELEMENT] + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c0.usageAllowed: false + @CompatibilityContract.c1.usageAllowed: false + @CompatibilityContract.c2.usageAllowed: false + test_no_operation : Integer; + + @Scope:[#OPERATION] + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c0.usageAllowed: false + @CompatibilityContract.c1.usageAllowed: false + @CompatibilityContract.c2.usageAllowed: false + test_with_operation : Integer; + + @Scope:[#OPERATION] + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c0.usageAllowed: true + @CompatibilityContract.c1.usageAllowed: true + @CompatibilityContract.c2.usageAllowed: true + test_bool : Boolean; + + @CompatibilityContract.c0: { + usageAllowed: false + } + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c1.usageAllowed: false + @CompatibilityContract.c2.usageAllowed: false + test_var01 : Integer; + + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c0.usageAllowed: false + @CompatibilityContract.c1.usageAllowed: false + @CompatibilityContract.c2.usageAllowed: false + test_var02 : Integer; + + @Metadata.lifecycle.status: #DEPRECATED + @Metadata.lifecycle.successor: 'test_var02' + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c0.usageAllowed: true + @CompatibilityContract.c1.usageAllowed: false + @CompatibilityContract.c2.usageAllowed: false + test_deprecated : Integer; + + @Metadata.lifecycle.status: #DEPRECATED + @CompatibilityContract.c0.allowedChanges.value: [#ANY] + @CompatibilityContract.c0.usageAllowed: true + @CompatibilityContract.c1.usageAllowed: false + @CompatibilityContract.c2.usageAllowed: false + test_deprecated2 : Integer; + + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + string_default : String(40) default 'āŒšŸ˜€šŸ’»āŒšŸ˜€šŸ’»'; + + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + string_default2 : String(40) default '¶¶¶¶¶¶'; // + + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + test_anno : Boolean default true; + + @ExampleAnnotation.test_anno: true + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + test_anno2 : Boolean default true; + + @ExampleAnnotation.test_anno: true + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + test_enum01 : array of String(20) + enum { + ENUM01; + ENUM02; + ENUM03; + }; + + @Scope:[ #SIMPLE_TYPE] + test_enum02 : String(20) enum { + ENUM01; + ENUM02; + }; + + lonG_Path { + lonG_Path { + lonG_Path { + lonG_Path { + lonG_Path { + lonG_Path { + lonG_Path { + @ExampleAnnotation.test_anno: true + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + tEst_EnuM01 : array of String(20) + enum { + ENUM01; + ENUM02; + ENUM03; + }; + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + bool_With_Default : Boolean default true; + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + int_witH_defauLt : Integer default 1; + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + string_With_DefauLt : String(10) default '¶¶¶¶¶¶'; + }; + }; + }; + }; + @ExampleAnnotation.test_anno: true + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + tEst_EnuM01 : array of String(20) + enum { + ENUM01; + ENUM02; + ENUM03; + }; + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + bool_With_Default : Boolean default true; + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + int_witH_defauLt : Integer default 1; + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] + string_With_DefauLt : String(10) default 'default šŸ˜€'; + }; + }; + }; + + scope { + @Scope:[#ENTITY] + entity : Boolean; + @Scope:[#VIEW] + view : Boolean; + @Scope:[#TABLE_FUNCTION] + tableFunction : Boolean; + @Scope:[#EXTEND_VIEW] + extendView : Boolean; + @Scope:[#ROLE] + role : Boolean; + @Scope:[#ACCESSPOLICY] + accessPolicy : Boolean; + @Scope:[#ANNOTATION] + annotation : Boolean; + @Scope:[#ANNOTATE] + annotate : Boolean; + @Scope:[#SERVICE] + service : Boolean; + @Scope:[#CUSTOM_ENTITY] + customEntity : Boolean; + @Scope:[#PARAMETER] + parameter : Boolean; + @Scope:[#ELEMENT] + element : Boolean; + @Scope:[#ASPECT] + aspect : Boolean; + @Scope:[#PFCG_MAPPING] + pfcgMapping : Boolean; + @Scope:[#SIMPLE_TYPE] + simpleType : Boolean; + @Scope:[#HIERARCHY] + hierarchy : Boolean; + @Scope:[#ENUM_VALUE] + enumValue : Boolean; + @Scope:[#OPERATION] + operation : Boolean default true; + }; + + + languageDependentType { + withoutDefault { + @LanguageDependency.maxLength: 40 + string : String(60); + }; + withDefault { + string : String(250) default 'defaultText' ; + }; + withDefault2 { + value: Boolean default true; + }; + }; +} diff --git a/team/tests/org.eclipse.team.tests.core/testdata/unifieddiff-editor.txt b/team/tests/org.eclipse.team.tests.core/testdata/unifieddiff-editor.txt new file mode 100644 index 00000000000..614477c9c9e --- /dev/null +++ b/team/tests/org.eclipse.team.tests.core/testdata/unifieddiff-editor.txt @@ -0,0 +1,45 @@ +@Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE] +@CompatibilityContract: { + c0: { + usageAllowed: true, + allowedChanges. annotation: [#ANY] + }, + c1: { + usageAllowed: false, + allowedChanges: { + annotation: [#NONE], + value: [#REMOVE] + } + } +} +@MetadataExtension.usageAllowed : true +@API.state: [ #RELEASED_FOR_KEY_USER_APPS, #RELEASED_FOR_CLOUD_PLATFORM ] +@ExampleAnnotation.string_default: 'āŒšŸ˜€šŸ’»āŒšŸ˜€šŸ’»' +@OtherAnnotation.string_default: 'šŸ˜€šŸ˜€šŸ˜€āŒšŸ˜€šŸ’»' + @NestedAnnotation.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a: { + a: { + a: { + ab: [ #LONG_ENUM_NAME_12345 ] + } + } + } +define annotation NestedAnnotation { + //maximal possible path šŸ˜€ + a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { + a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { + a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { + a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { + a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { a { + a { a { a { a { a { a { a { a { a { a { + @Scope:[#VIEW, #ENTITY, #ELEMENT, #PARAMETER, #ANNOTATE, #ANNOTATION, #ENUM_VALUE, #SIMPLE_TYPE, #SERVICE, #OPERATION] + ab : array of String(20) enum { A; B; C; LONG_ENUM_NAME_12345; }; + }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; + }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; + }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; + }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; + }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; + }; }; }; }; }; }; }; }; }; }; + + no_scope: Integer ; + +} diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/control/impl/ITerminalControlForText.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/control/impl/ITerminalControlForText.java index 66e4a82b25b..01d765f5ea4 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/control/impl/ITerminalControlForText.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/control/impl/ITerminalControlForText.java @@ -54,6 +54,15 @@ public interface ITerminalControlForText { default void enableBracketedPaste(boolean enable) { } + /** + * Says a program is drawing a screen and has not finished (DEC mode 2026), so + * that the view does not show it half drawn. + * + * @param redrawing whether a screen is being drawn + */ + default void enableSynchronizedOutput(boolean redrawing) { + } + /** * Shows or hides the cursor at the program's request (DEC mode 25). * @@ -62,4 +71,22 @@ default void enableBracketedPaste(boolean enable) { default void showCursor(boolean show) { } + /** + * A program that asks for mouse events wants them instead of the terminal's own + * handling of the mouse, scrolling included. + * + * @param mode 1000 (buttons), 1002 (buttons and drags), 1003 (every move), or 0 for none + */ + default void enableMouseReporting(int mode) { + } + + /** + * SGR encoding (CSI ?1006) reports coordinates as decimal numbers instead of + * single bytes, which is what lets them go past column 223. + * + * @param enable whether to use it + */ + default void enableSgrMouseEncoding(boolean enable) { + } + } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100Emulator.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100Emulator.java index 832d6e628dd..1da50022663 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100Emulator.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100Emulator.java @@ -128,7 +128,12 @@ public class VT100Emulator implements ControlListener { private final int[] savedCursorColumn = new int[2]; /** whether a program asked for the alternate screen (47, 1047 or 1049) */ - private boolean alternateScreen; + private volatile boolean alternateScreen; + + /** @return whether a program shows the alternate screen, as full screen programs do */ + public boolean isAlternateScreen() { + return alternateScreen; + } /** * This field holds an array of StringBuffer objects, each of which is one @@ -204,6 +209,11 @@ public void setBufferLineLimit(int bufferLineLimit) { text.setBufferLineLimit(bufferLineLimit); } + /** @return the lines of the screen, which are the last lines of the text */ + public int getLines() { + return text.getLines(); + } + /** * @see IVT100EmulatorBackend#getBufferLineLimit() */ @@ -531,8 +541,11 @@ private void resetTerminal() { * without one. */ private void resetProgramModes() { + terminal.enableSynchronizedOutput(false); // or the screen would stay frozen terminal.showCursor(true); terminal.enableBracketedPaste(false); + terminal.enableMouseReporting(0); + terminal.enableSgrMouseEncoding(false); } /** @@ -1356,10 +1369,22 @@ private void setDecPrivateMode(int param) { // Save cursor, as ESC 7 does. saveCursor(); break; + case 2026: + // Synchronized output: the program begins a screen; show it once it is drawn. + terminal.enableSynchronizedOutput(true); + break; case 2004: // Bracketed paste: pasted text is wrapped so a program can tell it from typing. terminal.enableBracketedPaste(true); break; + case 1000: // report button press and release + case 1002: // also report drag + case 1003: // also report every move + terminal.enableMouseReporting(param); + break; + case 1006: + terminal.enableSgrMouseEncoding(true); + break; default: Logger.log("Unsupported command parameter: CSI ?" + param + 'h'); //$NON-NLS-1$ break; @@ -1397,9 +1422,20 @@ private void resetDecPrivateMode(int param) { // Restore cursor, as ESC 8 does. restoreCursor(); break; + case 2026: + terminal.enableSynchronizedOutput(false); + break; case 2004: terminal.enableBracketedPaste(false); break; + case 1000: + case 1002: + case 1003: + terminal.enableMouseReporting(0); + break; + case 1006: + terminal.enableSgrMouseEncoding(false); + break; default: Logger.log("Unsupported command parameter: CSI ?" + param + 'l'); //$NON-NLS-1$ break; diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackend.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackend.java index 41c28de6c10..ef31c851963 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackend.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackend.java @@ -14,6 +14,10 @@ *******************************************************************************/ package org.eclipse.terminal.internal.emulator; +import java.text.BreakIterator; +import java.text.Normalizer; + +import org.eclipse.terminal.internal.model.Cells; import org.eclipse.terminal.internal.model.CharWidth; import org.eclipse.terminal.internal.model.TerminalTextDataStore; import org.eclipse.terminal.model.ITerminalTextData; @@ -89,6 +93,29 @@ int getHeight() { * and next output requires line wrap */ private boolean fWrapPending; private boolean fInsertMode; + + /** a run of characters on its way into the cells, with their fillers */ + private char[] fRun = new char[0]; + + /** finds where a grapheme cluster ends, by the rules of UAX #29 */ + private final BreakIterator fGraphemes = BreakIterator.getCharacterInstance(); + + /** the first half of a surrogate pair that ended the last write, waiting for the second */ + private char fHighSurrogate; + + /** the cluster written last, which what comes next may still go onto */ + private String fLastText; + /** its first cell, and how many lines above the cursor it is: 1 after an immediate wrap */ + private int fLastColumn, fLastLinesBack; + /** + * How many times anything but writing text has been done (a cursor move, an + * erase, an edit, a scroll), and how many times when the cluster was written: + * only what comes straight after it in the text can go on with it. + */ + private int fMoves, fAfterMoves; + /** whether a wrap was pending right after it */ + private boolean fAfterPending; + private TerminalStyle fDefaultStyle; private TerminalStyle fStyle; int fLines; @@ -119,6 +146,7 @@ public VT100EmulatorBackend(ITerminalTextData terminal) { @Override public void enableAlternateScreen(boolean enable, boolean cursor) { + endCluster(); synchronized (fTerminal) { if (enable == (fNormalScreen != null)) { // Already on the screen being asked for. Programs do ask twice. @@ -237,6 +265,7 @@ public void setBufferLineLimit(int bufferLineLimit) { @Override public void clearAll() { + endCluster(); synchronized (fTerminal) { if (fNormalScreen != null) { // Clearing while a full screen program shows clears what is behind it as @@ -271,6 +300,7 @@ public void setDimensions(int lines, int cols) { if (lines == fLines && cols == fColumns) { return; // nothing to do } + fLastText = null; // its place is no longer what it was // relative cursor line int cl = getCursorLine(); int cc = getCursorColumn(); @@ -325,31 +355,28 @@ public int toAbsoluteLine(int line) { @Override public void insertCharacters(int charactersToInsert) { + endCluster(); if (charactersToInsert <= 0) { return; // nothing moves, so no wide character may be broken either } synchronized (fTerminal) { int line = toAbsoluteLine(fCursorLine); - int n = charactersToInsert; - // A wide character is not left half on the line: one the insertion splits - // is blanked whole, and so is one whose second cell it pushes off the end. - if (isSecondCell(line, fCursorColumn)) { - eraseCells(line, fCursorColumn - 1, fCursorColumn + 1); + int col = fCursorColumn; + int n = Math.min(charactersToInsert, fColumns - col); + // A character is not left half on the line: one the insertion splits is + // erased whole, and so is one whose second cell it pushes off the end. + eraseWhole(line, col, col); + if (col + n < fColumns) { + eraseWhole(line, fColumns - n, fColumns - n); } - if (fCursorColumn + n < fColumns && isSecondCell(line, fColumns - n)) { - eraseCells(line, fColumns - n - 1, fColumns - n); - } - for (int col = fColumns - 1; col >= fCursorColumn + n; col--) { - char c = fTerminal.getChar(line, col - n); - TerminalStyle style = fTerminal.getStyle(line, col - n); - fTerminal.setChar(line, col, c, style); - } - eraseCells(line, fCursorColumn, Math.min(fCursorColumn + n, fColumns)); + moveCells(line, col, fColumns - n, n); + eraseCells(line, col, col + n); } } @Override public void eraseToEndOfScreen() { + endCluster(); synchronized (fTerminal) { eraseLineToEnd(); for (int line = toAbsoluteLine(fCursorLine + 1); line < toAbsoluteLine(fLines); line++) { @@ -361,6 +388,7 @@ public void eraseToEndOfScreen() { @Override public void eraseToCursor() { + endCluster(); synchronized (fTerminal) { for (int line = toAbsoluteLine(0); line < toAbsoluteLine(fCursorLine); line++) { eraseLine(line); @@ -371,6 +399,7 @@ public void eraseToCursor() { @Override public void eraseAll() { + endCluster(); synchronized (fTerminal) { // What is on the screen goes into the history before it is erased, as in // Windows Terminal and VTE, so that clearing the screen does not destroy @@ -400,19 +429,12 @@ public void eraseAll() { } private boolean isBlank(int line) { - char[] chars = fTerminal.getChars(line); - if (chars != null) { - for (char c : chars) { - if (c != '\000' && c != ' ') { - return false; - } - } - } - return true; + return Cells.text(fTerminal, line, 0, fColumns).isBlank(); } @Override public void eraseLine() { + endCluster(); synchronized (fTerminal) { eraseLine(toAbsoluteLine(fCursorLine)); } @@ -428,6 +450,7 @@ private void eraseLine(int line) { @Override public void eraseLineToEnd() { + endCluster(); synchronized (fTerminal) { int line = toAbsoluteLine(fCursorLine); eraseWhole(line, fCursorColumn, fColumns); @@ -443,11 +466,11 @@ public void eraseLineToEnd() { * @return where the erase ended, past a wide character it took whole */ private int eraseWhole(int line, int from, int to) { - if (isSecondCell(line, from)) { - from--; + if (from < fColumns) { + from = Cells.start(fTerminal, line, from); } - if (isSecondCell(line, to)) { - to++; + if (to < fColumns && fTerminal.getCellWidth(line, to) == 0) { + to++; // the range ends inside a character: all of it goes } eraseCells(line, from, to); return to; @@ -485,6 +508,7 @@ private TerminalStyle eraseStyle() { @Override public void eraseLineToCursor() { + endCluster(); synchronized (fTerminal) { eraseWhole(toAbsoluteLine(fCursorLine), 0, fCursorColumn + 1); } @@ -492,6 +516,7 @@ public void eraseLineToCursor() { @Override public void insertLines(int n) { + endCluster(); synchronized (fTerminal) { if (!isCusorInScrollingRegion()) { return; @@ -505,25 +530,21 @@ public void insertLines(int n) { @Override public void deleteCharacters(int n) { + endCluster(); if (n <= 0) { return; // nothing moves, so no wide character may be broken either } synchronized (fTerminal) { int line = toAbsoluteLine(fCursorLine); - // deleting either half of a wide character leaves none of it - int end = Math.min(fCursorColumn + n, fColumns); - if (isSecondCell(line, fCursorColumn)) { - eraseCells(line, fCursorColumn - 1, fCursorColumn); - } - if (isSecondCell(line, end)) { - eraseCells(line, end, end + 1); - } - for (int col = fCursorColumn + n; col < fColumns; col++) { - char c = fTerminal.getChar(line, col); - TerminalStyle style = fTerminal.getStyle(line, col); - fTerminal.setChar(line, col - n, c, style); + int col = fCursorColumn; + n = Math.min(n, fColumns - col); + // deleting either half of a character leaves none of it + eraseWhole(line, col, col); + if (col + n < fColumns) { + eraseWhole(line, col + n, col + n); } - eraseCells(line, Math.max(fCursorColumn, fColumns - n), fColumns); + moveCells(line, col + n, fColumns, -n); + eraseCells(line, fColumns - n, fColumns); // what reached the margin moved off it, so the line ends before it (xterm) fTerminal.clearWrappedLine(line); } @@ -531,6 +552,7 @@ public void deleteCharacters(int n) { @Override public void deleteLines(int n) { + endCluster(); synchronized (fTerminal) { if (!isCusorInScrollingRegion()) { return; @@ -580,126 +602,402 @@ public void setStyle(TerminalStyle style) { @Override public void appendString(String buffer) { synchronized (fTerminal) { + // a reader may hand over the two halves of a surrogate pair apart + if (fHighSurrogate != 0) { + buffer = fHighSurrogate + buffer; + fHighSurrogate = 0; + } + if (!buffer.isEmpty() && Character.isHighSurrogate(buffer.charAt(buffer.length() - 1))) { + fHighSurrogate = buffer.charAt(buffer.length() - 1); + buffer = buffer.substring(0, buffer.length() - 1); + } + buffer = withoutHidden(buffer); char[] chars = buffer.toCharArray(); int line = toAbsoluteLine(fCursorLine); + boolean[] starts = clusterStarts(lastCluster() >= 0 ? fLastText : "", buffer); //$NON-NLS-1$ int i = 0; while (i < chars.length) { + int codePoint = Character.codePointAt(chars, i); + int charsUsed = Character.charCount(codePoint); + // What goes on with the cluster written last goes onto it, even when that is + // on the last cell with a wrap pending: it belongs there, not on the next line. + if ((!starts[i] || takesNoCell(codePoint)) && lastCluster() >= 0) { + line = goOn(Character.toString(codePoint)); + i += charsUsed; + continue; + } if (fWrapPending) { line = doLineWrap(); } int room = fColumns - fCursorColumn; - int col; - int n = narrowRun(chars, i, room); + int col = fCursorColumn; + // a run of characters of the BMP that are each a cluster of their own goes + // in at once: most text is nothing else + if (fRun.length < room) { + fRun = new char[room]; + } + int n = 0; + int cells = 0; + int width = 0; + while (i + n < chars.length && starts[i + n] && !Character.isSurrogate(chars[i + n])) { + width = CharWidth.of(chars[i + n]); + if (width == 0 || cells + width > room) { + break; + } + fRun[cells++] = chars[i + n++]; + if (width == 2) { + fRun[cells++] = '\000'; // the filler of a wide character + } + } if (n > 0) { if (fInsertMode) { // room on the line the run goes to, which a wrap may have changed - insertCharacters(n); + insertCharacters(cells); } - breakWideChar(line, fCursorColumn); - breakWideChar(line, fCursorColumn + n - 1); - fTerminal.setChars(line, fCursorColumn, chars, i, n, fStyle); - col = fCursorColumn + n; + breakAround(line, col, col + cells); + fTerminal.setChars(line, col, fRun, 0, cells, fStyle); i += n; - } else { - int codePoint = Character.codePointAt(chars, i); - int charsUsed = Character.charCount(codePoint); - int width = cellWidth(codePoint); - if (width == 0) { - // combining marks and other non-printing code points occupy no cell - i += charsUsed; - continue; - } - if (width > room) { - if (fCursorColumn > 0) { - // a wide character is never split across the right margin, - // and the cell it leaves unused there is erased - eraseCharacters(room); - line = doLineWrap(); - continue; - } - // terminal narrower than the character itself - width = room; - } - if (fInsertMode) { - insertCharacters(width); // room in cells, not characters - } - breakWideChar(line, fCursorColumn); - breakWideChar(line, fCursorColumn + width - 1); - if (charsUsed > width) { - // a one column terminal: the two chars of a surrogate pair cannot share its cell - fTerminal.setChar(line, fCursorColumn, '\uFFFD', fStyle); - } else if (charsUsed == 2) { - fTerminal.setChars(line, fCursorColumn, chars, i, 2, fStyle); - } else { - fTerminal.setChar(line, fCursorColumn, chars[i], fStyle); - if (width == 2) { - fTerminal.setChar(line, fCursorColumn + 1, '\000', fStyle); - } - } - col = fCursorColumn + width; - i += charsUsed; + char last = chars[i - 1]; + line = written(col + cells - CharWidth.of(last), String.valueOf(last), col + cells); + continue; } - // wrap needed? - if (col == fColumns) { - if (fVT100LineWrapping) { - // deferred line wrapping (eat_newline_glitch) - setCursorColumn(col - 1); - fWrapPending = true; - } else { + String text = Character.toString(codePoint); + cells = CharWidth.clusterCells(text); + if (cells > room) { + if (col > 0) { + // a wide character is never split across the right margin, + // and the cell it leaves unused there is erased + eraseWhole(line, col, fColumns); line = doLineWrap(); + continue; } - } else { - setCursorColumn(col); + cells = room; // a screen narrower than the character } + if (fInsertMode) { + insertCharacters(cells); // room in cells, not characters + } + put(line, col, text, cells, fStyle); + i += charsUsed; + line = written(col, text, col + cells); } } } /** - * A wide character owns two cells. Overwriting either one leaves the other - * stranded: a filler with nothing in front of it, or a glyph that now spills - * over whatever was written next to it. Blanking the partner before the write - * goes in keeps the line honest, which is what a terminal is expected to do. + * Where a grapheme cluster starts in the text, by the Unicode rules (UAX #29), + * the cluster written last going first as the context the text goes on from. + * + * @return for each char of the text, whether a cluster starts there */ - private void breakWideChar(int line, int col) { - if (col < 0 || col >= fColumns) { - return; + private boolean[] clusterStarts(String before, String text) { + boolean[] starts = new boolean[text.length()]; + int simple = before.isEmpty() || startsAlways(before.charAt(before.length() - 1)) ? 0 : -1; + while (simple >= 0 && simple < starts.length && startsAlways(text.charAt(simple))) { + starts[simple++] = true; + } + if (simple == starts.length) { + return starts; // most text is nothing else } - char c = fTerminal.getChar(line, col); - if (Character.isLowSurrogate(c)) { - // second cell of a character beyond the BMP - if (col > 0 && Character.isHighSurrogate(fTerminal.getChar(line, col - 1))) { - blank(line, col - 1); + fGraphemes.setText(before + text); + int b = fGraphemes.following(Math.max(before.length() - 1, 0)); + for (; b != BreakIterator.DONE; b = fGraphemes.next()) { + if (b >= before.length() && b - before.length() < starts.length) { + starts[b - before.length()] = true; } - } else if (Character.isHighSurrogate(c)) { - if (col + 1 < fColumns && Character.isLowSurrogate(fTerminal.getChar(line, col + 1))) { - blank(line, col + 1); + } + if (before.isEmpty() && starts.length > 0) { + starts[0] = true; + } + return starts; + } + + /** the longest cluster kept, in chars: the longest emoji sequence is 15 */ + private static final int MAX_CLUSTER = 32; + + /** + * The text without what is kept out of the cells: control characters, format + * characters no cluster needs (a zero width space, bidirectional marks and + * overrides), and what only hides text: tag characters outside the tag + * sequence of a flag, and a variation selector that does not follow a + * character it could vary. None is drawn, and in text copied from the + * terminal it could make a command read differently from how it runs, or + * carry text no one saw. Taken out before the clusters are found, so that + * where the text was split into writes makes no difference. + */ + private String withoutHidden(String text) { + int i = 0; + while (i < text.length() && CharWidth.of(text.charAt(i)) != 0 && !Character.isSurrogate(text.charAt(i))) { + i++; + } + if (i == text.length()) { + return text; // nothing that could be: most text + } + StringBuilder kept = new StringBuilder(text.length()).append(text, 0, i); + String before = i > 0 ? text.substring(0, i) : lastCluster() >= 0 ? fLastText : ""; //$NON-NLS-1$ + int last = before.isEmpty() ? -1 : before.codePointBefore(before.length()); + int tags = 0; // tag characters of a flag so far + for (int k = before.length(); k > 0 && isTagSpec(before.codePointBefore(k)); k -= 2) { + tags++; + } + for (; i < text.length(); i += Character.charCount(text.codePointAt(i))) { + int codePoint = text.codePointAt(i); + if (!isHidden(codePoint, last, tags)) { + kept.appendCodePoint(codePoint); + tags = isTagSpec(codePoint) ? tags + 1 : 0; + last = codePoint; } - } else if (c == '\000') { - if (col > 0 && CharWidth.of(fTerminal.getChar(line, col - 1)) == 2) { - blank(line, col - 1); + } + return kept.toString(); + } + + /** + * @param last the code point kept before it + * @param tags how many tag characters of a flag are right before it + * @return whether the code point is kept out of the cells + */ + private boolean isHidden(int codePoint, int last, int tags) { + int type = Character.getType(codePoint); + if (type == Character.CONTROL) { + return true; + } + if (isSelector(codePoint)) { + return last < 0 || CharWidth.cells(last) == 0; // it varies or joins the character before it + } + if (type != Character.FORMAT || codePoint == 0x200D || codePoint == 0x200C) { + return false; + } + if (isTagSpec(codePoint)) { + // a flag spelled with tags (UTS #51): the black flag, up to six letters or digits, a cancel tag + return !(last == 0x1F3F4 || tags > 0) || tags >= 6; + } + if (codePoint == 0xE007F) { + return tags == 0; + } + // a prefix sign goes with what follows it, but one is enough + String letter = "a"; //$NON-NLS-1$ + return breaks(Character.toString(codePoint), letter) + || last >= 0 && Character.getType(last) == Character.FORMAT && !breaks(Character.toString(last), letter); + } + + /** + * @return whether the code point is invisible and only says how to show the + * character before it: a variation selector, a Mongolian free variation + * selector (not U+180E between them, a format character); the combining + * grapheme joiner is not one, it keeps marks apart (Unicode 23.2) + */ + private static boolean isSelector(int codePoint) { + return codePoint >= 0xFE00 && codePoint <= 0xFE0F || codePoint >= 0xE0100 && codePoint <= 0xE01EF + || codePoint >= 0x180B && codePoint <= 0x180D || codePoint == 0x180F; + } + + /** @return whether the code point is a tag letter or digit, as in the tag sequence of a flag */ + private static boolean isTagSpec(int codePoint) { + return codePoint >= 0xE0030 && codePoint <= 0xE0039 || codePoint >= 0xE0061 && codePoint <= 0xE007A; + } + + /** per char of the BMP: 0 not asked yet, 1 a cluster of its own next to any other such, 2 not */ + private static final byte[] ALONE = new byte[0x10000]; + + /** + * Whether no rule of UAX #29 can join the char to the one before it or after it, + * when that one is such a char too: for a run of them, every char starts a + * cluster and the rules need not be run. Asked once of the rules themselves: + * nothing joins it after a letter or before one, after a Hangul syllable (a + * conjoining vowel or final would) or before one (a leading consonant would). + * Half of a surrogate pair and a control character are never such a char. + */ + private boolean startsAlways(int c) { + if (ALONE[c] == 0) { + String one = String.valueOf((char) c); + String letter = "a"; //$NON-NLS-1$ + String syllable = "\uac00"; //$NON-NLS-1$ + boolean alone = !Character.isSurrogate((char) c) && Character.getType(c) != Character.CONTROL + && Character.getType(c) != Character.FORMAT && breaks(letter, one) && breaks(one, letter) + && breaks(syllable, one) && breaks(one, syllable); + ALONE[c] = (byte) (alone ? 1 : 2); + } + return ALONE[c] == 1; + } + + /** Whatever is done but writing text: the cluster written last is done with. */ + private void endCluster() { + synchronized (fTerminal) { // a resize comes from the display thread + fMoves++; + } + } + + private boolean breaks(String first, String second) { + fGraphemes.setText(first + second); + return fGraphemes.isBoundary(first.length()); + } + + /** + * A cluster that starts with a code point that takes no cell, such as a zero + * width space or a mark the rules leave on its own, goes onto the cluster + * before it, which has a cell to keep it in. A prefix sign does not: it goes + * with what follows it. Decided by the code point alone, so that it does not + * matter where the text was split into writes. + */ + private boolean takesNoCell(int codePoint) { + if (CharWidth.cells(codePoint) > 0) { + return false; + } + String prefix = Character.toString(codePoint); + fGraphemes.setText(prefix + "a"); //$NON-NLS-1$ + return fGraphemes.isBoundary(prefix.length()); + } + + /** + * @return the line of the cluster written last, when what comes next can still go + * onto it: the cursor has not moved since, and the cells still hold it; -1 + * otherwise + */ + private int lastCluster() { + if (fLastText == null || fMoves != fAfterMoves || fWrapPending != fAfterPending + || fLastColumn >= fColumns) { + return -1; + } + int line = toAbsoluteLine(fCursorLine) - fLastLinesBack; + return line >= 0 && fLastText.equals(Cells.text(fTerminal, line, fLastColumn)) ? line : -1; + } + + /** + * Moves the cursor past a character just written, whose cells end before + * end, and remembers it for what may still go onto it. + * + * @return the line the cursor is now on + */ + private int written(int col, String text, int end) { + int line = advance(end); + fLastText = text; + fLastColumn = col; + fLastLinesBack = end == fColumns && !fVT100LineWrapping ? 1 : 0; + fAfterMoves = fMoves; + fAfterPending = fWrapPending; + return line; + } + + /** + * A grapheme cluster is what a reader takes for one character, however many code + * points it runs to: a letter with its accents, a Hangul syllable sent as jamo, + * an emoji with a skin tone or joined to others, a flag. The code point goes on + * with the cluster written last. The cluster takes the cells its code points + * would, but at least one and no more than two, summed as Windows Terminal sums + * them: a mark takes none, VS16 (emoji presentation) makes it wide. Grown wide, + * it takes the cell after it, or moves whole to the next line from the last one. + * + * @return the line the cursor is on + */ + private int goOn(String codePoint) { + if (fLastText.length() + codePoint.length() > MAX_CLUSTER) { + return toAbsoluteLine(fCursorLine); // a flood of marks must not grow one cell without bound + } + int line = lastCluster(); + int col = fLastColumn; + String text = fLastText + codePoint; + int cells = fTerminal.getCellWidth(line, col); + TerminalStyle style = fTerminal.getStyle(line, col); + if (CharWidth.clusterCells(text) <= cells || fColumns < 2) { + put(line, col, text, cells, style); + fLastText = text; // in the same cells, with the cursor where it was + return toAbsoluteLine(fCursorLine); + } + if (col + 2 > fColumns) { + // on the last cell: a wide character is never split across the margin, so + // the cluster moves whole to the next line, the cell it leaves erased + boolean pending = fLastLinesBack == 0; + eraseCells(line, col, col + 1); + line = pending ? doLineWrap() : toAbsoluteLine(fCursorLine); + col = 0; + if (fInsertMode) { + insertCharacters(2); + } + } else if (fInsertMode) { + insertCharacters(1); // the second cell is room made, not a cell taken from what follows + } + put(line, col, text, 2, style); + return written(col, text, col + 2); + } + + /** + * Writes a character, which may be a whole grapheme cluster, into its cells from + * col, the one way characters get into cells. The cell gets the + * character that is drawn: the first that takes a cell (not a prefix sign before + * it), composed with its marks (NFC) where they have a composed form; a second + * cell gets a filler, unless the character is a surrogate pair. The cluster, as + * the program wrote it, is kept beside the line whenever it is more than that. + * A character the write cuts in half is blanked whole. + */ + private void put(int line, int col, String text, int cells, TerminalStyle style) { + breakAround(line, col, col + cells); + int base = ' '; + String composed = text.length() > Character.charCount(text.codePointAt(0)) + ? Normalizer.normalize(text, Normalizer.Form.NFC) + : text; + for (int i = 0; i < composed.length(); i += Character.charCount(composed.codePointAt(i))) { + base = composed.codePointAt(i); + if (CharWidth.cells(base) > 0) { + break; } - } else if (CharWidth.of(c) == 2 && col + 1 < fColumns && fTerminal.getChar(line, col + 1) == '\000') { - blank(line, col + 1); + base = ' '; + } + boolean lone = base >= Character.MIN_SURROGATE && base <= Character.MAX_SURROGATE; // half a pair + char[] chars = lone || Character.charCount(base) > cells ? new char[] { '\uFFFD' } : Character.toChars(base); + String drawn = new String(chars); + if (cells == 2 && chars.length == 1) { + chars = new char[] { chars[0], '\000' }; // the filler, written with it + } + fTerminal.setChars(line, col, chars, 0, chars.length, style); + if (!text.equals(drawn)) { + fTerminal.setCluster(line, col, text); } } /** - * Cells a code point takes on the screen: its display width, except that a - * printable character beyond the BMP always takes two, since its two chars - * cannot share a cell. + * A character that the cells from from to to cut in + * half is blanked whole, as a terminal is expected to do: half of it cannot be + * shown. */ - private static int cellWidth(int codePoint) { - int width = CharWidth.of(codePoint); - return width != 0 && Character.charCount(codePoint) == 2 ? 2 : width; + private void breakAround(int line, int from, int to) { + int first = Cells.start(fTerminal, line, from); + int last = Cells.start(fTerminal, line, to - 1); + int end = Math.min(last + fTerminal.getCellWidth(line, last), fColumns); + for (int col = first; col < from; col++) { + blank(line, col); + } + for (int col = to; col < end; col++) { + blank(line, col); + } } /** - * @return whether the cell is the second of a wide character's two cells + * Moves the characters in the cells from from to to by + * shift cells, each written whole, with its cluster. */ - private boolean isSecondCell(int line, int col) { - return col > 0 && col < fColumns && CharWidth.isSecondCell( - String.valueOf(new char[] { fTerminal.getChar(line, col - 1), fTerminal.getChar(line, col) }), 1); + private void moveCells(int line, int from, int to, int shift) { + int n = to - from; + if (n <= 0) { + return; + } + // read all first: where they go may be where they were + char[] chars = new char[n]; + TerminalStyle[] styles = new TerminalStyle[n]; + String[] clusters = new String[n]; + int[] widths = new int[n]; + for (int i = 0; i < n; i++) { + chars[i] = fTerminal.getChar(line, from + i); + styles[i] = fTerminal.getStyle(line, from + i); + clusters[i] = fTerminal.getCluster(line, from + i); + widths[i] = fTerminal.getCellWidth(line, from + i); + } + for (int i = 0; i < n;) { + int width = i + widths[i] <= n ? Math.max(widths[i], 1) : 1; + fTerminal.setChars(line, from + shift + i, chars, i, width, styles[i]); + if (clusters[i] != null) { + fTerminal.setCluster(line, from + shift + i, clusters[i]); + } + i += width; + } } private void blank(int line, int col) { @@ -707,18 +1005,23 @@ private void blank(int line, int col) { } /** - * Length of the run of characters starting at offset that each - * occupy exactly one cell, so that they can be copied in one block. Capped at - * max cells. Zero when the run does not start with such a - * character, which sends the caller down the code point by code point path. + * Moves the cursor past what was just written, which ends before col. + * + * @return the line the cursor is now on */ - private static int narrowRun(char[] chars, int offset, int max) { - int n = 0; - while (n < max && offset + n < chars.length && !Character.isSurrogate(chars[offset + n]) - && CharWidth.of(chars[offset + n]) == 1) { - n++; + private int advance(int col) { + if (col == fColumns) { + if (fVT100LineWrapping) { + // deferred line wrapping (eat_newline_glitch) + setCursorColumn(col - 1); + fWrapPending = true; + } else { + return doLineWrap(); + } + } else { + setCursorColumn(col); } - return n; + return toAbsoluteLine(fCursorLine); } private int doLineWrap() { @@ -777,6 +1080,7 @@ private void scrollTopAnchoredRegionUpIntoHistory() { @Override public void processNewline() { + endCluster(); synchronized (fTerminal) { doNewline(); } @@ -793,6 +1097,7 @@ private void doReverseLineFeed() { @Override public void processReverseLineFeed() { + endCluster(); synchronized (fTerminal) { doReverseLineFeed(); } @@ -814,6 +1119,7 @@ public int getCursorColumn() { @Override public void setCursor(int targetLine, int targetColumn) { + endCluster(); synchronized (fTerminal) { setCursorLine(targetLine); setCursorColumn(targetColumn); @@ -830,6 +1136,7 @@ public void setCursorColumn(int targetColumn) { } fCursorColumn = targetColumn; fWrapPending = false; + endCluster(); // a cursor moved away and back no longer goes on with what it wrote // We make the assumption that nobody is changing the // terminal cursor except this class! // This assumption gives a huge performance improvement @@ -847,6 +1154,7 @@ public void setCursorLine(int targetLine) { } fCursorLine = targetLine; fWrapPending = false; + endCluster(); // We make the assumption that nobody is changing the // terminal cursor except this class! // This assumption gives a huge performance improvement @@ -894,6 +1202,7 @@ public void setScrollRegion(int top, int bottom) { @Override public void scrollUp(int n) { + endCluster(); assert n > 0; synchronized (fTerminal) { int line = toAbsoluteLine(fScrollRegion.getTopLine()); @@ -904,6 +1213,7 @@ public void scrollUp(int n) { @Override public void scrollDown(int n) { + endCluster(); assert n > 0; synchronized (fTerminal) { int line = toAbsoluteLine(fScrollRegion.getTopLine()); @@ -914,6 +1224,7 @@ public void scrollDown(int n) { @Override public void eraseCharacters(int n) { + endCluster(); if (n <= 0) { return; // nothing is erased, so no wide character may be broken either } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100TerminalControl.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100TerminalControl.java index 699f6a18630..843e5fc388d 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100TerminalControl.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100TerminalControl.java @@ -50,6 +50,7 @@ import java.io.OutputStream; import java.net.SocketException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.EnumMap; import java.util.Map; @@ -86,6 +87,7 @@ import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; @@ -114,6 +116,7 @@ import org.eclipse.terminal.internal.textcanvas.TextCanvas; import org.eclipse.terminal.internal.textcanvas.TextLineRenderer; import org.eclipse.terminal.model.ITerminalTextData; +import org.eclipse.terminal.model.ITerminalTextDataReadOnly; import org.eclipse.terminal.model.ITerminalTextDataSnapshot; import org.eclipse.terminal.model.TerminalColor; import org.eclipse.terminal.model.TerminalTextDataFactory; @@ -165,7 +168,15 @@ public class VT100TerminalControl implements ITerminalControlForText, ITerminalC private final EditActionAccelerators editActionAccelerators = new EditActionAccelerators(); - private boolean fApplicationCursorKeys; + // set by the reader job, read by the display thread on a key press + private volatile boolean fApplicationCursorKeys; + // set by the reader job, read by the display thread on the mouse + private volatile int fMouseMode; + private volatile boolean fSgrMouseEncoding; + // the cell a move was last reported in; reset by the reader job with the mode + private volatile int fLastReportedLine, fLastReportedColumn; + // lines the wheel moved that make no whole notch yet, up positive; reset with the mode + private volatile int fWheelLines; /** * Listens to changes in the preferences @@ -174,10 +185,11 @@ public class VT100TerminalControl implements ITerminalControlForText, ITerminalC private final IPropertyChangeListener fFontListener = this::updateFont; // set by the reader job, read by the display thread when pasting private volatile boolean fBracketedPaste; - // asked for by the program (DECTCEM); kept on the control, as the canvas is new after a move. - // Written with the model it is copied to under fCursorLock, so a model made during a move - // cannot miss a hide or show that the reader job makes meanwhile + // asked for by the program (DECTCEM, mode 2026); kept on the control, as the canvas is new + // after a move. Written with the model they are copied to under fCursorLock, so a model made + // during a move cannot miss a change that the reader job makes meanwhile private boolean fCursorHidden; + private boolean fSynchronizedOutput; private final Object fCursorLock = new Object(); private static final String PASTE_START = "\u001b[200~"; //$NON-NLS-1$ private static final String PASTE_END = "\u001b[201~"; //$NON-NLS-1$ @@ -468,6 +480,8 @@ public void disconnectTerminal() { } catch (InterruptedException e) { } } + // the screen a program was drawing when cut off is shown by the last poll + enableSynchronizedOutput(false); fPollingTextCanvasModel.stopPolling(); } @@ -559,14 +573,16 @@ private void showErrorMessage(String message) { protected void sendString(String string) { Logger.log(string); - try { - // Send the string after converting it to an array of bytes using the - // platform's default character encoding. - // - // TODO: Find a way to force this to use the ISO Latin-1 encoding. - // TODO: handle Encoding Errors in a better way + // Send the string after converting it to an array of bytes using the + // platform's default character encoding. + // + // TODO: handle Encoding Errors in a better way + sendBytes(string.getBytes(fCharset)); + } - getOutputStream().write(string.getBytes(fCharset)); + private void sendBytes(byte[] bytes) { + try { + getOutputStream().write(bytes); getOutputStream().flush(); } catch (SocketException socketException) { displayTextInTerminal(socketException.getMessage()); @@ -603,7 +619,7 @@ private record XtermKey(int number, char last) { Map.entry(SWT.ARROW_UP, new XtermKey(1, 'A')), Map.entry(SWT.ARROW_DOWN, new XtermKey(1, 'B')), Map.entry(SWT.ARROW_RIGHT, new XtermKey(1, 'C')), Map.entry(SWT.ARROW_LEFT, new XtermKey(1, 'D')), Map.entry(SWT.HOME, new XtermKey(1, 'H')), Map.entry(SWT.END, new XtermKey(1, 'F')), - Map.entry(SWT.INSERT, new XtermKey(2, '~')), + Map.entry(SWT.INSERT, new XtermKey(2, '~')), Map.entry((int) SWT.DEL, new XtermKey(3, '~')), Map.entry(SWT.PAGE_UP, new XtermKey(5, '~')), Map.entry(SWT.PAGE_DOWN, new XtermKey(6, '~')), Map.entry(SWT.F1, new XtermKey(1, 'P')), Map.entry(SWT.F2, new XtermKey(1, 'Q')), Map.entry(SWT.F3, new XtermKey(1, 'R')), Map.entry(SWT.F4, new XtermKey(1, 'S')), @@ -656,6 +672,44 @@ private static String bracketed(String text) { return PASTE_START + text.replace("\u001b", "").replace("\u009b", "") + PASTE_END; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } + /** + * What Ctrl alone with a key sends where SWT gives the key's own character: Space + * (NUL, the mark in Emacs), / (undo in Emacs) and the digits as xterm spells them, + * Ctrl+6 being vim's alternate file. Windows hands Ctrl+2 over as '2', so its NUL + * comes from here too. + * + * @param character the character SWT reports + * @return the control character, or the character itself + */ + public static char ctrlCharacter(char character) { + return switch (character) { + case ' ', '2' -> '\u0000'; + case '3' -> '\u001b'; + case '4' -> '\u001c'; + case '5' -> '\u001d'; + case '6' -> '\u001e'; + case '/', '7' -> '\u001f'; + case '8' -> '\u007f'; + default -> character; + }; + } + + /** + * SWT reports AltGr as Ctrl+Alt, with the character AltGr types. A real Ctrl+Alt + * gives a control character instead, which keeps its Alt as in xterm: ESC before + * it, so Ctrl+Alt+V reaches Codex as itself. + * + * @param stateMask the modifiers of the key event + * @param character the character SWT reports + * @return whether the character goes out with ESC before it + */ + public static boolean altSendsEscape(int stateMask, char character) { + if ((stateMask & SWT.ALT) == 0) { + return false; + } + return (stateMask & SWT.CTRL) == 0 || character < '\u0020' || character == '\u007f'; + } + protected void sendChar(char chKey, boolean altKeyPressed) { try { int byteToSend = chKey; @@ -869,12 +923,15 @@ protected void setupControls(Composite parent) { synchronized (fCursorLock) { PollingTextCanvasModel model = new PollingTextCanvasModel(snapshot); model.setCursorHidden(fCursorHidden); + model.setSynchronizedOutput(fSynchronizedOutput); fPollingTextCanvasModel = model; } fCtlText = new TextCanvas(fWndParent, fPollingTextCanvasModel, SWT.NONE, new TextLineRenderer(() -> fCtlText, fPollingTextCanvasModel)); fCtlText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + fCtlText.setMouseWheelHandler(this::reportMouseWheel); + fCtlText.setMouseButtonHandler(new MouseReporter()); fCtlText.addResizeHandler((lines, columns) -> fTerminalText.setDimensions(lines, columns)); fCtlText.addMouseListener(new MouseAdapter() { @Override @@ -895,6 +952,12 @@ protected void setupListeners() { fFocusListener = new TerminalFocusListener(); getCtlText().addKeyListener(fKeyHandler); + // Shift+Tab is a key for the program (back tab, see keyPressed), not a move of the focus out of the terminal + getCtlText().addTraverseListener(e -> { + if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS && (e.stateMask & SWT.MODIFIER_MASK) == SWT.SHIFT) { + e.doit = false; + } + }); getCtlText().addFocusListener(fFocusListener); } @@ -1063,7 +1126,7 @@ public void keyPressed(KeyEvent event) { // Control key is _not_ also pressed. This works around a bug in SWT where, // on European keyboards, the AltGr key being pressed appears to us as Control // + Alt being pressed simultaneously. - boolean altKeyPressed = (event.stateMask & SWT.ALT) != 0 && !ctrlKeyPressed; + boolean altKeyPressed = altSendsEscape(event.stateMask, character); //if (!isConnected()) { if (fState == TerminalState.CLOSED) { @@ -1079,9 +1142,10 @@ public void keyPressed(KeyEvent event) { return; } - // Manage the Del key - if (event.keyCode == 0x000007f) { - sendString("\u001b[3~"); //$NON-NLS-1$ + // Manage the Del key: with a modifier as xterm spells it, Ctrl+Delete deleting a word in Codex + if (event.keyCode == SWT.DEL) { + String modified = modifiedSpecialKey(SWT.DEL, modifierKeys); + sendString(modified != null ? modified : "\u001b[3~"); //$NON-NLS-1$ return; } @@ -1260,8 +1324,10 @@ public void keyPressed(KeyEvent event) { } // a key Eclipse has a binding for stays with it, as Alt+Right (Quick Access) - // and Alt+Up (Maximize) do in this terminal - if (escSeq == null && !hasKeyBinding(accelerator)) { + // and Alt+Up (Maximize) do in this terminal; on the alternate screen the + // arrows go to the full screen program, Codex and Claude Code using Alt+Up + boolean arrow = event.keyCode >= SWT.ARROW_UP && event.keyCode <= SWT.ARROW_RIGHT; + if (escSeq == null && (arrow && fTerminalText.isAlternateScreen() || !hasKeyBinding(accelerator))) { escSeq = modifiedSpecialKey(event.keyCode, modifierKeys); } @@ -1281,17 +1347,7 @@ public void keyPressed(KeyEvent event) { Logger.log("stateMask = " + event.stateMask); //$NON-NLS-1$ if (onlyCtrlKeyPressed) { - switch (character) { - case ' ': - // Send a NUL character -- many terminal emulators send NUL when - // Control-Space is pressed. This is used to set the mark in Emacs. - character = '\u0000'; - break; - case '/': - // Ctrl+/ is undo in emacs - character = '\u001f'; - break; - } + character = ctrlCharacter(character); } // see javadoc on convertBackspace for details @@ -1299,6 +1355,12 @@ public void keyPressed(KeyEvent event) { character = 0x7f; } + // Shift+Tab sends back tab (CSI Z), as xterm and Windows Terminal do: Claude Code switches modes with it + if (character == '\t' && modifierKeys == SWT.SHIFT) { + sendString("\u001b[Z"); //$NON-NLS-1$ + return; + } + //TODO: At this point, Ctrl+M sends the same as Ctrl+Shift+M . //This is undesired. Fixing this here might make the special Ctrl+Shift+C //handling unnecessary further up. @@ -1524,6 +1586,159 @@ public void enableApplicationCursorKeys(boolean enable) { fApplicationCursorKeys = enable; } + @Override + public void enableMouseReporting(int mode) { + fMouseMode = mode; + // what was told of the mouse before belongs to the program that asked then + fLastReportedLine = fLastReportedColumn = -1; + fWheelLines = 0; + } + + @Override + public void enableSgrMouseEncoding(boolean enable) { + fSgrMouseEncoding = enable; + } + + /** + * A wheel notch is reported as a press of button 64 or 65, which is how a + * terminal has always told a program that the wheel moved. Without this the + * wheel only ever scrolled the terminal's own view, and a program drawing its + * own scrollable screen never heard about it. + * + * @return whether the program was told, in which case the canvas stays put + */ + private boolean reportMouseWheel(int count, int modifiers, Point cell) { + Point at = onScreen(cell); + if (fMouseMode == 0 || count == 0 || at == null || !isConnected()) { + return false; + } + int button = (count > 0 ? 64 : 65) + modifiers; // up, down + // SWT counts lines; a notch is three of them, however the events split them, + // and what is left over counts toward the next one in the same direction. + if (Integer.signum(count) != Integer.signum(fWheelLines)) { + fWheelLines = 0; + } + fWheelLines += count; + int notches = Math.abs(fWheelLines) / 3; + fWheelLines %= 3; + if (notches == 0) { + return true; // the program's, told once the lines make a notch + } + StringBuilder report = new StringBuilder(); + for (int i = 0; i < notches; i++) { + report.append(mouseReport(button, at.y, at.x, true)); + } + sendBytes(mouseReportBytes(report.toString())); + return true; + } + + /** + * A press, a release and the pointer moving, told to the program the way a + * terminal has always told it, so that a program drawing its own screen can be + * clicked on. The terminal keeps the event when shift is held, which is how a + * selection is still made with the mouse while a program is listening for it. + */ + private class MouseReporter implements TextCanvas.IMouseButtonHandler { + @Override + public boolean mouseButton(int button, int modifiers, Point cell, boolean pressed) { + Point at = onScreen(cell); + // a release is reported wherever it happens: its press was + if (fMouseMode == 0 || button < 1 || button > 3 || (at == null && pressed) || !isConnected()) { + return false; + } + if (at == null) { + at = new Point(Math.max(1, Math.min(cell.x + 1, fPollingTextCanvasModel.getTerminalText().getWidth())), 1); + } + sendBytes(mouseReportBytes(mouseReport(button - 1 + modifiers, at.y, at.x, pressed))); + // the program now knows the pointer is here: a drag after this press, or + // after one that ended elsewhere, is reported from here on + fLastReportedLine = at.y; + fLastReportedColumn = at.x; + if (pressed) { + // the press takes the terminal's selection away (the canvas clears it once + // this returns): the view's copy must know, after that + fDisplay.asyncExec(fTerminalListener::setTerminalSelectionChanged); + } + return true; + } + + @Override + public boolean mouseMoved(int button, int modifiers, Point cell) { + Point at = onScreen(cell); + // 1002 is only interested while a button is held, 1003 in every move. + if (fMouseMode < 1002 || (fMouseMode == 1002 && button == 0) || at == null || !isConnected()) { + return false; + } + int line = at.y; + int column = at.x; + if (line == fLastReportedLine && column == fLastReportedColumn) { + return true; // still the same cell, and a cell is all the program is told + } + fLastReportedLine = line; + fLastReportedColumn = column; + sendBytes(mouseReportBytes(mouseReport((button == 0 ? 3 : button - 1) + 32 + modifiers, line, column, true))); + return true; + } + } + + /** + * @return where a cell of the text is on the screen a program sees, as column and + * line counted from one; null for a line of the history above it, which the + * user scrolled back to and the program knows nothing of. Below the last line + * (the strip under it) is the last line. + */ + private Point onScreen(Point cell) { + // the height of what the canvas shows, which the cell is from, not of the text the + // reader is writing ahead of it + ITerminalTextDataReadOnly shown = fPollingTextCanvasModel.getTerminalText(); + return onScreen(cell, shown.getHeight(), fTerminalText.getLines(), shown.getWidth()); + } + + /** + * Where a cell of the text is on the screen a program sees, as in {@link #onScreen(Point)}. + * + * @param height the lines of the text, history included + * @param screenLines the lines of the screen, the last of the text + * @param width the columns of the screen + */ + public static Point onScreen(Point cell, int height, int screenLines, int width) { + int line = cell.y - (height - screenLines) + 1; + if (line < 1) { + return null; + } + return new Point(Math.max(1, Math.min(cell.x + 1, width)), Math.min(line, screenLines)); + } + + private String mouseReport(int button, int line, int column, boolean pressed) { + return mouseReport(fSgrMouseEncoding, button, line, column, pressed); + } + + public static String mouseReport(boolean sgr, int button, int line, int column, boolean pressed) { + if (sgr) { + return "\u001b[<" + button + ';' + column + ';' + line + (pressed ? 'M' : 'm'); //$NON-NLS-1$ + } + // The older spelling has no room past column 223 and no way to say which + // button came up, so a release is reported as button 3, meaning "some button", + // with the keys held as in a press. Past 223 nothing is reported, as in xterm. + if (column > 223 || line > 223) { + return ""; //$NON-NLS-1$ + } + return "\u001b[M" + (char) (32 + (pressed ? button : button | 3)) + (char) (32 + column) //$NON-NLS-1$ + + (char) (32 + line); + } + + /** + * A report is bytes, not text: the older spelling puts a column or line past 95 + * in one byte of 128 or more, which the terminal's encoding (UTF-8, say) would + * turn into two. The SGR spelling is ASCII, the same either way. + * + * @param report a report as {@link #mouseReport(boolean, int, int, int, boolean)} spells it + * @return the bytes the program is sent + */ + public static byte[] mouseReportBytes(String report) { + return report.getBytes(StandardCharsets.ISO_8859_1); + } + @Override public void addMouseListener(ITerminalMouseListener listener) { getCtlText().addTerminalMouseListener(listener); @@ -1554,6 +1769,16 @@ public void showCursor(boolean show) { } } + @Override + public void enableSynchronizedOutput(boolean redrawing) { + synchronized (fCursorLock) { + fSynchronizedOutput = redrawing; + if (fPollingTextCanvasModel != null) { + fPollingTextCanvasModel.setSynchronizedOutput(redrawing); + } + } + } + @Override public void updateTerminalDimensions() { getTerminalText().adjustTerminalDimensions(); diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/Cells.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/Cells.java new file mode 100644 index 00000000000..ade0c01b578 --- /dev/null +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/Cells.java @@ -0,0 +1,171 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * All rights reserved. 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.terminal.internal.model; + +import java.text.Normalizer; + +import org.eclipse.terminal.model.ITerminalTextDataReadOnly; + +/** + * The characters of a line as its cells hold them, for everything that reads + * them: the selection, copying, the word under the pointer, drawing and the + * emulator. How many cells a character takes is kept by the text data + * ({@link ITerminalTextDataReadOnly#getCellWidth(int, int)}); this puts the + * character back together from them: a surrogate pair from its two cells, a + * grapheme cluster from beside the line + * ({@link ITerminalTextDataReadOnly#getCluster(int, int)}). + */ +public final class Cells { + + private Cells() { + } + + /** @return the first cell of the character the cell belongs to */ + public static int start(ITerminalTextDataReadOnly data, int line, int col) { + return col > 0 && data.getCellWidth(line, col) == 0 ? col - 1 : col; + } + + /** + * @return the character starting in the cell as the program wrote it: a whole + * grapheme cluster, both halves of a surrogate pair, or the one char (a + * replacement character for half a pair); "" for the second cell of a + * character and for a cell never written + */ + public static String text(ITerminalTextDataReadOnly data, int line, int col) { + return text(data, line, col, false); + } + + /** + * @param pastMargin whether the text goes on past the margin, where a narrowed + * screen keeps what it no longer shows: a pair the margin cuts is whole + * there + */ + private static String text(ITerminalTextDataReadOnly data, int line, int col, boolean pastMargin) { + if (data.getCellWidth(line, col) == 0) { + return ""; //$NON-NLS-1$ + } + String cluster = data.getCluster(line, col); + if (cluster != null) { + return cluster; + } + char c = charAt(data, line, col); + if (c == '\000') { + return ""; //$NON-NLS-1$ + } + if (Character.isHighSurrogate(c) && (data.getCellWidth(line, col) == 2 + || pastMargin && Character.isLowSurrogate(charAt(data, line, col + 1)))) { + return new String(new char[] { c, charAt(data, line, col + 1) }); + } + // half a pair, its other half cut off by a narrowed screen, is no character + return Character.isSurrogate(c) ? "\uFFFD" : String.valueOf(c); //$NON-NLS-1$ + } + + /** + * @return the char in the cell, also one a narrowed screen keeps past its margin + * (0 where there is none) + */ + private static char charAt(ITerminalTextDataReadOnly data, int line, int col) { + if (col < data.getWidth()) { + return data.getChar(line, col); + } + char[] chars = data.getChars(line); + return chars != null && col < chars.length ? chars[col] : 0; + } + + /** + * The text of a whole row, also what a narrowed screen keeps past its margin and + * shows again when it widens. + */ + public static String row(ITerminalTextDataReadOnly data, int line, int from) { + char[] chars = data.getChars(line); + int to = Math.max(data.getWidth(), chars == null ? 0 : chars.length); + return text(data, line, from, to, to > data.getWidth()); + } + + /** + * @return the character starting in the cell as it is drawn: a cluster with its + * marks composed where they have a composed form (NFC) + */ + public static String drawn(ITerminalTextDataReadOnly data, int line, int col) { + String text = text(data, line, col); + return text.length() > 1 ? Normalizer.normalize(text, Normalizer.Form.NFC) : text; + } + + /** + * The characters starting in the cells from from to + * to as they are drawn, a cell never written as a space: text that + * lines up cell for cell as long as each character is drawn as wide as the cells + * it takes. + * + * @param cells the chars of those cells, as + * {@link ITerminalTextDataReadOnly#getLineSegments(int, int, int)} + * has them + * @return the text, or null when a character the range starts or ends in is cut + * by it + */ + public static String drawn(ITerminalTextDataReadOnly data, int line, int from, String cells) { + if (data.isSimpleLine(line)) { + return cells.replace('\000', ' '); // the chars are the text + } + int to = from + cells.length(); + if (data.getCellWidth(line, from) == 0) { + return null; + } + StringBuilder drawn = new StringBuilder(cells.length()); + for (int col = from; col < to;) { + int width = Math.max(data.getCellWidth(line, col), 1); // always on, whatever the cells hold + if (col + width > to) { + return null; + } + String cluster = data.getCluster(line, col); + char c = cells.charAt(col - from); + if (cluster != null) { + drawn.append(Normalizer.normalize(cluster, Normalizer.Form.NFC)); + } else if (c == '\000') { + drawn.append(' '); + } else { + drawn.append(c); + if (width == 2 && Character.isHighSurrogate(c)) { + drawn.append(cells.charAt(col - from + 1)); + } + } + col += width; + } + return drawn.toString(); + } + + /** + * The text of the characters starting in the cells from from to + * to: a cell never written stands for a space, and those at the + * end of the range are left out. + */ + public static String text(ITerminalTextDataReadOnly data, int line, int from, int to) { + return text(data, line, from, to, false); + } + + private static String text(ITerminalTextDataReadOnly data, int line, int from, int to, boolean pastMargin) { + StringBuilder text = new StringBuilder(to - from); + int written = 0; + for (int col = from; col < to; col++) { + if (data.getCellWidth(line, col) == 0) { + continue; + } + String c = text(data, line, col, pastMargin); + if (c.isEmpty()) { + text.append(' '); + } else { + text.append(c); + written = text.length(); + } + } + text.setLength(written); + return text.toString(); + } +} diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/CharWidth.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/CharWidth.java index 5d7a511f76a..c95e518cb52 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/CharWidth.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/CharWidth.java @@ -62,45 +62,53 @@ private CharWidth() { 0x1FAEF, 0x1FAF8, 0x20000, 0x2FFFD, 0x30000, 0x3FFFD }; + /** the width of every character of the BMP, looked up rather than worked out for each one written */ + private static final byte[] BMP = new byte[0x10000]; + static { + for (int c = 0; c < BMP.length; c++) { + BMP[c] = (byte) compute(c); + } + } + /** @return 0 for combining and non-printing, 2 for East Asian W/F, else 1 */ public static int of(int codePoint) { + return codePoint < BMP.length ? BMP[codePoint] : compute(codePoint); + } + + private static int compute(int codePoint) { if (codePoint < 0x0080) { return codePoint < 0x20 || codePoint == 0x7F ? 0 : 1; } return isZeroWidth(codePoint) ? 0 : isWide(codePoint) ? 2 : 1; } - /** @return the total display width of {@code s} */ - public static int ofString(String s) { - return s.codePoints().map(CharWidth::of).sum(); + /** + * Cells a code point takes by itself: its width, beyond the BMP as well. A + * narrow one there, such as a mathematical letter, takes one cell, which keeps + * it as a cluster beside the line since its two chars cannot share the cell. + */ + public static int cells(int codePoint) { + return of(codePoint); } /** - * A {@code '\000'} means one of two things in a line of cells: the filler that - * a wide character puts in the cell it also covers, which carries no text of - * its own, or a cell that was never written or has been erased, which reads as - * a space. Only a wide character of the BMP leaves a filler: one beyond the - * BMP already covers its two cells with its two surrogates, so a null after it - * is an ordinary empty cell. - * - * @return whether the cell at {@code index} is the filler of the character - * before it + * Cells a grapheme cluster takes, summed as Windows Terminal sums them: what its + * code points take, VS16 (emoji presentation) counting as two, but at least one + * and no more than two. */ - public static boolean isFiller(CharSequence text, int index) { - if (index == 0 || text.charAt(index) != '\000') { - return false; + public static int clusterCells(String cluster) { + int cells = 0; + for (int i = 0; i < cluster.length();) { + int codePoint = cluster.codePointAt(i); + cells += codePoint == 0xFE0F ? 2 : cells(codePoint); + i += Character.charCount(codePoint); } - char before = text.charAt(index - 1); - return !Character.isSurrogate(before) && of(before) == 2; + return Math.max(1, Math.min(2, cells)); } - /** - * @return whether the cell at {@code index} is the second of the two cells of - * a wide character: its filler, or the low half of a surrogate pair - */ - public static boolean isSecondCell(CharSequence text, int index) { - return isFiller(text, index) || index > 0 && Character.isLowSurrogate(text.charAt(index)) - && Character.isHighSurrogate(text.charAt(index - 1)); + /** @return the total display width of {@code s} */ + public static int ofString(String s) { + return s.codePoints().map(CharWidth::of).sum(); } private static boolean isZeroWidth(int codePoint) { diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/SynchronizedTerminalTextData.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/SynchronizedTerminalTextData.java index 3de26a78cb4..b04b3b2b857 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/SynchronizedTerminalTextData.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/SynchronizedTerminalTextData.java @@ -162,4 +162,24 @@ synchronized public void setWrappedLine(int line) { synchronized public void clearWrappedLine(int line) { fData.clearWrappedLine(line); } + + @Override + synchronized public String getCluster(int line, int column) { + return fData.getCluster(line, column); + } + + @Override + synchronized public int getCellWidth(int line, int column) { + return fData.getCellWidth(line, column); + } + + @Override + synchronized public boolean isSimpleLine(int line) { + return fData.isSimpleLine(line); + } + + @Override + synchronized public void setCluster(int line, int column, String cluster) { + fData.setCluster(line, column, cluster); + } } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextData.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextData.java index b4cae86bc03..a385c387759 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextData.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextData.java @@ -348,4 +348,25 @@ public void clearWrappedLine(int line) { fData.clearWrappedLine(line); sendLineChangedToSnapshots(line); } + + @Override + public String getCluster(int line, int column) { + return fData.getCluster(line, column); + } + + @Override + public int getCellWidth(int line, int column) { + return fData.getCellWidth(line, column); + } + + @Override + public boolean isSimpleLine(int line) { + return fData.isSimpleLine(line); + } + + @Override + public void setCluster(int line, int column, String cluster) { + fData.setCluster(line, column, cluster); + sendLineChangedToSnapshots(line); + } } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataFastScroll.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataFastScroll.java index 4f42ed8386f..cbabcc607b7 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataFastScroll.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataFastScroll.java @@ -310,6 +310,30 @@ private void validateLineParameter(int line) { } } + @Override + public String getCluster(int line, int column) { + validateLineParameter(line); + return fData.getCluster(getPositionOfLine(line), column); + } + + @Override + public int getCellWidth(int line, int column) { + validateLineParameter(line); + return fData.getCellWidth(getPositionOfLine(line), column); + } + + @Override + public boolean isSimpleLine(int line) { + validateLineParameter(line); + return fData.isSimpleLine(getPositionOfLine(line)); + } + + @Override + public void setCluster(int line, int column, String cluster) { + validateLineParameter(line); + fData.setCluster(getPositionOfLine(line), column, cluster); + } + @Override public void setWrappedLine(int line) { validateLineParameter(line); diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataSnapshot.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataSnapshot.java index 2a1688523eb..bf9ef8c04bf 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataSnapshot.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataSnapshot.java @@ -318,4 +318,19 @@ public ITerminalTextData getTerminalTextData() { public boolean isWrappedLine(int line) { return fSnapshot.isWrappedLine(line); } + + @Override + public String getCluster(int line, int column) { + return fSnapshot.getCluster(line, column); + } + + @Override + public int getCellWidth(int line, int column) { + return fSnapshot.getCellWidth(line, column); + } + + @Override + public boolean isSimpleLine(int line) { + return fSnapshot.isSimpleLine(line); + } } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataStore.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataStore.java index d0f3ac2b398..4d5c03a7dad 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataStore.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataStore.java @@ -13,8 +13,11 @@ import java.lang.reflect.Array; import java.util.ArrayList; +import java.util.Arrays; import java.util.BitSet; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.eclipse.terminal.model.ITerminalTextData; import org.eclipse.terminal.model.ITerminalTextDataSnapshot; @@ -34,10 +37,24 @@ public class TerminalTextDataStore implements ITerminalTextData { private int fCursorColumn; private int fCursorLine; final private BitSet fWrappedLines = new BitSet(); + /** per line, how its characters lie in its cells; null for a line of one-cell characters only */ + private Layout[] fLayout; + + /** + * Where a character takes two cells, and the grapheme clusters, of one line: + * set when the characters are written, so that reading it is a lookup. + */ + private static final class Layout { + /** the cells that are the second of a character starting in the cell before */ + final BitSet second = new BitSet(); + /** the clusters, by first cell */ + final Map clusters = new HashMap<>(); + } public TerminalTextDataStore() { fChars = new char[0][]; fStyle = new TerminalStyle[0][]; + fLayout = new Layout[0]; fWidth = 0; } @@ -67,6 +84,7 @@ public void setDimensions(int height, int width) { } fStyle = (TerminalStyle[][]) resizeArray(fStyle, height); fChars = (char[][]) resizeArray(fChars, height); + fLayout = (Layout[]) resizeArray(fLayout, height); } // clean the new lines if (height > fHeight) { @@ -192,6 +210,7 @@ public void setChar(int line, int column, char c, TerminalStyle style) { ensureLineLength(line, column + 1); fChars[line][column] = c; fStyle[line][column] = style; + layOut(line, column, 1); } @Override @@ -206,9 +225,87 @@ public void setChars(int line, int column, char[] chars, int start, int len, Ter "Parameter 'column' must be >= 0 and less than 'width' (current value '" + fWidth + "')"); //$NON-NLS-1$ //$NON-NLS-2$ } ensureLineLength(line, column + len); - for (int i = 0; i < len; i++) { - fChars[line][column + i] = chars[i + start]; - fStyle[line][column + i] = style; + System.arraycopy(chars, start, fChars[line], column, len); + Arrays.fill(fStyle[line], column, column + len, style); + layOut(line, column, len); + } + + /** + * The cells from column on were just written: what took them before + * is gone, a character cut in half by the write is one cell, and a character + * written together with what fills its second cell (a wide character and a + * null, the two halves of a surrogate pair) takes two. + */ + private void layOut(int line, int column, int len) { + if (len == 0) { + return; // nothing written, so nothing laid out anew either + } + Layout layout = fLayout[line]; + char[] chars = fChars[line]; + int end = column + len; + if (layout == null) { + for (int col = column; col + 1 < end; col++) { + if (takesTwo(chars[col], chars[col + 1])) { + layout = fLayout[line] = new Layout(); + break; + } + } + if (layout == null) { + return; // the usual case: one cell each, as before + } + } + if (column > 0 && layout.second.get(column)) { + layout.clusters.remove(column - 1); // its second cell is gone + } + layout.second.clear(column, end + 1); + for (int col = column; col < end && !layout.clusters.isEmpty(); col++) { + layout.clusters.remove(col); + } + for (int col = column; col + 1 < end; col++) { + if (takesTwo(chars[col], chars[col + 1])) { + layout.second.set(++col); + } + } + } + + private static boolean takesTwo(char c, char next) { + return Character.isHighSurrogate(c) ? Character.isLowSurrogate(next) : next == '\000' && CharWidth.of(c) == 2; + } + + @Override + public int getCellWidth(int line, int column) { + Layout layout = fLayout[line]; + if (layout == null) { + return 1; + } + if (layout.second.get(column)) { + return 0; + } + return column + 1 < fWidth && layout.second.get(column + 1) ? 2 : 1; + } + + @Override + public String getCluster(int line, int column) { + Layout layout = fLayout[line]; + return layout == null || layout.clusters.isEmpty() ? null : layout.clusters.get(column); + } + + @Override + public boolean isSimpleLine(int line) { + Layout layout = fLayout[line]; + return layout == null || layout.second.isEmpty() && layout.clusters.isEmpty(); + } + + @Override + public void setCluster(int line, int column, String cluster) { + if (fLayout[line] == null) { + fLayout[line] = new Layout(); + } + Layout layout = fLayout[line]; + layout.clusters.put(column, cluster); + // a cluster written over two cells, its second one filled, takes both + if (column + 1 < fWidth && CharWidth.clusterCells(cluster) == 2 && !layout.second.get(column)) { + layout.second.set(column + 1); } } @@ -224,6 +321,7 @@ public void scroll(int startLine, int size, int shift) { for (int i = startLine; i < startLine + size + shift; i++) { fChars[i] = fChars[i - shift]; fStyle[i] = fStyle[i - shift]; + fLayout[i] = fLayout[i - shift]; fWrappedLines.set(i, fWrappedLines.get(i - shift)); } // then clean the opened lines @@ -233,6 +331,7 @@ public void scroll(int startLine, int size, int shift) { for (int i = startLine + size - 1; i >= startLine && i - shift >= 0; i--) { fChars[i] = fChars[i - shift]; fStyle[i] = fStyle[i - shift]; + fLayout[i] = fLayout[i - shift]; fWrappedLines.set(i, fWrappedLines.get(i - shift)); } cleanLines(startLine, Math.min(shift, getHeight() - startLine)); @@ -289,6 +388,7 @@ public void copy(ITerminalTextData source) { if (getHeight() != n) { fChars = new char[n][]; fStyle = new TerminalStyle[n][]; + fLayout = new Layout[n]; } for (int i = 0; i < n; i++) { copyLine(source, i, i); @@ -321,9 +421,27 @@ public void copyRange(ITerminalTextData source, int sourceStartLine, int destSta @Override public void copyLine(ITerminalTextData source, int sourceLine, int destLine) { - fChars[destLine] = source.getChars(sourceLine); + char[] chars = source.getChars(sourceLine); + // read before writing: the source may be this very line + Layout layout = null; + boolean simple = source.isSimpleLine(sourceLine); + for (int col = 0; !simple && chars != null && col < chars.length; col++) { + String cluster = source.getCluster(sourceLine, col); + int width = source.getCellWidth(sourceLine, col); + if (cluster != null || width == 0) { + if (layout == null) { + layout = new Layout(); + } + if (cluster != null) { + layout.clusters.put(col, cluster); + } + layout.second.set(col, width == 0); + } + } + fChars[destLine] = chars; fStyle[destLine] = source.getStyles(sourceLine); fWrappedLines.set(destLine, source.isWrappedLine(sourceLine)); + fLayout[destLine] = layout; } @Override @@ -346,6 +464,8 @@ public void setLine(int line, char[] chars, TerminalStyle[] styles) { fChars[line] = chars.clone(); fStyle[line] = styles.clone(); fWrappedLines.clear(line); + fLayout[line] = null; + layOut(line, 0, chars.length); } @Override @@ -363,6 +483,7 @@ public void cleanLine(int line) { fChars[line] = null; fStyle[line] = null; fWrappedLines.clear(line); + fLayout[line] = null; } @Override diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataWindow.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataWindow.java index 92149232a88..713ff397c3b 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataWindow.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/model/TerminalTextDataWindow.java @@ -261,6 +261,28 @@ public boolean isWrappedLine(int line) { return false; } + @Override + public String getCluster(int line, int column) { + return isInWindow(line) ? fData.getCluster(line - fWindowStartLine, column) : null; + } + + @Override + public int getCellWidth(int line, int column) { + return isInWindow(line) ? fData.getCellWidth(line - fWindowStartLine, column) : 1; + } + + @Override + public boolean isSimpleLine(int line) { + return !isInWindow(line) || fData.isSimpleLine(line - fWindowStartLine); + } + + @Override + public void setCluster(int line, int column, String cluster) { + if (isInWindow(line)) { + fData.setCluster(line - fWindowStartLine, column, cluster); + } + } + @Override public void setWrappedLine(int line) { if (isInWindow(line)) { diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/AbstractTextCanvasModel.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/AbstractTextCanvasModel.java index 4792864b406..15d2aff9b4c 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/AbstractTextCanvasModel.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/AbstractTextCanvasModel.java @@ -21,7 +21,7 @@ import org.eclipse.core.runtime.Platform; import org.eclipse.swt.graphics.Point; import org.eclipse.terminal.connector.Logger; -import org.eclipse.terminal.internal.model.CharWidth; +import org.eclipse.terminal.internal.model.Cells; import org.eclipse.terminal.model.ITerminalTextDataReadOnly; import org.eclipse.terminal.model.ITerminalTextDataSnapshot; import org.eclipse.terminal.model.TextRange; @@ -102,10 +102,12 @@ protected ITerminalTextDataSnapshot getSnapshot() { } protected void updateSnapshot() { - if (!fInUpdate && fSnapshot.isOutOfDate()) { + if (!fInUpdate && isOutOfDate()) { fInUpdate = true; try { - fSnapshot.updateSnapshot(false); + if (!takeSnapshot()) { + return; + } if (fSnapshot.hasTerminalChanged()) { fireTerminalDataChanged(); } @@ -130,6 +132,21 @@ protected void updateSnapshot() { } } + /** @return whether the snapshot the view paints is behind the terminal text */ + protected boolean isOutOfDate() { + return fSnapshot.isOutOfDate(); + } + + /** + * Copies the terminal text into the snapshot the view paints. + * + * @return whether it was copied + */ + protected boolean takeSnapshot() { + fSnapshot.updateSnapshot(false); + return true; + } + /** * must be called from the UI thread */ @@ -299,11 +316,12 @@ private void doSetSelection(int startLine, int endLine, int startColumn, int end // A wide character is selected whole: a selection that starts on its // second cell starts on its first, one that ends on its first ends on // its second. - if (isSecondCell(startLine, startColumn)) { - startColumn--; + if (inside(startLine, startColumn)) { + startColumn = Cells.start(fSelectionSnapshot, startLine, startColumn); } - if (isSecondCell(endLine, endColumn + 1)) { - endColumn++; + if (inside(endLine, endColumn)) { + int start = Cells.start(fSelectionSnapshot, endLine, endColumn); + endColumn = start + fSelectionSnapshot.getCellWidth(endLine, start) - 1; } } int oldStart = fSelectionStartLine; @@ -383,7 +401,7 @@ public void expandHoverSelectionAt(final int line, final int col) { return; } fHoverRange = TextRange.EMPTY; - if (line < 0 || line > fSnapshot.getHeight() || col < 0) { + if (line < 0 || line >= fSnapshot.getHeight() || col < 0) { return; } int row1 = line; @@ -391,45 +409,50 @@ public void expandHoverSelectionAt(final int line, final int col) { while (row1 > 0 && fSnapshot.isWrappedLine(row1 - 1)) { row1--; } - while (row2 < fSnapshot.getHeight() && fSnapshot.isWrappedLine(row2)) { + while (row2 + 1 < fSnapshot.getHeight() && fSnapshot.isWrappedLine(row2)) { row2++; } row2++; - String lineText = ""; //$NON-NLS-1$ + int width = fSnapshot.getWidth(); + // the first cells of the characters of the logical line, as row * width + column + int[] cells = new int[(row2 - row1) * width]; + int n = 0; + int at = -1; + int under = col < width ? line * width + Cells.start(fSnapshot, line, col) : -1; for (int l = row1; l < row2; l++) { - char[] chars = fSnapshot.getChars(l); - if (chars == null) { + if (fSnapshot.getChars(l) == null) { return; } - lineText += String.valueOf(chars); + for (int c = 0; c < width; c++) { + if (fSnapshot.getCellWidth(l, c) > 0) { + if (l * width + c == under) { + at = n; + } + cells[n++] = l * width + c; + } + } } - int width = fSnapshot.getWidth(); - int col1 = col + (line - row1) * width; - if (lineText.length() <= col1 || isBoundary(lineText, col1)) { + if (at < 0 || isBoundary(cells[at], width)) { return; } - int wordStart = 0; - int wordEnd = lineText.length(); - for (int c = col1; c >= 1; c--) { - if (isBoundary(lineText, c - 1)) { - wordStart = c; - break; - } + int first = at; + int last = at; + while (first > 0 && !isBoundary(cells[first - 1], width)) { + first--; } - for (int c = col1; c < lineText.length(); c++) { - if (isBoundary(lineText, c)) { - wordEnd = c; - break; - } + while (last + 1 < n && !isBoundary(cells[last + 1], width)) { + last++; } - if (wordStart < wordEnd) { - fHoverRange = new TextRange(row1 + wordStart / width, row1 + (wordEnd - 1) / width + 1, (wordStart % width), - (wordEnd - 1) % width + 1, - lineText.substring(wordStart, wordEnd).replace("\000", "")); //$NON-NLS-1$ //$NON-NLS-2$ - if (DEBUG_HOVER) { - System.out.format("hover: %s <- [%s,%s][%s,%s]\n", //$NON-NLS-1$ - fHoverRange, col, line, wordStart, wordEnd); - } + StringBuilder word = new StringBuilder(); + for (int k = first; k <= last; k++) { + word.append(Cells.text(fSnapshot, cells[k] / width, cells[k] % width)); + } + int a = cells[first]; + int b = cells[last]; + fHoverRange = new TextRange(a / width, b / width + 1, a % width, + b % width + fSnapshot.getCellWidth(b / width, b % width), word.toString()); + if (DEBUG_HOVER) { + System.out.format("hover: %s <- [%s,%s]\n", fHoverRange, col, line); //$NON-NLS-1$ } } @@ -439,45 +462,22 @@ public String getHoverSelectionText() { } /** - * The filler in the second cell of a wide character is what its character is: - * part of the word for a path with Hangul in it, which would otherwise end at - * every syllable, and a boundary for an ideographic space (U+3000). + * A word ends at a cell never written, at whitespace, the wide ideographic space + * included, and at a quote. */ - private boolean isBoundary(String text, int index) { - char c = text.charAt(CharWidth.isFiller(text, index) ? index - 1 : index); - return Character.isWhitespace(c) || (c < '\u0020') || c == '"' || c == '\''; - } - - // helper to sanitize text copied out of a snapshot - private static String scrubLine(String text) { - // get rid of the empty space at the end of the lines - // text=text.replaceAll("\000+$",""); //$NON-NLS-1$//$NON-NLS-2$ - // - int i = text.length() - 1; - while (i >= 0 && text.charAt(i) == '\000') { - i--; - } - text = text.substring(0, i + 1); - // - // null means space, unless it is the filler of a wide character - StringBuilder scrubbed = new StringBuilder(text.length()); - for (int j = 0; j < text.length(); j++) { - char c = text.charAt(j); - if (c != '\000') { - scrubbed.append(c); - } else if (!CharWidth.isFiller(text, j)) { - scrubbed.append(' '); - } + private boolean isBoundary(int cell, int width) { + int line = cell / width; + int col = cell % width; + if (fSnapshot.getCellWidth(line, col) == 0) { + return true; } - return scrubbed.toString(); + char c = fSnapshot.getChar(line, col); // what the cell shows, not a prefix written before it + return Character.isWhitespace(c) || c < '\u0020' || c == '"' || c == '\''; } - private boolean isSecondCell(int line, int col) { - if (line < 0 || line >= fSelectionSnapshot.getHeight() || col <= 0) { - return false; - } - char[] chars = fSelectionSnapshot.getChars(line); - return chars != null && col < chars.length && CharWidth.isSecondCell(new String(chars), col); + /** @return whether the cell is on the selection's snapshot */ + private boolean inside(int line, int col) { + return line >= 0 && line < fSelectionSnapshot.getHeight() && col >= 0 && col < fSelectionSnapshot.getWidth(); } /** @@ -493,14 +493,12 @@ private String extractSelectedText() { String text; char[] chars = fSelectionSnapshot.getChars(line); if (chars != null) { - text = new String(chars); - if (line == fSeletionEndLine && fSelectionEndColumn >= 0) { - text = text.substring(0, Math.min(fSelectionEndColumn + 1, text.length())); - } - if (line == fSelectionStartLine) { - text = text.substring(Math.min(fSelectionStartCoumn, text.length())); - } - text = scrubLine(text); + int width = fSelectionSnapshot.getWidth(); + int from = line == fSelectionStartLine ? Math.min(fSelectionStartCoumn, width) : 0; + // a row selected to its end comes whole, with what a narrowed screen keeps past its margin + text = line == fSeletionEndLine && fSelectionEndColumn >= 0 && fSelectionEndColumn + 1 < width + ? Cells.text(fSelectionSnapshot, line, from, Math.min(fSelectionEndColumn + 1, width)) + : Cells.row(fSelectionSnapshot, line, from); } else { text = ""; //$NON-NLS-1$ } @@ -561,7 +559,7 @@ public String getAllText() { char[] chars = snapshot.getChars(line); String text; if (chars != null) { - text = scrubLine(new String(chars)); // take care of NULs + text = Cells.row(snapshot, line, 0); } else { text = ""; //$NON-NLS-1$ null arrays represent empty lines } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/GridCanvas.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/GridCanvas.java index c3384f57260..c5290e06596 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/GridCanvas.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/GridCanvas.java @@ -31,7 +31,7 @@ abstract public class GridCanvas extends VirtualCanvas { public GridCanvas(Composite parent, int style) { super(parent, style); addListener(SWT.MouseWheel, event -> { - if (getVerticalBar().isVisible()) { + if (!handleMouseWheel(event.x, event.y, event.count, event.stateMask) && getVerticalBar().isVisible()) { int delta = -fCellHeight * event.count; scrollYDelta(delta); } @@ -40,6 +40,17 @@ public GridCanvas(Composite parent, int style) { } + /** + * Offered the wheel before the canvas scrolls itself. + * + * @param count lines the wheel asked for, positive when scrolling up + * @param stateMask the keys held at the time + * @return whether it was taken, in which case the canvas leaves it alone + */ + protected boolean handleMouseWheel(int x, int y, int count, int stateMask) { + return false; + } + /** template method paint. * iterates over all cells in the clipping rectangle and paints them. */ diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/PollingTextCanvasModel.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/PollingTextCanvasModel.java index 5bc81c3271b..b856eb2f828 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/PollingTextCanvasModel.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/PollingTextCanvasModel.java @@ -20,7 +20,70 @@ */ public class PollingTextCanvasModel extends AbstractTextCanvasModel { private static final int DEFAULT_POLL_INTERVAL = 50; + /** + * How long a program is given to finish a screen it said it was drawing. A + * program that says so and then stops must not leave the view frozen. + */ + private static final int REDRAW_GRACE = 200; int fPollInterval = -1; + private boolean fRedrawing; + // whether the view held back since it last looked, and since when (System.nanoTime) + private boolean fHeldBack; + private long fHeldBackSince; + // where a scroll or resize moved the view, or -1: applied with the next copy, as moving + // the window over a snapshot held back would show its lines in the wrong places + private int fWindowStart = -1, fWindowSize; + + /** + * A program that draws a screen in pieces can say where a screen begins and + * ends, and while it is between the two the view leaves it alone rather than + * catching it half drawn. + * + * @param redrawing whether a screen is being drawn + */ + public synchronized void setSynchronizedOutput(boolean redrawing) { + fRedrawing = redrawing; + } + + /** + * Copies the text unless a screen is being drawn. Every look at the text + * comes here, the polls and a scroll or resize alike, and the check and the + * copy are one step, so a screen cannot begin between them. The view is held + * back for at most {@link #REDRAW_GRACE} ms since it last looked, however many + * screens begin meanwhile, on a clock that does not move with the time of day. + */ + @Override + protected synchronized boolean takeSnapshot() { + long now = System.nanoTime(); + if (fRedrawing && !fHeldBack) { + fHeldBack = true; + fHeldBackSince = now; + } + if (fRedrawing && now - fHeldBackSince < REDRAW_GRACE * 1_000_000L) { + return false; + } + fHeldBack = false; + if (fWindowStart >= 0) { + getSnapshot().setInterestWindow(fWindowStart, fWindowSize); + fWindowStart = -1; + } + return super.takeSnapshot(); + } + + @Override + protected synchronized boolean isOutOfDate() { + return fWindowStart >= 0 || super.isOutOfDate(); + } + + /** A scroll or resize moves the window with the next copy of the text, not before. */ + @Override + public void setVisibleRectangle(int startLine, int startCol, int height, int width) { + synchronized (this) { + fWindowStart = Math.max(0, startLine); + fWindowSize = Math.max(1, height); + } + update(); + } /** * diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextCanvas.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextCanvas.java index 11d7487ee77..f6cddcd6c66 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextCanvas.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextCanvas.java @@ -42,8 +42,9 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; import org.eclipse.terminal.control.ITerminalMouseListener; -import org.eclipse.terminal.internal.model.CharWidth; import org.eclipse.terminal.model.ITerminalTextDataReadOnly; import org.eclipse.terminal.model.TerminalColor; @@ -66,6 +67,14 @@ public class TextCanvas extends GridCanvas { private ResizeListener fResizeListener; private final List fMouseListeners; private SelectionMode fSelMode = SelectionMode.NONE; + private IMouseWheelHandler fWheelHandler; + private IMouseButtonHandler fButtonHandler; + // the buttons whose press went to the program, as bits 1 << button: their releases go there too + private int fReportedButtons; + // whether the last press went to the program: its double-click and context menu are its too + private boolean fPressReported; + // the last click the program took: where a shift-drag starts while nothing is selected + private Point fReportedClick; private enum SelectionMode { NONE, DRAG, WORD, LINE @@ -151,6 +160,55 @@ public void focusLost(FocusEvent e) { fCellCanvasModel.setCursorEnabled(false); } }); + // Before every other mouse listener: a press the program takes is the program's + // alone. The terminal's own use of it (a selection, the middle-click paste, a + // double-click, the copy on release) must not happen too, so the event goes no + // further (SWT delivers no more listeners once the type is None). Shift keeps + // the mouse for the terminal. + Listener reporter = event -> { + switch (event.type) { + case SWT.MouseDown: + fPressReported = wouldReport(event.stateMask) && report(event, event.button, true); + if (!fPressReported) { + // a release of this button lost earlier (a dialog took it) is not waited for + fReportedButtons &= ~(1 << event.button); + return; + } + fReportedButtons |= 1 << event.button; + // The click went to the program, so whatever the terminal had + // selected is no longer what the pointer is pointing at. + fCellCanvasModel.setSelection(-1, -1, -1, -1); + fCellCanvasModel.expandHoverSelectionAt(-1, -1); + fDraggingStart = null; + // a later shift-drag starts from here: the anchor, kept apart too, as + // the model gives no anchor while nothing is selected + fReportedClick = cell(event.x, event.y); + fCellCanvasModel.setSelectionAnchor(fReportedClick); + break; + case SWT.MouseUp: + // a release goes wherever its press went, however the keyboard stands by then + if ((fReportedButtons & 1 << event.button) == 0) { + return; + } + fReportedButtons &= ~(1 << event.button); + report(event, event.button, false); + break; + default: // SWT.MouseDoubleClick + if (!fPressReported) { + return; + } + } + event.type = SWT.None; + }; + addListener(SWT.MouseDown, reporter); + addListener(SWT.MouseUp, reporter); + addListener(SWT.MouseDoubleClick, reporter); + // the context menu of a right-click the program took; the menu key still opens it + addListener(SWT.MenuDetect, event -> { + if (event.detail == SWT.MENU_MOUSE && fPressReported) { + event.doit = false; + } + }); fMouseListeners = new ArrayList<>(); addMouseListener(new MouseListener() { @Override @@ -202,11 +260,16 @@ public void mouseDown(MouseEvent e) { fHasSelection = false; if ((e.stateMask & SWT.SHIFT) != 0) { Point anchor = fCellCanvasModel.getSelectionAnchor(); + if (anchor == null && fReportedClick != null + && fReportedClick.y < fCellCanvasModel.getTerminalText().getHeight()) { + anchor = fReportedClick; // unless the text was cleared below it since + } if (anchor != null) { fDraggingStart = anchor; } } else { fCellCanvasModel.setSelectionAnchor(fDraggingStart); + fReportedClick = null; } fDraggingEnd = null; } @@ -272,6 +335,12 @@ public void mouseUp(MouseEvent e) { } }); addMouseMoveListener(e -> { + int held = heldButton(e.stateMask, fReportedButtons); + // a button held down is a drag of the program's only if its press was the program's + if (fDraggingStart == null && held >= 0 && wouldReport(e.stateMask) + && fButtonHandler.mouseMoved(held, modifiers(e.stateMask), cell(e.x, e.y))) { + return; + } if (fDraggingStart != null) { // Dragging past an edge keeps the lines beyond it coming into view. if (dragPast(e.y) != 0 && !fDragScrolling) { @@ -575,6 +644,94 @@ protected void repaintRange(int col, int line, int width, int height) { repaint(r); } + /** + * Hands the wheel to whoever can pass it on to the program being run. + */ + public interface IMouseWheelHandler { + /** + * @param count lines the wheel asked for, positive when scrolling up + * @param cell the cell of the text under the pointer, history lines included + * @return whether the program took it + */ + boolean mouseWheel(int count, int modifiers, Point cell); + } + + /** + * Hands a button or the pointer moving to whoever can pass it on to the program + * being run, with the cell of the text under the pointer, history lines included. + */ + public interface IMouseButtonHandler { + /** @return whether the program took it */ + boolean mouseButton(int button, int modifiers, Point cell, boolean pressed); + + /** @return whether the program took it */ + boolean mouseMoved(int button, int modifiers, Point cell); + } + + public void setMouseButtonHandler(IMouseButtonHandler handler) { + fButtonHandler = handler; + } + + /** + * Holding shift keeps the event for the terminal, which is how a selection is + * still made with the mouse while a program is listening for it. Asked of a + * press and of the pointer moving; a release is not its own decision but goes + * wherever the press it ends went, however the keyboard stands by then. + */ + private boolean wouldReport(int stateMask) { + return fButtonHandler != null && (stateMask & SWT.SHIFT) == 0 && getCellWidth() > 0 && getCellHeight() > 0; + } + + private boolean report(Event e, int button, boolean pressed) { + return fButtonHandler.mouseButton(button, modifiers(e.stateMask), cell(e.x, e.y), pressed); + } + + /** the cell of the text under the point: its line counts the history above the screen too */ + private Point cell(int x, int y) { + return screenPointToCell(Math.max(0, x), Math.max(0, y)); + } + + /** + * What xterm adds to a button for the keys held with it: 8 for alt, 16 for + * control. Shift is never among them, being what keeps the mouse for the + * terminal. + */ + static int modifiers(int stateMask) { + return ((stateMask & SWT.ALT) != 0 ? 8 : 0) | ((stateMask & SWT.CTRL) != 0 ? 16 : 0); + } + + /** + * @param reported the buttons whose press went to the program, as bits 1 << button + * @return the first button held whose press went to the program; 0 when none is + * held, -1 when every button held is the terminal's + */ + static int heldButton(int stateMask, int reported) { + int[] masks = { SWT.BUTTON1, SWT.BUTTON2, SWT.BUTTON3 }; + boolean held = false; + for (int button = 1; button <= 3; button++) { + if ((stateMask & masks[button - 1]) != 0) { + held = true; + if ((reported & 1 << button) != 0) { + return button; + } + } + } + return held ? -1 : 0; + } + + public void setMouseWheelHandler(IMouseWheelHandler handler) { + fWheelHandler = handler; + } + + @Override + protected boolean handleMouseWheel(int x, int y, int count, int stateMask) { + // shift keeps the wheel for the terminal's own scrolling, as it keeps the buttons + if (fWheelHandler == null || (stateMask & SWT.SHIFT) != 0 || getCellWidth() <= 0 || getCellHeight() <= 0) { + return false; + } + return fWheelHandler.mouseWheel(count, modifiers(stateMask), cell(x, y)); + } + @Override protected void drawLine(GC gc, int line, int x, int y, int colFirst, int colLast) { // A wide character spans two cells and has to be drawn from the first of @@ -598,17 +755,8 @@ protected void drawLine(GC gc, int line, int x, int y, int colFirst, int colLast */ private boolean isFillerCell(int line, int col) { ITerminalTextDataReadOnly text = fCellCanvasModel.getTerminalText(); - if (col <= 0 || col >= text.getWidth() || line < 0 || line >= text.getHeight()) { - return false; - } - char c = text.getChar(line, col); - char before = text.getChar(line, col - 1); - // the filler of a wide character of the BMP, or the low half of a surrogate - // pair, whose high half sits in the cell before - if (Character.isLowSurrogate(c)) { - return Character.isHighSurrogate(before); - } - return c == '\000' && !Character.isSurrogate(before) && CharWidth.of(before) == 2; + return col > 0 && col < text.getWidth() && line >= 0 && line < text.getHeight() + && text.getCellWidth(line, col) == 0; } @Override @@ -657,6 +805,7 @@ public void selectAll() { */ public void clearSelection() { fCellCanvasModel.setSelection(-1, -1, -1, -1); + fReportedClick = null; } /** diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextLineRenderer.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextLineRenderer.java index 56c185363a1..f52bd71f330 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextLineRenderer.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/TextLineRenderer.java @@ -27,7 +27,7 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.terminal.connector.Logger; -import org.eclipse.terminal.internal.model.CharWidth; +import org.eclipse.terminal.internal.model.Cells; import org.eclipse.terminal.model.ITerminalTextDataReadOnly; import org.eclipse.terminal.model.LineSegment; import org.eclipse.terminal.model.TerminalColor; @@ -73,8 +73,7 @@ public void drawLine(ITextCanvasModel model, GC gc, int line, int x, int y, int LineSegment segment = segments[i]; TerminalStyle style = segment.getStyle(); setupGC(gc, style); - String text = segment.getText(); - drawText(gc, x, y, colFirst, segment.getColumn(), text); + drawText(gc, line, x, y, colFirst, segment.getColumn(), segment.getText()); drawCursor(model, gc, line, x, y, colFirst); } if (fModel.hasHoverSelection(line)) { @@ -122,8 +121,7 @@ public void drawLine(ITextCanvasModel model, GC gc, int line, int x, int y, int } len = Math.min(len, chars.length - offset); if (len > 0) { - String text = new String(chars, offset, len); - drawText(gc, x, y, colFirst, offset, text); + drawText(gc, line, x, y, colFirst, offset, new String(chars, offset, len)); } } } @@ -154,12 +152,8 @@ private void drawCursor(ITextCanvasModel model, GC gc, int row, int x, int y, in if (cursorColumn < getTerminalText().getWidth()) { // On a wide character the cursor covers both of its cells, whichever // one it is on, as in xterm: half a glyph cannot be drawn reversed. - char[] chars = getTerminalText().getChars(row); - String line = chars == null ? "" : new String(chars); //$NON-NLS-1$ - if (cursorColumn < line.length() && CharWidth.isSecondCell(line, cursorColumn)) { - cursorColumn--; - } - int cells = cursorColumn + 1 < line.length() && CharWidth.isSecondCell(line, cursorColumn + 1) ? 2 : 1; + cursorColumn = Cells.start(getTerminalText(), row, cursorColumn); + int cells = getTerminalText().getCellWidth(row, cursorColumn); TerminalStyle style = getTerminalText().getStyle(row, cursorColumn); if (style == null) { // TODO make the cursor color customizable @@ -167,103 +161,72 @@ private void drawCursor(ITextCanvasModel model, GC gc, int row, int x, int y, in } style = style.setReverse(!style.isReverse()); setupGC(gc, style); - String text = cells == 2 ? line.substring(cursorColumn, cursorColumn + 2) - : String.valueOf(getTerminalText().getChar(row, cursorColumn)); Rectangle clipping = gc.getClipping(); gc.setClipping(clipping.intersection(new Rectangle(x + (cursorColumn - colFirst) * getCellWidth(), y, cells * getCellWidth(), getCellHeight()))); - drawText(gc, x, y, colFirst, cursorColumn, text); + char[] text = new char[cells]; + for (int i = 0; i < cells; i++) { + text[i] = getTerminalText().getChar(row, cursorColumn + i); // a null past what was written + } + drawText(gc, row, x, y, colFirst, cursorColumn, new String(text)); gc.setClipping(clipping); } } } - private void drawText(GC gc, int x, int y, int colFirst, int col, String text) { + /** + * Draws the characters that start in the cells from col whose + * chars are cells, each as {@link Cells} has it: a cluster whole, + * over the cells it takes. + */ + private void drawText(GC gc, int line, int x, int y, int colFirst, int col, String cells) { + ITerminalTextDataReadOnly data = getTerminalText(); + cells = cells.substring(0, Math.max(0, Math.min(cells.length(), data.getWidth() - col))); + int end = col + cells.length(); int offset = (col - colFirst) * getCellWidth(); if (fStyleMap.isFontProportional()) { - // draw the background - // TODO why does this not work??????? - // gc.fillRectangle(x,y,fStyleMap.getFontWidth()*text.length(),fStyleMap.getFontHeight()); int xx = x + offset; - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - int cells = cellsAt(text, i); - // a character beyond the BMP is drawn whole, both surrogates at once - int n = Character.charCount(text.codePointAt(i)); + for (int c = col; c < end;) { + int width = Math.max(data.getCellWidth(line, c), 1); // TODO why do I have to draw the background character by character?????? - gc.fillRectangle(xx, y, cells * fStyleMap.getFontWidth(), fStyleMap.getFontHeight()); - if (c != ' ' && c != '\000') { - gc.drawString(text.substring(i, i + n), fStyleMap.getCharOffset(c) + xx, y, false); + gc.fillRectangle(xx, y, width * fStyleMap.getFontWidth(), fStyleMap.getFontHeight()); + String drawn = Cells.drawn(data, line, c); + if (!drawn.isBlank()) { + // placed by the character the cell shows, not a prefix written before it + gc.drawString(drawn, fStyleMap.getCharOffset(data.getChar(line, c)) + xx, y, false); } - xx += cells * fStyleMap.getFontWidth(); - i += n - 1; + xx += width * fStyleMap.getFontWidth(); + c += width; } + return; + } + // One call keeps whatever the font does with the run, ligatures included, + // but only while it advances exactly one cell per column. A character the + // font does not have is drawn from somewhere else and rarely does, and + // then everything after it on the line sits in the wrong column. + String drawn = Cells.drawn(data, line, col, cells); + if (drawn != null && gc.textExtent(drawn).x == (end - col) * getCellWidth()) { + gc.drawString(drawn, x + offset, y, false); } else { - // One call keeps whatever the font does with the run, ligatures included, - // but only while it advances exactly one cell per column. A character the - // font does not have is drawn from somewhere else and rarely does, and - // then everything after it on the line sits in the wrong column. - String drawn = withoutFillers(text); - if (gc.textExtent(drawn).x == text.length() * getCellWidth()) { - gc.drawString(drawn, x + offset, y, false); - } else { - drawCellByCell(gc, x + offset, y, text); - } + drawCellByCell(gc, data, line, col, end, x + offset, y); } } /** * Puts every character at the start of its own cell, so the columns hold no - * matter what the font makes of it. A wide character is left to cover the cell - * of the filler that follows it. + * matter what the font makes of it. A character that takes two cells is left to + * cover the second one. */ - private void drawCellByCell(GC gc, int x, int y, String text) { + private void drawCellByCell(GC gc, ITerminalTextDataReadOnly data, int line, int col, int end, int x, int y) { // The whole run at once, because the characters are drawn over it one at a // time and the cells between them would otherwise keep what was there before. - gc.fillRectangle(x, y, text.length() * getCellWidth(), getCellHeight()); - for (int i = 0; i < text.length();) { - // A character beyond the BMP is two chars in two cells, and has to be - // drawn whole: half of a surrogate pair is no character at all. - int n = Character.charCount(text.codePointAt(i)); - char c = text.charAt(i); - if (c != ' ' && c != '\000') { - gc.drawString(text.substring(i, i + n), x + i * getCellWidth(), y, true); - } - i += n; - } - } - - /** - * Cells taken up by the character at index: none for the filler of - * a wide character, since the character it belongs to already covers it, two - * for a wide character, one for anything else. - */ - private static int cellsAt(String text, int index) { - if (CharWidth.isFiller(text, index)) { - return 0; - } - int codePoint = text.codePointAt(index); - // a surrogate pair takes two cells whatever its width, as it is stored - return Character.charCount(codePoint) == 2 || CharWidth.of(codePoint) == 2 ? 2 : 1; - } - - /** - * The text as it should be handed to a fixed width font: fillers dropped, since - * the wide character before them already spans their cell, and every other null - * turned into the space it stands for. What is left lines up column for column, - * as long as the font draws a wide character in exactly two cells. - */ - private static String withoutFillers(String text) { - StringBuilder drawn = new StringBuilder(text.length()); - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - if (c != '\000') { - drawn.append(c); - } else if (!CharWidth.isFiller(text, i)) { - drawn.append(' '); + gc.fillRectangle(x, y, (end - col) * getCellWidth(), getCellHeight()); + for (int c = col; c < end; c++) { + String drawn = Cells.drawn(data, line, c); + if (!drawn.isBlank()) { + gc.drawString(drawn, x + (c - col) * getCellWidth(), y, true); } } - return drawn.toString(); } /** diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextData.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextData.java index 46f145a370e..d28f827a03f 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextData.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextData.java @@ -166,4 +166,12 @@ public interface ITerminalTextData extends ITerminalTextDataReadOnly { default void clearWrappedLine(int line) { } + /** + * Records the whole of a grapheme cluster drawn in the cells from column, see + * {@link #getCluster(int, int)}. Writing any of its cells forgets it. + * @since 1.2 + */ + default void setCluster(int line, int column, String cluster) { + } + } diff --git a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextDataReadOnly.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextDataReadOnly.java index 9809e17ef37..b980c6229dc 100644 --- a/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextDataReadOnly.java +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/model/ITerminalTextDataReadOnly.java @@ -90,4 +90,45 @@ public interface ITerminalTextDataReadOnly { */ boolean isWrappedLine(int line); + /** + * A grapheme cluster is drawn in one or two cells however many characters make + * it up: a letter with a mark that has no composed form, an emoji joined to + * others, or given a skin tone or a presentation selector. The cells hold the + * character drawn for it; this is the whole of it, as the program wrote it. + * + * @param line + * @param column the first of its cells + * @return the cluster, or null where the cells hold nothing more than they show + * @since 1.2 + */ + default String getCluster(int line, int column) { + return null; + } + + /** + * How the characters of a line lie in its cells: a character beyond the BMP, a + * wide one and a grapheme cluster may take two. Set when the character is + * written, together with what fills its second cell. + * + * @param line + * @param column + * @return 2 or 1, the cells the character starting in the cell takes; 0 when the + * cell is the second of a character starting in the one before + * @since 1.2 + */ + default int getCellWidth(int line, int column) { + return 1; + } + + /** + * @param line + * @return whether every character on the line is one char in one cell, with no + * grapheme cluster kept beside it: then the chars are the text as it is + * drawn. False when not known. + * @since 1.2 + */ + default boolean isSimpleLine(int line) { + return false; + } + } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/AllTestSuite.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/AllTestSuite.java index b82f997997f..bb29c33d8cf 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/AllTestSuite.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/AllTestSuite.java @@ -21,7 +21,9 @@ */ @Suite @SelectClasses({ // + MouseReportTest.class, // VT100EmulatorBackendTest.class, // + VT100EmulatorCellsTest.class, // VT100EmulatorTest.class, // }) public class AllTestSuite { diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MockTerminalControlForText.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MockTerminalControlForText.java index 6601d6e8de5..b0d8ce19f20 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MockTerminalControlForText.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MockTerminalControlForText.java @@ -66,6 +66,17 @@ public boolean isCursorShown() { return cursorShown; } + private boolean synchronizedOutput; + + @Override + public void enableSynchronizedOutput(boolean redrawing) { + synchronizedOutput = redrawing; + } + + public boolean isSynchronizedOutput() { + return synchronizedOutput; + } + @Override public void enableBracketedPaste(boolean enable) { bracketedPaste = enable; @@ -75,6 +86,27 @@ public boolean isBracketedPaste() { return bracketedPaste; } + private int mouseMode; + private boolean sgrMouse; + + @Override + public void enableMouseReporting(int mode) { + mouseMode = mode; + } + + public int getMouseMode() { + return mouseMode; + } + + @Override + public void enableSgrMouseEncoding(boolean enable) { + sgrMouse = enable; + } + + public boolean isSgrMouseEncoding() { + return sgrMouse; + } + private boolean applicationCursorKeys; @Override diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MouseReportTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MouseReportTest.java new file mode 100644 index 00000000000..44eec506d56 --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MouseReportTest.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * All rights reserved. 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.terminal.internal.emulator; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.eclipse.swt.graphics.Point; +import org.junit.jupiter.api.Test; + +/** How a mouse event is spelled for the program, in xterm's two encodings. */ +public class MouseReportTest { + + private static final String CSI = "\u001b["; + + @Test + public void testSgrEncoding() { + // CSI < button ; column ; row M for a press, m for a release, 1-based + assertEquals(CSI + "<0;10;5M", VT100TerminalControl.mouseReport(true, 0, 5, 10, true)); + assertEquals(CSI + "<0;10;5m", VT100TerminalControl.mouseReport(true, 0, 5, 10, false)); + assertEquals(CSI + "<2;10;5M", VT100TerminalControl.mouseReport(true, 2, 5, 10, true)); + assertEquals(CSI + "<32;10;5M", VT100TerminalControl.mouseReport(true, 32, 5, 10, true)); // drag + assertEquals(CSI + "<64;10;5M", VT100TerminalControl.mouseReport(true, 64, 5, 10, true)); // wheel up + assertEquals(CSI + "<16;10;5M", VT100TerminalControl.mouseReport(true, 0 + 16, 5, 10, true)); // control + assertEquals(CSI + "<72;10;5M", VT100TerminalControl.mouseReport(true, 64 + 8, 5, 10, true)); // alt-wheel + // room for any column, which the older encoding has not + assertEquals(CSI + "<0;300;5M", VT100TerminalControl.mouseReport(true, 0, 5, 300, true)); + } + + @Test + public void testX10Encoding() { + // CSI M then button, column and row each offset by 32 + assertEquals(CSI + "M" + (char) 32 + (char) 42 + (char) 37, + VT100TerminalControl.mouseReport(false, 0, 5, 10, true)); + // a release says only that some button came up + assertEquals(CSI + "M" + (char) 35 + (char) 42 + (char) 37, + VT100TerminalControl.mouseReport(false, 0, 5, 10, false)); + // with the keys held kept, as in the press: alt and left up is 3 + 8 + assertEquals(CSI + "M" + (char) (32 + 11) + (char) 42 + (char) 37, + VT100TerminalControl.mouseReport(false, 0 + 8, 5, 10, false)); + assertEquals(CSI + "M" + (char) (32 + 19) + (char) 42 + (char) 37, + VT100TerminalControl.mouseReport(false, 2 + 16, 5, 10, false)); + // no room past column or row 223: nothing is reported, as in xterm + assertEquals("", VT100TerminalControl.mouseReport(false, 0, 5, 224, true)); + assertEquals("", VT100TerminalControl.mouseReport(false, 0, 224, 10, true)); + } + + @Test + public void testReportsAreBytes() { + // column 100 is the one byte 132, not the two UTF-8 would make of it + assertArrayEquals(new byte[] { 27, '[', 'M', 32, (byte) 132, 37 }, + VT100TerminalControl.mouseReportBytes(VT100TerminalControl.mouseReport(false, 0, 5, 100, true))); + assertArrayEquals("\u001b[<0;100;5M".getBytes(java.nio.charset.StandardCharsets.US_ASCII), + VT100TerminalControl.mouseReportBytes(VT100TerminalControl.mouseReport(true, 0, 5, 100, true))); + } + + @Test + public void testCellsOnTheScreen() { + // 100 lines of text, the last 24 of them the screen: line 76 is its first line + assertEquals(new Point(1, 1), VT100TerminalControl.onScreen(new Point(0, 76), 100, 24, 80)); + assertEquals(new Point(10, 24), VT100TerminalControl.onScreen(new Point(9, 99), 100, 24, 80)); + // the history above it is not the program's + assertNull(VT100TerminalControl.onScreen(new Point(0, 75), 100, 24, 80)); + // the strip under the last line and the margin right of the last column are the last ones + assertEquals(new Point(80, 24), VT100TerminalControl.onScreen(new Point(85, 100), 100, 24, 80)); + // no history: the text is the screen + assertEquals(new Point(3, 2), VT100TerminalControl.onScreen(new Point(2, 1), 24, 24, 80)); + } +} diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/TerminalMouseWheelUITest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/TerminalMouseWheelUITest.java new file mode 100644 index 00000000000..565b2390cf4 --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/TerminalMouseWheelUITest.java @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * All rights reserved. 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.terminal.internal.emulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.eclipse.swt.SWT; +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.Event; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.terminal.connector.ITerminalConnector; +import org.eclipse.terminal.connector.ITerminalControl; +import org.eclipse.terminal.connector.TerminalState; +import org.eclipse.terminal.connector.provider.AbstractTerminalConnector; +import org.eclipse.terminal.control.ITerminalListener; +import org.eclipse.terminal.control.TerminalTitleRequestor; +import org.eclipse.terminal.internal.connector.TerminalConnector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The wheel as a program hears it: SWT's wheel events, however they split the + * lines, make one report per notch of three lines. + */ +public class TerminalMouseWheelUITest { + + // the button of each report: where on the screen the cell is depends on the size the + // shell happens to get, which differs between platforms + private static final String UP = "\u001b[<64", DOWN = "\u001b[<65"; //$NON-NLS-1$ //$NON-NLS-2$ + + private Display display; + private Shell shell; + private VT100TerminalControl terminal; + private final ByteArrayOutputStream sent = new ByteArrayOutputStream(); + + @BeforeEach + public void createTerminal() { + display = Display.getCurrent() != null ? null : new Display(); + shell = new Shell(); + shell.setLayout(new FillLayout()); + ITerminalListener listener = new ITerminalListener() { + @Override + public void setState(TerminalState state) { + } + + @Override + public void setTerminalSelectionChanged() { + } + + @Override + public void setTerminalTitle(String title, TerminalTitleRequestor requestor) { + } + }; + terminal = new VT100TerminalControl(listener, new Composite(shell, 0), new ITerminalConnector[0]); + AbstractTerminalConnector connector = new AbstractTerminalConnector() { + @Override + public void connect(ITerminalControl control) { + super.connect(control); + control.setState(TerminalState.CONNECTED); + } + + @Override + public OutputStream getTerminalToRemoteStream() { + return sent; + } + + @Override + public String getSettingsSummary() { + return ""; //$NON-NLS-1$ + } + }; + ITerminalConnector wrapped = new TerminalConnector(() -> connector, "test", "test", false); //$NON-NLS-1$ //$NON-NLS-2$ + terminal.setConnector(wrapped); + wrapped.connect(terminal); + assertTrue(terminal.isConnected()); + terminal.enableMouseReporting(1000); + terminal.enableSgrMouseEncoding(true); + } + + @AfterEach + public void dispose() { + terminal.disposeTerminal(); + shell.dispose(); + if (display != null) { + display.dispose(); + } + } + + /** wheel events of these line counts, then what the program was sent */ + private String wheel(int... counts) { + Control canvas = terminal.getControl(); + for (int count : counts) { + Event event = new Event(); + event.x = 1; + event.y = 1; + event.count = count; + canvas.notifyListeners(SWT.MouseWheel, event); + } + String text = sent.toString(StandardCharsets.ISO_8859_1); + sent.reset(); + return text.replaceAll(";\\d+;\\d+M", ""); //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Test + public void threeLinesMakeOneNotch() { + assertEquals("", wheel(1, 1)); //$NON-NLS-1$ + assertEquals(UP, wheel(1)); + assertEquals(UP + UP, wheel(6)); + assertEquals(DOWN, wheel(-3)); + } + + @Test + public void whatIsLeftOverCountsTowardTheNextNotch() { + assertEquals(UP, wheel(4)); + assertEquals(UP, wheel(2)); + assertEquals("", wheel(2)); //$NON-NLS-1$ + assertEquals(UP, wheel(1)); + } + + @Test + public void turningTheWheelBackForgetsTheLinesLeftOver() { + assertEquals("", wheel(2, -1)); //$NON-NLS-1$ + assertEquals(DOWN, wheel(-2)); + // the two lines up were dropped at the turn: one more up is not a notch + assertEquals("", wheel(1)); //$NON-NLS-1$ + } + + @Test + public void aNewModeForgetsTheLinesLeftOver() { + assertEquals("", wheel(2)); //$NON-NLS-1$ + terminal.enableMouseReporting(1000); + assertEquals("", wheel(1)); //$NON-NLS-1$ + terminal.enableMouseReporting(0); + terminal.enableMouseReporting(1002); + assertEquals("", wheel(2)); //$NON-NLS-1$ + assertEquals(UP, wheel(1)); + } +} diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackendTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackendTest.java index 915663ada59..6c3a93a37e0 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackendTest.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorBackendTest.java @@ -22,10 +22,16 @@ import static org.eclipse.terminal.model.TerminalColor.WHITE; 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.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Set; + +import org.eclipse.terminal.internal.model.Cells; import org.eclipse.terminal.internal.model.TerminalTextData; import org.eclipse.terminal.internal.model.TerminalTextDataStore; import org.eclipse.terminal.internal.model.TerminalTextTestHelper; @@ -1325,10 +1331,12 @@ public void testInsertModeBeyondBmp() { vt100.appendString("abc"); vt100.setCursorColumn(0); vt100.setInsertMode(true); - // U+1D400 is one column wide, but its two chars still take two cells: insert room for both + // U+1D400 is one column wide and takes one cell, its two chars kept beside the line vt100.appendString("\uD835\uDC00"); vt100.setInsertMode(false); - assertEquals("\uD835\uDC00abc", new String(term.getChars(0), 0, 5)); + assertEquals("\uD835\uDC00", Cells.text(term, 0, 0)); + assertEquals(1, term.getCellWidth(0, 0)); + assertEquals("abc", new String(term.getChars(0), 1, 3)); } @Test @@ -1924,4 +1932,393 @@ public void testWrappedLineMarkComesOff() { vt100.eraseCharacters(1); assertFalse(term.isWrappedLine(0)); } + + @Test + public void testCombiningMarks() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(4); + vt100.setDimensions(4, 10); + vt100.setCursor(0, 0); + // a mark composes with the character before it where the two have one form + vt100.appendString("e\u0301x"); + assertEquals("\u00e9x", new String(term.getChars(0), 0, 2)); + assertEquals(2, vt100.getCursorColumn()); + // Hangul conjoining jamo make a syllable, in one wide cell + vt100.setCursor(1, 0); + vt100.appendString("\u1112\u1161\u11ab|"); + assertEquals("\ud55c\000|", new String(term.getChars(1), 0, 3)); + // a mark with no composed form is kept with the character as a cluster + vt100.setCursor(2, 0); + vt100.appendString("1\ufe0f\u20e3|"); // keycap one + assertEquals("1\ufe0f\u20e3", term.getCluster(2, 0)); + assertEquals('|', term.getChar(2, 2)); + } + + @Test + public void testGraphemeClusters() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(4); + vt100.setDimensions(4, 20); + String family = "\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67"; // man ZWJ woman ZWJ girl + String heart = "\u2764\ufe0f"; // heavy black heart + emoji presentation + String thumbs = "\ud83d\udc4d\ud83c\udffd"; // thumbs up + medium skin tone + String flag = "\ud83c\uddf0\ud83c\uddf7"; // regional indicators K R + // a cluster takes two cells however many characters it runs to + vt100.setCursor(0, 0); + vt100.appendString(family + "|"); + assertEquals(3, vt100.getCursorColumn()); + assertEquals("\ud83d\udc68", new String(term.getChars(0), 0, 2)); // the cells hold the first of them + assertEquals(family, term.getCluster(0, 0)); // the whole is kept beside them + // a narrow character shown as an emoji takes a second cell + vt100.setCursor(1, 0); + vt100.appendString(heart + "|" + thumbs + "|" + flag + "|"); + assertEquals(9, vt100.getCursorColumn()); + assertEquals(heart, term.getCluster(1, 0)); + assertEquals(thumbs, term.getCluster(1, 3)); + assertEquals(flag, term.getCluster(1, 6)); + // writing over a cell forgets the cluster that had it + vt100.setCursor(1, 1); + vt100.appendString("x"); + assertNull(term.getCluster(1, 0)); + assertEquals(' ', term.getChar(1, 0)); // and blanks its other cell, as for any wide character + // a cluster on the last two cells, with the wrap pending, is still joined + vt100.setVT100LineWrapping(true); + vt100.setCursor(2, 18); + vt100.appendString(family); + assertEquals(family, term.getCluster(2, 18)); + vt100.appendString("y"); + assertEquals('y', term.getChar(3, 0)); + } + + @Test + public void testClusterEdits() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(8); + vt100.setDimensions(8, 10); + String heart = "\u2764\ufe0f"; + String smile = "\ud83d\ude00"; + // a mark with no composed form stays on a narrow character, which keeps one cell + vt100.setCursor(0, 0); + vt100.appendString("q\u0301|1\u20e3|"); + assertEquals("q\u0301", term.getCluster(0, 0)); + assertEquals("1\u20e3", term.getCluster(0, 2)); // a keycap without VS16 is narrow, as in Windows Terminal + assertEquals("q|1|", new String(term.getChars(0), 0, 4)); + // a later mark composes with the marks already there: KA, acute, dakuten is drawn as GA; + // copied, it is what the program wrote + vt100.setCursor(1, 0); + vt100.appendString("\u30ab\u0301\u3099"); + assertEquals('\u30ac', term.getChar(1, 0)); + assertEquals("\u30ab\u0301\u3099", term.getCluster(1, 0)); + // a joiner joins only what is written right after it + vt100.setCursor(2, 0); + vt100.appendString(smile); + vt100.setCursor(3, 0); + vt100.appendString(smile + "\u200d"); + vt100.setCursor(2, 2); + vt100.appendString("x"); + assertEquals('x', term.getChar(2, 2)); + assertNull(term.getCluster(2, 0)); + // in insert mode the second cell of a heart is made room for + vt100.setCursor(4, 0); + vt100.appendString("abc"); + vt100.setCursor(4, 0); + vt100.setInsertMode(true); + vt100.appendString(heart); + vt100.setInsertMode(false); + assertEquals("\u2764\000abc", new String(term.getChars(4), 0, 5)); + assertEquals(heart, term.getCluster(4, 0)); + // inserting and deleting cells moves clusters with them + vt100.setCursor(4, 0); + vt100.insertCharacters(1); + assertEquals(heart, term.getCluster(4, 1)); + vt100.deleteCharacters(1); + assertEquals(heart, term.getCluster(4, 0)); + // a heart made wide on the last two cells waits to wrap, as any wide character does + vt100.setVT100LineWrapping(true); + vt100.setCursor(5, 8); + vt100.appendString(heart + "y"); + assertEquals(heart, term.getCluster(5, 8)); + assertEquals('y', term.getChar(6, 0)); + } + + @Test + public void testClusterBoundaries() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(8); + vt100.setDimensions(8, 20); + String smile = "\ud83d\ude00"; + // UAX #29 GB11: after a joiner only a pictograph goes on, so x is a character of its own + vt100.setCursor(0, 0); + vt100.appendString(smile + "\u200dx"); + assertEquals(smile + "\u200d", term.getCluster(0, 0)); + assertEquals('x', term.getChar(0, 2)); + // a skin tone goes on with any character, which then takes two cells, as in Windows Terminal + vt100.setCursor(1, 0); + vt100.appendString("a\ud83c\udffd|"); + assertEquals("a\ud83c\udffd", term.getCluster(1, 0)); + assertEquals('|', term.getChar(1, 2)); + // a third regional indicator starts a flag of its own + vt100.setCursor(2, 0); + vt100.appendString("\ud83c\uddf0\ud83c\uddf7\ud83c\uddfa|"); + assertEquals("\ud83c\uddf0\ud83c\uddf7", term.getCluster(2, 0)); + assertEquals('|', term.getChar(2, 3)); // a regional indicator alone is narrow + // an Indic vowel sign goes with its consonant: one cluster, drawn whole over two cells + vt100.setCursor(3, 0); + vt100.appendString("\u0915\u093f|"); + assertEquals("\u0915\u093f", term.getCluster(3, 0)); + assertEquals('|', term.getChar(3, 2)); + // a selector goes onto the character just written, not onto a cluster before it + vt100.setCursor(4, 0); + vt100.appendString("q\u0301x\ufe0f|"); + assertEquals("q\u0301", term.getCluster(4, 0)); + assertEquals("x\ufe0f", term.getCluster(4, 1)); + assertEquals('|', term.getChar(4, 3)); + // a sequence of narrow pictographs with a joiner and a selector is one cluster, two cells + vt100.setCursor(5, 0); + vt100.appendString("\u26f9\u200d\u2642\ufe0f|"); + assertEquals("\u26f9\u200d\u2642\ufe0f", term.getCluster(5, 0)); + assertEquals('|', term.getChar(5, 2)); + // a character on the last cell that a selector makes wide moves whole to the next line + vt100.setVT100LineWrapping(true); + vt100.setCursor(6, 19); + vt100.appendString("x\ufe0f|"); + assertEquals('\000', term.getChar(6, 19)); + assertEquals("x\ufe0f", term.getCluster(7, 0)); + assertEquals('|', term.getChar(7, 2)); + // a prefix sign keeps the character after it, which is drawn and copied with it + vt100.setCursor(3, 10); + vt100.appendString("a\u0600\u4e2d|"); + assertEquals("\u0600\u4e2d", term.getCluster(3, 11)); + assertEquals('\u4e2d', term.getChar(3, 11)); + assertEquals('|', term.getChar(3, 13)); + // a terminal one column wide has no second cell for a heart to grow into: it keeps one + vt100.setDimensions(8, 1); + vt100.setCursor(0, 0); + vt100.appendString("\u2764\ufe0f"); + assertEquals("\u2764\ufe0f", term.getCluster(0, 0)); + assertEquals(1, term.getCellWidth(0, 0)); + assertEquals('\u2764', term.getChar(0, 0)); + vt100.setDimensions(8, 20); + // a cluster goes on in the next string written + vt100.setCursor(6, 0); + vt100.appendString(smile); + vt100.appendString("\u200d" + smile); + assertEquals(smile + "\u200d" + smile, term.getCluster(6, 0)); + } + + @Test + public void testClustersAcrossWritesAndWraps() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(4); + vt100.setDimensions(4, 4); + // a prefix sign and the character after it, written apart, still make one cluster + vt100.setCursor(0, 0); + vt100.appendString("\u0600"); + vt100.appendString("\u4e2d"); + assertEquals("\u0600\u4e2d", term.getCluster(0, 0)); + // but not once the cursor has moved, even back to where it was + vt100.setCursor(0, 2); + vt100.appendString("\u0600"); + vt100.setCursor(0, 0); + vt100.setCursor(0, 2); + vt100.appendString("x"); + assertNull(term.getCluster(0, 2)); + // with an immediate wrap, a mark after the last cell still goes onto it + vt100.setVT100LineWrapping(false); + vt100.setCursor(1, 0); + vt100.appendString("abce"); + vt100.appendString("\u0301"); + assertEquals('\u00e9', term.getChar(1, 3)); + assertEquals("e\u0301", term.getCluster(1, 3)); + assertEquals(0, vt100.getCursorColumn()); + // and a character there made wide moves whole to the line it wrapped to + vt100.setCursor(2, 0); + vt100.appendString("abc\u2764"); + vt100.appendString("\ufe0f|"); + assertEquals('\000', term.getChar(2, 3)); + assertEquals("\u2764\ufe0f", term.getCluster(3, 0)); + assertEquals('|', term.getChar(3, 2)); + } + + @Test + public void testClusterGrowingWideScrollsWithIt() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(2); + vt100.setDimensions(2, 4); + vt100.setVT100LineWrapping(false); + // a heart grown wide on the last two cells of the bottom row wraps, which scrolls: + // the cluster is written before that, and goes up with its row + vt100.setCursor(1, 2); + vt100.appendString("\u2764\ufe0f"); + assertEquals("\u2764\ufe0f", term.getCluster(0, 2)); + assertNull(term.getCluster(1, 2)); + } + + @Test + public void testClusterEdgeCases() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(4); + // a screen one row high: the row a mark goes back to after an immediate wrap is in the history + vt100.setDimensions(1, 4); + vt100.setVT100LineWrapping(false); + vt100.setCursor(0, 0); + vt100.appendString("abce"); + vt100.appendString("\u0301"); + assertEquals('\u00e9', term.getChar(term.getHeight() - 2, 3)); + assertEquals("e\u0301", term.getCluster(term.getHeight() - 2, 3)); + // on a screen one column wide nothing takes two cells, a cluster neither + vt100.setVT100LineWrapping(true); + vt100.setDimensions(1, 1); + vt100.setCursor(0, 0); + vt100.appendString("\u4e2d\u0301"); + assertEquals("\u4e2d\u0301", term.getCluster(term.getHeight() - 1, 0)); + assertEquals(1, term.getCellWidth(term.getHeight() - 1, 0)); + // the cells show the character a prefix sign goes before, not the sign + vt100.setDimensions(1, 8); + vt100.setCursor(0, 0); + vt100.appendString("\u0600\u4e2d\u0301"); + int row = term.getHeight() - 1; + assertEquals('\u4e2d', term.getChar(row, 0)); + assertEquals("\u0600\u4e2d\u0301", term.getCluster(row, 0)); + // so does a prefix sign beyond the BMP + vt100.setCursor(0, 6); + vt100.appendString("\ud804\udcbda"); // U+110BD, a prefix that takes no cell + assertEquals('a', term.getChar(row, 6)); + assertEquals("\ud804\udcbda", term.getCluster(row, 6)); + // a character beyond the BMP that composes into one inside it leaves a filler, not half a pair + vt100.setCursor(0, 3); + vt100.appendString("\ud87e\udc00\u0301"); // U+2F800, which NFC makes U+4E3D + assertEquals('\u4e3d', term.getChar(row, 3)); + assertEquals('\000', term.getChar(row, 4)); + assertEquals("\ud87e\udc00\u0301", term.getCluster(row, 3)); + } + + @Test + public void testInsertKeepsAClusterNextToTheMargin() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(2); + vt100.setDimensions(2, 10); + vt100.setVT100LineWrapping(true); + vt100.setCursor(0, 0); + vt100.appendString("abcdefx\u0301g\u4e2d"); + // the wide character is pushed off the end; the accented x moves two cells, its accent with it + vt100.setCursor(0, 0); + vt100.insertCharacters(2); + assertEquals("x\u0301", term.getCluster(0, 8)); + assertEquals(1, term.getCellWidth(0, 8)); + assertEquals(1, term.getCellWidth(0, 9)); + } + + @Test + public void testNothingHiddenAndNoEndlessCluster() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(2); + vt100.setDimensions(2, 20); + // control and format characters no cluster needs are kept out, so a copy shows what is drawn + vt100.setCursor(0, 0); + vt100.appendString("a\u0085\u202eb\u2066c\u2069\u200b\u200e\udb40\udc41d"); + assertEquals("abcd", new String(term.getChars(0), 0, 4)); + for (int col = 0; col < 4; col++) { + assertNull(term.getCluster(0, col)); + } + assertEquals(4, vt100.getCursorColumn()); + // the joiners and the tags of a flag stay + String england = "\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f"; + vt100.appendString(england + "\u0628\u200c\u0628"); + assertEquals(england, term.getCluster(0, 4)); + assertEquals("\u0628\u200c", term.getCluster(0, 6)); + // what only hides text: tags past a flag's six, and variation selectors not right after a character + vt100.setCursor(1, 0); + String tags = "\udb40\udc61".repeat(10); + vt100.appendString("\ud83c\udff4" + tags + "\udb40\udc7fx\ufe0f\ufe0f\u200d\ufe0f|"); + assertEquals("\ud83c\udff4" + "\udb40\udc61".repeat(6) + "\udb40\udc7f", term.getCluster(1, 0)); + assertEquals("x\ufe0f\u200d", term.getCluster(1, 2)); + assertEquals('|', term.getChar(1, 4)); + vt100.setCursor(1, 4); + vt100.appendString("y\u180b\u180b\u180ez"); // selectors: one, after a character; U+180E is no selector + assertEquals("y\u180b", term.getCluster(1, 4)); + assertEquals('z', term.getChar(1, 5)); + vt100.setCursor(1, 4); + vt100.appendString("a\u0308\u034f\u0323"); // the joiner keeps marks apart, so it stays + assertEquals("a\u0308\u034f\u0323", term.getCluster(1, 4)); + vt100.setCursor(1, 6); + vt100.appendString("\u0600\u0600\u0600" + "1"); // one prefix sign is enough + assertEquals("\u06001", term.getCluster(1, 6)); + // a flood of marks stops growing the cluster + vt100.setCursor(1, 0); + vt100.appendString("e" + "\u0301".repeat(10000) + "x"); + assertEquals(32, term.getCluster(1, 0).length()); + assertEquals('x', term.getChar(1, 1)); + } + + @Test + public void testClusterKeptPastTheMarginAndEndedByAMove() { + ITerminalTextData term = makeITerminalTextData(); + IVT100EmulatorBackend vt100 = makeBakend(term); + term.setMaxHeight(2); + vt100.setDimensions(2, 4); + // a line copied while narrowed keeps the layout of what it holds past the margin + vt100.setCursor(0, 0); + vt100.appendString("ab\u2764\ufe0f"); + vt100.setDimensions(2, 2); + term.copyLine(term, 0, 0); + vt100.setDimensions(2, 4); + assertEquals("\u2764\ufe0f", term.getCluster(0, 2)); + assertEquals(2, term.getCellWidth(0, 2)); + // moved away and back, the cursor no longer goes on with what it wrote + vt100.setCursor(1, 0); + vt100.appendString("\u0600"); + vt100.setCursor(0, 0); + vt100.setCursor(1, 1); + vt100.appendString("x"); + assertEquals('x', term.getChar(1, 1)); + assertEquals(2, vt100.getCursorColumn()); + } + + /** + * Only text can go on with the cluster written last: every other public command, + * one added later as well, ends it, and what is written after it is not joined + * to it however it left the cursor. + */ + @Test + public void testEveryCommandButWritingEndsTheCluster() throws Exception { + // settings that change no cell and move no cursor; a resize that changes the + // screen ends the cluster itself, one that changes nothing leaves it + Set text = Set.of("appendString", "setStyle", "setDefaultStyle", "setInsertMode", + "setVT100LineWrapping", "setScrollRegion", "setBufferLineLimit"); + int checked = 0; + for (Method method : VT100EmulatorBackend.class.getDeclaredMethods()) { + if (!Modifier.isPublic(method.getModifiers()) || method.getReturnType() != void.class + || text.contains(method.getName())) { + continue; + } + Object[] args = new Object[method.getParameterCount()]; + for (int i = 0; i < args.length; i++) { + Class type = method.getParameterTypes()[i]; + // a count of one; a buffer, though, holds at least the screen + int n = method.getName().equals("setBufferLineLimit") ? 100 : 1; + args[i] = type == int.class ? (Object) n : type == boolean.class ? (Object) false : null; + } + ITerminalTextData term = makeITerminalTextData(); + VT100EmulatorBackend vt100 = new VT100EmulatorBackend(term); + term.setMaxHeight(5); + vt100.setDimensions(5, 10); + vt100.setCursor(0, 0); + vt100.appendString("\u0600"); // a prefix: x right after it would join it + method.invoke(vt100, args); + vt100.appendString("x"); + assertNotEquals("\u0600x", Cells.text(term, 0, 0), method.getName()); + checked++; + } + assertTrue(checked >= 19, "commands checked: " + checked); + } } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorCellsTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorCellsTest.java new file mode 100644 index 00000000000..421677216b9 --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorCellsTest.java @@ -0,0 +1,229 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * All rights reserved. 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.terminal.internal.emulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.Random; + +import org.eclipse.terminal.internal.model.Cells; +import org.eclipse.terminal.internal.model.TerminalTextDataStore; +import org.eclipse.terminal.internal.textcanvas.AbstractTextCanvasModel; +import org.eclipse.terminal.model.ITerminalTextData; +import org.eclipse.terminal.model.ITerminalTextDataSnapshot; +import org.eclipse.terminal.model.LineSegment; +import org.eclipse.terminal.model.TerminalTextDataFactory; +import org.junit.jupiter.api.Test; + +/** + * Random writes and edits, checking after every step that the cells hold what + * {@link Cells} says they hold: what any path that writes cells has to keep. + */ +public class VT100EmulatorCellsTest { + + /** characters that are hard to lay out, and some that are not */ + private static final String[] PIECES = { "a", "x", " ", "1", "e", "\u4e2d", "\uac00", "\ud83d\ude00", + "\ud83d\udc68", "\u200d", "\ufe0f", "\ufe0e", "\u0301", "\u3099", "\u30ab", "\u0600", "\u200b", + "\ud83c\uddf0", "\ud83c\uddf7", "\ud83c\udffd", "\u1100", "\u1161", "\u11a8", "\u2764", "\u20e3", + "\u0915", "\u093f", "\ud87e\udc00", "\ufa6c", "\u3000" }; + + @Test + public void testRandomEditsKeepTheCellsConsistent() { + Random random = new Random(2904); + for (int run = 0; run < 400; run++) { + ITerminalTextData term = TerminalTextDataFactory.makeTerminalTextData(); + VT100EmulatorBackend vt100 = new VT100EmulatorBackend(term); + term.setMaxHeight(6); + vt100.setDimensions(1 + random.nextInt(4), 1 + random.nextInt(6)); + vt100.setVT100LineWrapping(random.nextBoolean()); + StringBuilder log = new StringBuilder(); + for (int step = 0; step < 60; step++) { + String op = step(vt100, random); + log.append(op).append("; "); //$NON-NLS-1$ + check(term, log); + } + } + } + + @Test + public void testSplitWritesGiveTheSameCells() { + Random random = new Random(29041); + for (int run = 0; run < 2000; run++) { + StringBuilder text = new StringBuilder(); + for (int i = random.nextInt(8); i >= 0; i--) { + text.append(PIECES[random.nextInt(PIECES.length)]); + } + int columns = 2 + random.nextInt(6); + boolean deferred = random.nextBoolean(); + String whole = cells(text.toString(), new int[0], columns, deferred); + if (text.chars().noneMatch(c -> c == 0x200b || c == 0xfe0e || c == 0xfe0f) + && !text.toString().contains("\u0600\u0600")) { //$NON-NLS-1$ + // what is written comes back whole, but for what is kept out because it only hides text + assertEquals(escape(text.toString()), escape(copied(text.toString(), columns, deferred)), + "copied back"); //$NON-NLS-1$ + } + int[] splits = random.ints(1 + random.nextInt(3), 0, text.length() + 1).sorted().toArray(); + assertEquals(whole, cells(text.toString(), splits, columns, deferred), + "split at " + java.util.Arrays.toString(splits) + " of " + escape(text.toString())); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** @return all the text, as copying it gives it back, after writing it alone */ + private static String copied(String text, int columns, boolean deferred) { + ITerminalTextData term = TerminalTextDataFactory.makeTerminalTextData(); + VT100EmulatorBackend vt100 = new VT100EmulatorBackend(term); + term.setMaxHeight(20); + vt100.setDimensions(20, columns); + vt100.setVT100LineWrapping(deferred); + vt100.appendString(text); + ITerminalTextDataSnapshot snapshot = term.makeSnapshot(); + snapshot.updateSnapshot(true); + String all = new AbstractTextCanvasModel(snapshot) { + }.getAllText(); + return all.substring(0, all.indexOf('\n') < 0 ? all.length() : all.indexOf('\n')); + } + + private static String cells(String text, int[] splits, int columns, boolean deferred) { + ITerminalTextData term = new TerminalTextDataStore(); + VT100EmulatorBackend vt100 = new VT100EmulatorBackend(term); + term.setMaxHeight(8); + vt100.setDimensions(4, columns); + vt100.setVT100LineWrapping(deferred); + int from = 0; + for (int split : splits) { + vt100.appendString(text.substring(from, split)); + from = split; + } + vt100.appendString(text.substring(from)); + StringBuilder cells = new StringBuilder(); + for (int line = 0; line < term.getHeight(); line++) { + for (int col = 0; col < columns; col++) { + cells.append(term.getCellWidth(line, col)).append(escape(Cells.text(term, line, col))).append('|'); + } + cells.append('\n'); + } + return cells.append(vt100.getCursorLine()).append(',').append(vt100.getCursorColumn()).toString(); + } + + private static String step(VT100EmulatorBackend vt100, Random random) { + int lines = vt100.getLines(); + int columns = vt100.getColumns(); + switch (random.nextInt(20)) { + case 0: + vt100.setCursor(random.nextInt(lines), random.nextInt(columns)); + return "cup"; //$NON-NLS-1$ + case 1: + vt100.setCursorColumn(0); + return "cr"; //$NON-NLS-1$ + case 2: + vt100.processNewline(); + return "lf"; //$NON-NLS-1$ + case 3: + vt100.eraseCharacters(1 + random.nextInt(3)); + return "ech"; //$NON-NLS-1$ + case 4: + vt100.insertCharacters(1 + random.nextInt(3)); + return "ich"; //$NON-NLS-1$ + case 5: + vt100.deleteCharacters(1 + random.nextInt(3)); + return "dch"; //$NON-NLS-1$ + case 6: + vt100.eraseLineToEnd(); + return "el0"; //$NON-NLS-1$ + case 7: + vt100.eraseLineToCursor(); + return "el1"; //$NON-NLS-1$ + case 8: + vt100.insertLines(1); + return "il"; //$NON-NLS-1$ + case 9: + vt100.deleteLines(1); + return "dl"; //$NON-NLS-1$ + case 10: + vt100.scrollUp(1); + return "su"; //$NON-NLS-1$ + case 11: + vt100.scrollDown(1); + return "sd"; //$NON-NLS-1$ + case 12: + int newColumns = 1 + random.nextInt(6); + vt100.setDimensions(lines, newColumns); + return "cols " + newColumns; //$NON-NLS-1$ + case 13: + boolean on = random.nextBoolean(); + vt100.setInsertMode(on); + return "irm " + on; //$NON-NLS-1$ + case 14: + boolean alternate = random.nextBoolean(); + vt100.enableAlternateScreen(alternate, true); + return "alt " + alternate; //$NON-NLS-1$ + case 15: + vt100.processReverseLineFeed(); + return "ri"; //$NON-NLS-1$ + default: + StringBuilder text = new StringBuilder(); + for (int i = random.nextInt(4); i >= 0; i--) { + text.append(PIECES[random.nextInt(PIECES.length)]); + } + vt100.appendString(text.toString()); + return "write " + escape(text.toString()); //$NON-NLS-1$ + } + } + + private static void check(ITerminalTextData term, CharSequence log) { + int width = term.getWidth(); + for (int line = 0; line < term.getHeight(); line++) { + for (int col = 0; col < width; col++) { + int cells = term.getCellWidth(line, col); + if (cells == 2 && (col + 1 >= width || term.getCellWidth(line, col + 1) != 0)) { + fail("two cells without a second one at " + line + "," + col + " after " + log); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + if (cells == 0 && term.getCluster(line, col) != null) { + fail("a cluster on a second cell at " + line + "," + col + " after " + log); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + String text = Cells.text(term, line, col); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + boolean paired = Character.isHighSurrogate(c) ? i + 1 < text.length() && Character.isLowSurrogate(text.charAt(i + 1)) + : !Character.isLowSurrogate(c) || i > 0 && Character.isHighSurrogate(text.charAt(i - 1)); + if (!paired) { + fail("half a surrogate pair at " + line + "," + col + " after " + log); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + } + // selecting, copying and the word under the pointer read the same cells + ITerminalTextDataSnapshot snapshot = term.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + model.getAllText(); + for (int line = 0; line < term.getHeight(); line++) { + for (LineSegment segment : snapshot.getLineSegments(line, 0, width)) { + Cells.drawn(snapshot, line, segment.getColumn(), segment.getText()); // what is drawn + } + } + for (int line = 0; line < term.getHeight(); line++) { + for (int col = 0; col < width; col++) { + model.setSelection(line, line, col, col); + model.expandHoverSelectionAt(-1, -1); + model.expandHoverSelectionAt(line, col); + } + } + snapshot.detach(); + } + + private static String escape(String text) { + StringBuilder escaped = new StringBuilder(); + text.chars().forEach(c -> escaped.append(c < 0x80 ? Character.toString(c) : String.format("\\u%04x", c))); //$NON-NLS-1$ + return escaped.toString(); + } +} diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorTest.java index 32366a9f172..071e06f9157 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorTest.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/VT100EmulatorTest.java @@ -599,8 +599,9 @@ public void testModifiedSpecialKeys() { // xterm's spelling: CSI number ; modifier final, with 2 shift, 3 alt, 5 control and their sums Map keys = Map.ofEntries(Map.entry(SWT.ARROW_UP, "1;%dA"), Map.entry(SWT.ARROW_DOWN, "1;%dB"), Map.entry(SWT.ARROW_RIGHT, "1;%dC"), Map.entry(SWT.ARROW_LEFT, "1;%dD"), Map.entry(SWT.HOME, "1;%dH"), - Map.entry(SWT.END, "1;%dF"), Map.entry(SWT.INSERT, "2;%d~"), Map.entry(SWT.PAGE_UP, "5;%d~"), - Map.entry(SWT.PAGE_DOWN, "6;%d~"), Map.entry(SWT.F1, "1;%dP"), Map.entry(SWT.F2, "1;%dQ"), + Map.entry(SWT.END, "1;%dF"), Map.entry(SWT.INSERT, "2;%d~"), Map.entry((int) SWT.DEL, "3;%d~"), + Map.entry(SWT.PAGE_UP, "5;%d~"), Map.entry(SWT.PAGE_DOWN, "6;%d~"), Map.entry(SWT.F1, "1;%dP"), + Map.entry(SWT.F2, "1;%dQ"), Map.entry(SWT.F3, "1;%dR"), Map.entry(SWT.F4, "1;%dS"), Map.entry(SWT.F5, "15;%d~"), Map.entry(SWT.F6, "17;%d~"), Map.entry(SWT.F7, "18;%d~"), Map.entry(SWT.F8, "19;%d~"), Map.entry(SWT.F9, "20;%d~"), Map.entry(SWT.F10, "21;%d~"), Map.entry(SWT.F11, "23;%d~"), @@ -617,6 +618,39 @@ public void testModifiedSpecialKeys() { assertEquals(null, VT100TerminalControl.modifiedSpecialKey(SWT.ARROW_LEFT, SWT.COMMAND | SWT.SHIFT)); } + @Test + public void testCtrlCharacter() { + // xterm: Ctrl+2 to Ctrl+8 are NUL, ESC, FS, GS, RS, US and DEL + assertEquals("\u0000\u001b\u001c\u001d\u001e\u001f\u007f", + "2345678".chars().map(c -> VT100TerminalControl.ctrlCharacter((char) c)) + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()); + assertEquals('\u0000', VT100TerminalControl.ctrlCharacter(' ')); + assertEquals('\u001f', VT100TerminalControl.ctrlCharacter('/')); + assertEquals('1', VT100TerminalControl.ctrlCharacter('1')); + assertEquals('\u0016', VT100TerminalControl.ctrlCharacter('\u0016')); + } + + @Test + public void testAltSendsEscape() { + assertTrue(VT100TerminalControl.altSendsEscape(SWT.ALT, 'f')); + assertTrue(VT100TerminalControl.altSendsEscape(SWT.ALT | SWT.SHIFT, 'F')); + // a real Ctrl+Alt+V gives a control character and keeps its Alt + assertTrue(VT100TerminalControl.altSendsEscape(SWT.CTRL | SWT.ALT, '\u0016')); + // AltGr+Q on a German keyboard: Ctrl+Alt with the '@' it types, no ESC + assertFalse(VT100TerminalControl.altSendsEscape(SWT.CTRL | SWT.ALT, '@')); + assertFalse(VT100TerminalControl.altSendsEscape(SWT.CTRL, '\u0016')); + assertFalse(VT100TerminalControl.altSendsEscape(0, 'f')); + } + + @Test + public void testAlternateScreenIsReported() { + assertFalse(emulator.isAlternateScreen()); + run("\u001b[?1049h"); + assertTrue(emulator.isAlternateScreen()); + run("\u001b[?1049l"); + assertFalse(emulator.isAlternateScreen()); + } + @Test public void testDecPrivateModes() { // the cursor hidden and shown again by a program @@ -666,6 +700,21 @@ public void testFullResetEndsDecPrivateModes() { assertAll(() -> assertTrue(control.isCursorShown()), () -> assertFalse(control.isBracketedPaste())); } + @Test + public void testSynchronizedOutput() { + // a program begins and ends a screen with mode 2026 + run("\u001b[?2026h"); + assertTrue(control.isSynchronizedOutput()); + run("\u001b[?2026l"); + assertFalse(control.isSynchronizedOutput()); + // a program that began one and was cut off or reset does not leave the view frozen + run("\u001b[?2026h"); + emulator.resetState(); + assertFalse(control.isSynchronizedOutput()); + run("\u001b[?2026h\u001bc"); + assertFalse(control.isSynchronizedOutput()); + } + @Test public void testPasteText() { // each line break goes as a CR, as the Enter key sends it: a Windows CR LF is one break @@ -678,4 +727,25 @@ public void testPasteText() { assertEquals(start + "[20[201~1~x" + end, VT100TerminalControl.pasteText("\033[20\033[201~1~x", true)); assertEquals(start + "201~x" + end, VT100TerminalControl.pasteText("\u009b201~x", true)); } + + @Test + public void testMouseModes() { + // how ncurses turns the mouse on: both modes in one sequence + run("\u001b[?1006;1000h"); + assertAll(() -> assertEquals(1000, control.getMouseMode()), () -> assertTrue(control.isSgrMouseEncoding())); + run("\u001b[?1002h"); + assertEquals(1002, control.getMouseMode()); + run("\u001b[?1000;1006l"); + assertAll(() -> assertEquals(0, control.getMouseMode()), () -> assertFalse(control.isSgrMouseEncoding())); + } + + @Test + public void testResetStateEndsMouseModes() { + run("\u001b[?1002;1006h"); + assertAll(() -> assertEquals(1002, control.getMouseMode()), () -> assertTrue(control.isSgrMouseEncoding())); + // a program cut off while listening to the mouse must not leave the next + // connection with it + emulator.resetState(); + assertAll(() -> assertEquals(0, control.getMouseMode()), () -> assertFalse(control.isSgrMouseEncoding())); + } } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AbstractITerminalTextDataTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AbstractITerminalTextDataTest.java index f205b8447db..29c8b41fedc 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AbstractITerminalTextDataTest.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AbstractITerminalTextDataTest.java @@ -13,6 +13,7 @@ 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.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -663,4 +664,45 @@ public void testWrappedLines() { term.clearWrappedLine(2); assertFalse(term.isWrappedLine(2)); } + + @Test + public void testClusters() { + ITerminalTextData term = makeITerminalTextData(); + term.setDimensions(4, 6); + term.setMaxHeight(4); + fill(term, "abcdef\nghijkl\nmnopqr\nstuvwx"); + String heart = "\u2764\ufe0f"; // made wide by VS16: two cells + assertNull(term.getCluster(1, 2)); + term.setCluster(1, 2, heart); + assertEquals(heart, term.getCluster(1, 2)); + // writing nothing, even at its second cell, leaves it as it is + term.setChars(1, 3, new char[0], null); + assertEquals(heart, term.getCluster(1, 2)); + // writing either of its cells forgets a cluster + term.setChar(1, 3, 'X', null); + assertNull(term.getCluster(1, 2)); + term.setCluster(1, 2, heart); + term.setChars(1, 0, new char[] { 'y', 'z' }, null); + assertEquals(heart, term.getCluster(1, 2)); // untouched cells keep theirs + term.setChars(1, 1, new char[] { 'y', 'z' }, null); + assertNull(term.getCluster(1, 2)); + // a narrow character with a mark has one cell: writing the next one keeps it + term.setCluster(1, 2, "q\u0301"); + term.setChar(1, 3, 'X', null); + assertEquals("q\u0301", term.getCluster(1, 2)); + // a cluster goes with its line when lines scroll, and is gone with a cleaned line + term.setCluster(2, 0, heart); + term.scroll(0, 4, -1); + assertEquals(heart, term.getCluster(1, 0)); + assertNull(term.getCluster(2, 0)); + term.cleanLine(1); + assertNull(term.getCluster(1, 0)); + // and is copied with its line, also onto itself + term.setCluster(0, 4, heart); + term.copyLine(term, 0, 0); + assertEquals(heart, term.getCluster(0, 4)); + ITerminalTextData copy = makeITerminalTextData(); + copy.copy(term); + assertEquals(heart, copy.getCluster(0, 4)); + } } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AllTestSuite.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AllTestSuite.java index 236b1b61dc8..02ce35e57af 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AllTestSuite.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/AllTestSuite.java @@ -21,6 +21,7 @@ */ @Suite @SelectClasses({ // + CellsTest.class, // CharWidthTest.class, // SnapshotChangesTest.class, // SynchronizedTerminalTextDataTest.class, // diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CellsTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CellsTest.java new file mode 100644 index 00000000000..c71bba2c87f --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CellsTest.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * All rights reserved. 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.terminal.internal.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CellsTest { + + private static TerminalTextDataStore line(String cells, int width) { + TerminalTextDataStore data = new TerminalTextDataStore(); + data.setDimensions(1, width); + data.setChars(0, 0, cells.toCharArray(), null); + return data; + } + + private static String widths(TerminalTextDataStore data) { + StringBuilder widths = new StringBuilder(); + for (int col = 0; col < data.getWidth(); col++) { + widths.append(data.getCellWidth(0, col)); + } + return widths.toString(); + } + + @Test + public void testWideCharacters() { + // a wide character of the BMP and its filler, a pair beyond it, and empty cells + TerminalTextDataStore data = line("\uac00\000\ud83d\ude00a\000", 6); + assertEquals("202011", widths(data)); + assertEquals(0, Cells.start(data, 0, 1)); + assertEquals(2, Cells.start(data, 0, 3)); + assertEquals("\uac00", Cells.text(data, 0, 0)); + assertEquals("", Cells.text(data, 0, 1)); + assertEquals("\ud83d\ude00", Cells.text(data, 0, 2)); + assertEquals("", Cells.text(data, 0, 5)); // never written + // only the first null after a wide character is its filler + assertEquals("2011", widths(line("\uac00\000\000a", 4))); + // a lone low surrogate is a character of its own, and so is one cut off by the margin + assertEquals("11", widths(line("\ude00a", 2))); + assertEquals("11", widths(line("a\uac00", 2))); + } + + @Test + public void testClusters() { + TerminalTextDataStore data = line("\u2764\000e|", 4); + data.setCluster(0, 0, "\u2764\ufe0f"); // a heart made wide by VS16 + data.setCluster(0, 2, "e\u0301"); // an accent with its letter, in one cell + assertEquals("2011", widths(data)); + assertEquals("\u2764\ufe0f", Cells.text(data, 0, 0)); + assertEquals("\u00e9", Cells.drawn(data, 0, 2)); + assertEquals("e\u0301", Cells.text(data, 0, 2)); + // a cluster of two cells needs its second one: written over, it is one cell + data.setChars(0, 0, "\u2764x".toCharArray(), null); + assertEquals("1111", widths(data)); + } + + @Test + public void testTextOfRange() { + TerminalTextDataStore data = line("a\000\uac00\000b\000\000", 7); + assertEquals("a \uac00b", Cells.text(data, 0, 0, 7)); // never written: a space, none at the end + assertEquals(" \uac00", Cells.text(data, 0, 1, 4)); // the empty cell after a narrow character is a space + assertEquals("\uac00", Cells.text(data, 0, 2, 4)); + assertEquals("b", Cells.text(data, 0, 3, 7)); // a character that starts before the range is not in it + } +} diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CharWidthTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CharWidthTest.java index 4602340b863..be0577daf75 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CharWidthTest.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/CharWidthTest.java @@ -10,8 +10,6 @@ package org.eclipse.terminal.internal.model; 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.junit.jupiter.api.Test; @@ -57,27 +55,4 @@ public void testOfString() { assertEquals(1, CharWidth.ofString("é")); // combining mark adds nothing } - @Test - public void testIsFiller() { - assertTrue(CharWidth.isFiller("ź°€\000", 1)); - // a character beyond the BMP covers its two cells with its surrogates, - // so the null after it is an empty cell, not a filler - assertFalse(CharWidth.isFiller("šŸ˜€\000", 2)); - assertFalse(CharWidth.isFiller("šŸ˜€\000a", 2)); - assertFalse(CharWidth.isFiller("a\000", 1)); // an empty cell after a narrow character - assertFalse(CharWidth.isFiller("\000a", 0)); - assertFalse(CharWidth.isFiller("ab", 1)); - assertFalse(CharWidth.isFiller("ź°€\000\000", 2)); // only the first null is the filler - } - - @Test - public void testIsSecondCell() { - assertTrue(CharWidth.isSecondCell("ź°€\000", 1)); // the filler - assertTrue(CharWidth.isSecondCell("šŸ˜€", 1)); // the low surrogate - assertFalse(CharWidth.isSecondCell("ź°€\000", 0)); - assertFalse(CharWidth.isSecondCell("šŸ˜€", 0)); - assertFalse(CharWidth.isSecondCell("a\000", 1)); - assertFalse(CharWidth.isSecondCell("ab", 1)); - assertFalse(CharWidth.isSecondCell("\uDE00a", 0)); // a lone low surrogate has nothing before it - } } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/TerminalTextDataWindowTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/TerminalTextDataWindowTest.java index b4be30273ad..85f41a84b00 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/TerminalTextDataWindowTest.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/model/TerminalTextDataWindowTest.java @@ -15,6 +15,7 @@ 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.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -446,4 +447,17 @@ public void testWrappedLines() { assertFalse(term.isWrappedLine(3)); term.clearWrappedLine(0); // outside window, harmless } + + @Override + @Test + public void testClusters() { + ITerminalTextData term = makeITerminalTextData(); + term.setDimensions(4, 6); + term.setCluster(0, 2, "\u2764\ufe0f"); // outside window + term.setCluster(3, 2, "\u2764\ufe0f"); + assertNull(term.getCluster(0, 2)); + assertEquals("\u2764\ufe0f", term.getCluster(3, 2)); + term.setChar(3, 3, 'X', null); + assertNull(term.getCluster(3, 2)); + } } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasModelTest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasModelTest.java index ecc792c2fa1..ec6c176a481 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasModelTest.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasModelTest.java @@ -12,6 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Display; import org.eclipse.terminal.internal.model.TerminalTextData; import org.eclipse.terminal.model.ITerminalTextDataSnapshot; import org.junit.jupiter.api.Test; @@ -55,6 +56,22 @@ public void testHoverWideSpaceIsBoundary() { assertEquals(new Point(3, 0), model.getHoverSelectionStart()); } + @Test + public void testHoverPrefixedSpaceIsBoundary() { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(1, 10); + // the space shown in the cell ends a word, whatever prefix was written before it + data.setChars(0, 0, "a b".toCharArray(), null); + data.setCluster(0, 1, "\u0600 "); + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + model.expandHoverSelectionAt(0, 2); + assertEquals("b", model.getHoverSelectionText()); + assertEquals(new Point(2, 0), model.getHoverSelectionStart()); + } + @Test public void testSelectionCoversWideCharactersWhole() { TerminalTextData data = new TerminalTextData(); @@ -86,4 +103,143 @@ public void testCopyKeepsSpacesBeforeAFold() { model.setSelection(0, 1, 0, 3); assertEquals("foo bar", model.getSelectedText()); } + + @Test + public void testSynchronizedOutputHoldsTheViewBackForAWhile() throws InterruptedException { + Display display = Display.getCurrent() != null ? null : new Display(); + try { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(3, 4); + data.setChars(0, 0, "a".toCharArray(), null); + data.setChars(1, 0, "b".toCharArray(), null); + data.setChars(2, 0, "c".toCharArray(), null); + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + PollingTextCanvasModel model = new PollingTextCanvasModel(snapshot); + model.stopPolling(); + model.setVisibleRectangle(0, 0, 3, 4); + model.setSynchronizedOutput(true); + data.setChars(1, 0, "x".toCharArray(), null); + model.update(); + assertEquals('b', model.getTerminalText().getChar(1, 0)); + // a scroll waits like a poll, and the lines already shown stay where they are + model.setVisibleRectangle(1, 0, 2, 4); + assertEquals(0, snapshot.getInterestWindowStartLine()); + assertEquals('b', model.getTerminalText().getChar(1, 0)); + assertEquals('c', model.getTerminalText().getChar(2, 0)); + // a new screen begun meanwhile does not hold the view back longer + Thread.sleep(150); + model.setSynchronizedOutput(false); + model.setSynchronizedOutput(true); + Thread.sleep(100); + model.update(); + assertEquals(1, snapshot.getInterestWindowStartLine()); + data.setChars(2, 0, "y".toCharArray(), null); + model.setSynchronizedOutput(false); + model.update(); + assertEquals('y', model.getTerminalText().getChar(2, 0)); + } finally { + if (display != null) { + display.dispose(); + } + } + } + + @Test + public void testSelectionCoversWideClusterWhole() { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(1, 10); + data.setChars(0, 0, "\u2764\000|".toCharArray(), null); + data.setCluster(0, 0, "\u2764\ufe0f"); // a heart made wide by VS16 + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + for (int col : new int[] { 0, 1 }) { + model.setSelection(0, 0, col, col); + assertEquals("\u2764\ufe0f", model.getSelectedText()); + } + } + + @Test + public void testCopiesClusters() { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(1, 12); + // a black cat ends in a wide character of the BMP: the empty cells after it stay spaces + data.setChars(0, 0, "\ud83d\udc08\000\000x".toCharArray(), null); + data.setCluster(0, 0, "\ud83d\udc08\u200d\u2b1b"); + data.setChars(0, 6, new char[] { '\u00e9' }, null); + data.setCluster(0, 6, "e\u0301"); + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + model.setSelection(0, 0, 0, 11); + assertEquals("\ud83d\udc08\u200d\u2b1b x e\u0301", model.getSelectedText()); + assertEquals("\ud83d\udc08\u200d\u2b1b x e\u0301", model.getAllText()); + } + + @Test + public void testCopyKeepsWhatANarrowedScreenHolds() { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(1, 6); + data.setChars(0, 0, "abcde\ud55c".toCharArray(), null); + data.setDimensions(1, 3); + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + // the row comes whole, as it does again when the screen widens + assertEquals("abcde\ud55c", model.getAllText()); + model.setSelection(0, 0, 0, 2); + assertEquals("abcde\ud55c", model.getSelectedText()); + // a selection that ends inside the screen ends there + model.setSelection(0, 0, 0, 1); + assertEquals("ab", model.getSelectedText()); + // a pair the margin cuts comes whole, though the screen shows no half of it + TerminalTextData pair = new TerminalTextData(); + pair.setDimensions(1, 4); + pair.setChars(0, 0, "ab\ud83d\ude00".toCharArray(), null); + pair.setDimensions(1, 3); + ITerminalTextDataSnapshot narrowed = pair.makeSnapshot(); + narrowed.updateSnapshot(true); + assertEquals("ab\ud83d\ude00", new AbstractTextCanvasModel(narrowed) { + }.getAllText()); + } + + @Test + public void testHoverWordKeepsClusters() { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(1, 8); + data.setChars(0, 0, "a\u2764\000b c".toCharArray(), null); + data.setCluster(0, 1, "\u2764\ufe0f"); // a heart made wide by VS16 + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + model.expandHoverSelectionAt(0, 0); + assertEquals("a\u2764\ufe0fb", model.getHoverSelectionText()); + } + + @Test + public void testHoverAfterResizeAndWideClusters() { + TerminalTextData data = new TerminalTextData(); + data.setDimensions(1, 5); + data.setChars(0, 0, "abcde".toCharArray(), null); + data.setDimensions(1, 4); // the row keeps all five characters + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(true); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + model.expandHoverSelectionAt(0, 1); + assertEquals("abcd", model.getHoverSelectionText()); + // the empty cell after a wide character with a mark is still a gap + data.setDimensions(1, 6); + data.setChars(0, 0, "\u4e2d\000\000x".toCharArray(), null); + data.setCluster(0, 0, "\u4e2d\u0301"); + snapshot.updateSnapshot(true); + model.expandHoverSelectionAt(-1, -1); // let go of the last hover first + model.expandHoverSelectionAt(0, 0); + assertEquals("\u4e2d\u0301", model.getHoverSelectionText()); + } } diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseFuzzUITest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseFuzzUITest.java new file mode 100644 index 00000000000..023989ebe12 --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseFuzzUITest.java @@ -0,0 +1,147 @@ +/******************************************************************************* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * All rights reserved. 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.terminal.internal.textcanvas; + +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.util.Random; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.terminal.internal.model.TerminalTextData; +import org.eclipse.terminal.model.ITerminalTextDataSnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Presses, releases, moves and double-clicks in random order, with and without + * shift, while a program that takes some presses and not others listens: whatever + * the order, a gesture stays on one side. The program gets a release for every + * press it got and for no other, and a drag only of a button whose press it got. + */ +public class TextCanvasMouseFuzzUITest { + + private static final int[] BUTTON_MASKS = { 0, SWT.BUTTON1, SWT.BUTTON2, SWT.BUTTON3 }; + + private Display display; + private Shell shell; + private TextCanvas canvas; + private final Random random = new Random(2902); + // the buttons whose press the program got and whose release it has not + private int programHolds; + private boolean shift; + + @BeforeEach + public void createCanvas() { + display = Display.getCurrent() != null ? null : new Display(); + shell = new Shell(); + TerminalTextData data = new TerminalTextData(); + data.setDimensions(24, 80); + ITerminalTextDataSnapshot snapshot = data.makeSnapshot(); + snapshot.updateSnapshot(false); + AbstractTextCanvasModel model = new AbstractTextCanvasModel(snapshot) { + }; + canvas = new TextCanvas(shell, model, SWT.NONE, new TextLineRenderer(() -> canvas, model)); + canvas.setSize(400, 300); + canvas.setMouseButtonHandler(new TextCanvas.IMouseButtonHandler() { + @Override + public boolean mouseButton(int button, int modifiers, Point cell, boolean pressed) { + int bit = 1 << button; + if (pressed) { + assertFalse(shift, "a press with shift is the terminal's"); + assertEquals(0, programHolds & bit, "a second press of a button the program holds"); + // a program that does not listen at the moment declines it + if (random.nextInt(5) == 0) { + return false; + } + programHolds |= bit; + } else { + assertTrue((programHolds & bit) != 0, "a release of a press the program never got"); + programHolds &= ~bit; + } + return true; + } + + @Override + public boolean mouseMoved(int button, int modifiers, Point cell) { + if (button != 0) { + assertTrue((programHolds & 1 << button) != 0, "a drag of a button whose press was the terminal's"); + } + return true; + } + }); + } + + @AfterEach + public void dispose() { + shell.dispose(); + if (display != null) { + display.dispose(); + } + } + + @Test + public void aGestureStaysOnOneSide() { + int down = 0; // the buttons physically down + for (int step = 0; step < 20000; step++) { + shift = random.nextInt(4) == 0; + int button = 1 + random.nextInt(3); + int bit = 1 << button; + switch (random.nextInt(4)) { + case 0: + if ((down & bit) == 0) { + send(SWT.MouseDown, button, down); + down |= bit; + if (random.nextBoolean()) { + send(SWT.MouseDoubleClick, button, down); + } + } + break; + case 1: + if ((down & bit) != 0) { + send(SWT.MouseUp, button, down); + down &= ~bit; + } + break; + default: + send(SWT.MouseMove, 0, down); + } + } + shift = false; + for (int button = 1; button <= 3; button++) { + if ((down & 1 << button) != 0) { + send(SWT.MouseUp, button, down); + down &= ~(1 << button); + } + } + assertEquals(0, programHolds, "presses the program never got the release of"); + } + + private void send(int type, int button, int down) { + Event event = new Event(); + event.button = button; + int state = shift ? SWT.SHIFT : 0; + for (int b = 1; b <= 3; b++) { + if ((down & 1 << b) != 0) { + state |= BUTTON_MASKS[b]; + } + } + event.stateMask = state; + event.x = random.nextInt(400); + event.y = random.nextInt(300); + canvas.notifyListeners(type, event); + } +} diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseUITest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseUITest.java new file mode 100644 index 00000000000..ed464743875 --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseUITest.java @@ -0,0 +1,137 @@ +/******************************************************************************* + * Copyright (c) 2026 Eclipse contributors 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.terminal.internal.textcanvas; + + +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.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.terminal.connector.ITerminalConnector; +import org.eclipse.terminal.connector.TerminalState; +import org.eclipse.terminal.control.ITerminalListener; +import org.eclipse.terminal.control.TerminalTitleRequestor; +import org.eclipse.terminal.internal.emulator.VT100TerminalControl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * A click a program listening to the mouse takes is its alone: the terminal's own + * listeners (the middle-click paste, the copy on release, a double-click) and its + * context menu do not get it too. Shift keeps the click for the terminal. + */ +public class TextCanvasMouseUITest { + + private Display display; + private Shell shell; + private VT100TerminalControl terminal; + private TextCanvas canvas; + private final List reported = new ArrayList<>(); + private final List seenByOthers = new ArrayList<>(); + + @BeforeEach + public void createTerminal() { + display = Display.getCurrent() != null ? null : new Display(); + shell = new Shell(); + shell.setLayout(new FillLayout()); + ITerminalListener listener = new ITerminalListener() { + @Override + public void setState(TerminalState state) { + } + + @Override + public void setTerminalSelectionChanged() { + } + + @Override + public void setTerminalTitle(String title, TerminalTitleRequestor requestor) { + } + }; + terminal = new VT100TerminalControl(listener, new Composite(shell, 0), new ITerminalConnector[0], + new PreferenceStore()); + canvas = (TextCanvas) terminal.getControl(); + // a program listening to the mouse + canvas.setMouseButtonHandler(new TextCanvas.IMouseButtonHandler() { + @Override + public boolean mouseButton(int button, int modifiers, Point cell, boolean pressed) { + reported.add(button + (pressed ? " down" : " up")); + return true; + } + + @Override + public boolean mouseMoved(int button, int modifiers, Point cell) { + return true; + } + }); + // as the middle-click paste of the terminals view listens: added after the canvas's own + for (int type : new int[] { SWT.MouseDown, SWT.MouseUp, SWT.MouseDoubleClick }) { + canvas.addListener(type, e -> seenByOthers.add(e.type)); + } + } + + @AfterEach + public void dispose() { + terminal.disposeTerminal(); + shell.dispose(); + if (display != null) { + display.dispose(); + } + } + + private Event send(int type, int button, int stateMask) { + Event event = new Event(); + event.button = button; + event.stateMask = stateMask; + event.x = 1; + event.y = 1; + event.detail = SWT.MENU_MOUSE; + canvas.notifyListeners(type, event); + return event; + } + + @Test + public void aClickTheProgramTakesGoesNoFurther() { + for (int button : new int[] { 1, 2, 3 }) { + send(SWT.MouseDown, button, 0); + send(SWT.MouseDoubleClick, button, 0); + send(SWT.MouseUp, button, 0); + } + assertEquals(List.of("1 down", "1 up", "2 down", "2 up", "3 down", "3 up"), reported); + assertTrue(seenByOthers.isEmpty(), "seen by the terminal's own listeners: " + seenByOthers); + // and the right-click opens no context menu, while the menu key still does + assertFalse(send(SWT.MenuDetect, 3, 0).doit); + Event key = new Event(); + key.detail = SWT.MENU_KEYBOARD; + canvas.notifyListeners(SWT.MenuDetect, key); + assertTrue(key.doit); + } + + @Test + public void shiftKeepsTheClickForTheTerminal() { + send(SWT.MouseDown, 2, SWT.SHIFT); + send(SWT.MouseUp, 2, SWT.SHIFT); + assertTrue(reported.isEmpty()); + assertEquals(List.of(SWT.MouseDown, SWT.MouseUp), seenByOthers); + assertTrue(send(SWT.MenuDetect, 3, SWT.SHIFT).doit); + } +} diff --git a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/test/AutomatedTestSuite.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/test/AutomatedTestSuite.java index e8673b2cf64..013c89bca79 100644 --- a/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/test/AutomatedTestSuite.java +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/test/AutomatedTestSuite.java @@ -28,6 +28,9 @@ org.eclipse.terminal.internal.connector.TerminalToRemoteInjectionOutputStreamTest.class, // org.eclipse.terminal.internal.textcanvas.TerminalControlRecreateUITest.class, // org.eclipse.terminal.internal.emulator.TerminalPasteUITest.class, // + org.eclipse.terminal.internal.emulator.TerminalMouseWheelUITest.class, // + org.eclipse.terminal.internal.textcanvas.TextCanvasMouseUITest.class, // + org.eclipse.terminal.internal.textcanvas.TextCanvasMouseFuzzUITest.class, // org.eclipse.terminal.view.ui.tests.InputChunksTest.class, // org.eclipse.terminal.view.ui.tests.TerminalsViewReorderTest.class, // })