From ebe1cefc189d1caf907af207e3fc6f0d92d39561 Mon Sep 17 00:00:00 2001 From: insjang Date: Fri, 13 Nov 2026 16:45:37 +0900 Subject: [PATCH] Terminal: report the mouse to programs that ask for it Programs that draw their own screen - htop, ncurses menus, and lately CLIs with clickable options and wheel scrolling - ask the terminal for mouse events with DEC modes 1000 (presses and releases), 1002 (also drags) and 1003 (every move), in xterm's legacy encoding or the SGR one (mode 1006). The terminal ignored the request and kept every click for its own selection, so such programs could not be clicked on or scrolled. The canvas now hands presses, releases, moves and the wheel to the control while a program has asked for them, with the alt and control keys folded into the button as xterm does. A click the program takes is the program's alone, as in xterm and GNOME Terminal: the middle-click does not also paste, the right-click opens no context menu (the menu key still does), and neither a double-click nor the copy on release acts on it. The canvas reports it in a listener that runs before every other and stops the event there. Shift keeps the mouse, the wheel included, for the terminal, which is the convention every terminal uses to still allow a selection while a program is listening; a button held down drags for the program only if its press went there. A wheel notch is three of the lines SWT counts, however its events split them, the rest counting toward the next notch in the same direction; Windows set to scroll a page at a time counts notches, which are taken as such. Another number of lines per notch in the Windows settings is not known to SWT's API and still counts as lines. Positions are the program's screen, counted from its first line, not from the top of the view: with history above the screen the view rarely starts on a whole line, and a click over the history the user scrolled back to is the terminal's, not the program's. Past column or row 223, where the legacy encoding has no room, the position is a zero byte, as xterm sends it, so a drag past it still ends in a release; a release in it keeps the alt and control bits of its press. A report is sent as bytes, not through the terminal's text encoding, so a column or row past 95 stays the one byte the legacy encoding means. A press that went to the program takes the terminal's selection away, and a left one becomes the selection anchor, so a later shift-drag starts from where the user last clicked rather than from a selection made long before; once the program stops or starts listening, that click is forgotten. A press while a button of the terminal's own selection is held stays the terminal's, and a right press the program took opens no context menu, whatever is pressed before its release. A release goes wherever its press went, whatever the keyboard state by then, so press and release always reach the same side. Whose a gesture is, the program's or the terminal's, is decided in one place, MouseRouter, when the button is pressed, and the drag, release, double-click and context menu that follow read that answer instead of deciding again. What a program has been told (the last cell, the wheel lines short of a notch) lives in a session that a new mode replaces whole, so nothing carries over to the next program. This builds on the DEC private mode parsing change (every parameter in a set/reset), since ncurses turns the mouse on with CSI ? 1006 ; 1000 h. A reset, which runs before every connection, turns mouse reporting and SGR mouse encoding off, and nothing is reported while the terminal is not connected: a program cut off while it listened left the reports on for the next connection, and a click in between threw from writing to an output stream that no longer existed. The modes are written by the reader job and read on the display thread, so they are volatile, as is application cursor keys, which had the same gap. The horizontal wheel and the back and forward buttons are not reported. MouseReport.mouseReport is public, as the test bundle calls it across the bundle boundary. --- .../control/impl/ITerminalControlForText.java | 18 ++ .../internal/emulator/VT100Emulator.java | 23 ++ .../emulator/VT100TerminalControl.java | 212 ++++++++++++++++- .../internal/textcanvas/GridCanvas.java | 17 +- .../internal/textcanvas/MouseRouter.java | 154 +++++++++++++ .../internal/textcanvas/TextCanvas.java | 96 ++++++++ .../internal/emulator/AllTestSuite.java | 1 + .../emulator/MockTerminalControlForText.java | 21 ++ .../internal/emulator/MouseReportTest.java | 82 +++++++ .../emulator/TerminalMouseWheelUITest.java | 166 +++++++++++++ .../internal/emulator/VT100EmulatorTest.java | 21 ++ .../textcanvas/TextCanvasMouseFuzzUITest.java | 157 +++++++++++++ .../textcanvas/TextCanvasMouseUITest.java | 218 ++++++++++++++++++ .../terminal/test/AutomatedTestSuite.java | 3 + 14 files changed, 1180 insertions(+), 9 deletions(-) create mode 100644 terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/MouseRouter.java create mode 100644 terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MouseReportTest.java create mode 100644 terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/TerminalMouseWheelUITest.java create mode 100644 terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseFuzzUITest.java create mode 100644 terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseUITest.java 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..91e4f2adfbb 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 @@ -62,4 +62,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..d4c60637bb7 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 @@ -204,6 +204,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() */ @@ -533,6 +538,8 @@ private void resetTerminal() { private void resetProgramModes() { terminal.showCursor(true); terminal.enableBracketedPaste(false); + terminal.enableMouseReporting(0); + terminal.enableSgrMouseEncoding(false); } /** @@ -1360,6 +1367,14 @@ private void setDecPrivateMode(int param) { // 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; @@ -1400,6 +1415,14 @@ private void resetDecPrivateMode(int param) { 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/VT100TerminalControl.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/emulator/VT100TerminalControl.java index 699f6a18630..e06e1ac39d9 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,10 @@ 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; + // what a program that asked for the mouse is told of it + private final MouseReporter fMouse = new MouseReporter(); /** * Listens to changes in the preferences @@ -559,14 +565,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()); @@ -875,6 +883,7 @@ protected void setupControls(Composite parent) { new TextLineRenderer(() -> fCtlText, fPollingTextCanvasModel)); fCtlText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + fCtlText.setMouseHandler(fMouse); fCtlText.addResizeHandler((lines, columns) -> fTerminalText.setDimensions(lines, columns)); fCtlText.addMouseListener(new MouseAdapter() { @Override @@ -1524,6 +1533,193 @@ public void enableApplicationCursorKeys(boolean enable) { fApplicationCursorKeys = enable; } + @Override + public void enableMouseReporting(int mode) { + fMouse.setMode(mode); + } + + @Override + public void enableSgrMouseEncoding(boolean enable) { + fMouse.fSgr = enable; + } + + /** + * One mode a program asked for, and what it has been told in it. A new mode is a + * new session: nothing told to the program that asked before carries over. + */ + private static final class MouseSession { + /** 1000 (buttons), 1002 (and drags), 1003 (and every move), 0 for none */ + final int mode; + /** the cell the pointer was last reported in */ + int line = -1, column = -1; + /** lines the wheel moved that make no whole notch yet, up positive */ + int wheelLines; + + MouseSession(int mode) { + this.mode = mode; + } + } + + /** + * Presses, releases, moves and the wheel, told to a program that asked for them + * the way a terminal has always told it, so that a program drawing its own screen + * can be clicked on and scrolled. Whether a gesture is the program's at all is the + * canvas's to decide; this only tells it. + */ + private class MouseReporter implements TextCanvas.IMouseHandler { + // set by the reader job, read by the display thread, which alone changes the session + private volatile MouseSession fSession = new MouseSession(0); + volatile boolean fSgr; + + void setMode(int mode) { + fSession = new MouseSession(mode); + // the last click told belongs to the program that asked then + if (fCtlText != null) { + fDisplay.asyncExec(() -> { + if (!fCtlText.isDisposed()) { + fCtlText.forgetProgramClick(); + } + }); + } + } + + @Override + public boolean button(int button, int modifiers, Point cell, boolean pressed) { + MouseSession session = fSession; + if (session.mode == 0 || button < 1 || button > 3 || !isConnected()) { + return false; + } + Point at = onScreen(cell); + if (at == null) { + if (pressed) { + return false; // over the history, which the program knows nothing of + } + // a release is reported wherever it happens: its press was + at = new Point(Math.max(1, Math.min(cell.x + 1, fPollingTextCanvasModel.getTerminalText().getWidth())), 1); + } + send(button - 1 + modifiers, at, 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 + session.line = at.y; + session.column = 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 moved(int button, int modifiers, Point cell) { + MouseSession session = fSession; + // 1002 is only interested while a button is held, 1003 in every move. + if (session.mode < 1002 || (session.mode == 1002 && button == 0) || !isConnected()) { + return false; + } + Point at = onScreen(cell); + if (at == null) { + return false; + } + if (at.y == session.line && at.x == session.column) { + return true; // still the same cell, and a cell is all the program is told + } + session.line = at.y; + session.column = at.x; + send((button == 0 ? 3 : button - 1) + 32 + modifiers, at, true); + return true; + } + + /** + * A wheel notch is reported as a press of button 64 or 65, never released. + * 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. + */ + @Override + public boolean wheel(int lines, int modifiers, Point cell) { + MouseSession session = fSession; + if (session.mode == 0 || lines == 0 || !isConnected()) { + return false; + } + Point at = onScreen(cell); + if (at == null) { + return false; // over the history: the view scrolls + } + if (Integer.signum(lines) != Integer.signum(session.wheelLines)) { + session.wheelLines = 0; + } + session.wheelLines += lines; + int notches = Math.abs(session.wheelLines) / 3; + session.wheelLines %= 3; + for (int i = 0; i < notches; i++) { + send((lines > 0 ? 64 : 65) + modifiers, at, true); + } + return true; // the program's, told once the lines make a notch + } + + private void send(int button, Point at, boolean pressed) { + sendBytes(mouseReportBytes(mouseReport(fSgr, button, at.y, at.x, pressed))); + } + } + + /** + * @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)); + } + + 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 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. + return "\u001b[M" + (char) (32 + (pressed ? button : button | 3)) + legacyPosition(column) //$NON-NLS-1$ + + legacyPosition(line); + } + + /** + * A column or line in one byte, which has no room past 223: as xterm, anything + * further is sent as a zero byte, so that a drag past it still ends in a release. + */ + private static char legacyPosition(int value) { + return value > 223 ? 0 : (char) (32 + value); + } + + /** + * 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); 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..b4be230474b 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,11 @@ abstract public class GridCanvas extends VirtualCanvas { public GridCanvas(Composite parent, int style) { super(parent, style); addListener(SWT.MouseWheel, event -> { - if (getVerticalBar().isVisible()) { + // Windows set to scroll a page at a time counts notches, not lines: a notch is three + // lines here, as GTK and the Windows default count them. Another number of lines per + // notch in the Windows settings is not known to SWT's API, and still counts as lines. + int lines = event.detail == SWT.SCROLL_PAGE ? 3 * event.count : event.count; + if (!handleMouseWheel(event.x, event.y, lines, event.stateMask) && getVerticalBar().isVisible()) { int delta = -fCellHeight * event.count; scrollYDelta(delta); } @@ -40,6 +44,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/MouseRouter.java b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/MouseRouter.java new file mode 100644 index 00000000000..06b45dbcdbe --- /dev/null +++ b/terminal/bundles/org.eclipse.terminal.control/src/org/eclipse/terminal/internal/textcanvas/MouseRouter.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.textcanvas; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; + +/** + * Whose a gesture of the mouse is: the program's, which asked for the mouse, or + * the terminal's own (a selection, the paste, the context menu). A press decides + * it, once, and what follows from that press (its drag, its release, its + * double-click, its context menu) goes the same way, however the keyboard stands + * by then. Everything the canvas needs to know of that is kept here, and only + * here. + *

+ * Shift keeps the mouse for the terminal, which is the convention every terminal + * uses to still allow a selection while a program is listening. A press while a + * button of the terminal's own gesture is held is the terminal's too: a gesture + * is not split between the two. + */ +final class MouseRouter { + + private TextCanvas.IMouseHandler fProgram; + /** the buttons whose press went to the program, as bits 1 << button */ + private int fProgramButtons; + /** whether the last press went to the program: its double-click is its too */ + private boolean fLastPressProgram; + /** whether the last right press went to the program: its context menu is not opened */ + private boolean fRightPressProgram; + /** the last left click the program took: where a shift-drag starts while nothing is selected */ + private Point fProgramClick; + + void setProgram(TextCanvas.IMouseHandler program) { + fProgram = program; + } + + /** + * @param cell the cell under the pointer, null while the canvas has no cells yet + * @return whether the program took the press, which the terminal then leaves alone + */ + boolean press(int button, int stateMask, Point cell) { + int bit = 1 << button; + boolean program = listens(stateMask, cell) && heldButton(stateMask, fProgramButtons) >= 0 + && fProgram.button(button, modifiers(stateMask), cell, true); + fLastPressProgram = program; + if (button == 3) { + fRightPressProgram = program; + } + if (!program) { + // a release of this button lost earlier (a dialog took it) is not waited for + fProgramButtons &= ~bit; + return false; + } + fProgramButtons |= bit; + if (button == 1) { + fProgramClick = cell; + } + return true; + } + + /** @return whether the release went to the program, as its press did */ + boolean release(int button, int stateMask, Point cell) { + int bit = 1 << button; + if ((fProgramButtons & bit) == 0) { + return false; + } + fProgramButtons &= ~bit; + fProgram.button(button, modifiers(stateMask), cell, false); + return true; + } + + /** @return whether the double-click is the program's, as the press before it was */ + boolean doubleClick() { + return fLastPressProgram; + } + + /** @return whether the context menu of a right-click stays shut, the program having taken it */ + boolean menuTaken() { + return fRightPressProgram; + } + + /** + * @param terminalDragging whether the terminal's own selection is being dragged + * @return whether the program took the move + */ + boolean move(int stateMask, Point cell, boolean terminalDragging) { + int held = heldButton(stateMask, fProgramButtons); + // a button held down is a drag of the program's only if its press was the program's + return !terminalDragging && held >= 0 && listens(stateMask, cell) + && fProgram.moved(held, modifiers(stateMask), cell); + } + + /** @return whether the program took the wheel, which then does not scroll the view */ + boolean wheel(int lines, int stateMask, Point cell) { + return listens(stateMask, cell) && fProgram.wheel(lines, modifiers(stateMask), cell); + } + + /** + * @param height the lines of the text now + * @return where a shift-drag starts while nothing is selected: the last left click + * the program took, unless its line is gone; null for none + */ + Point clickAnchor(int height) { + return fProgramClick != null && fProgramClick.y < height ? fProgramClick : null; + } + + /** + * The last click the program took no longer counts: the program stopped or + * started listening (its line may not even be the same line after a switch of + * screens), the selection was cleared, or the terminal took a click of its own. + */ + void forgetClick() { + fProgramClick = null; + } + + private boolean listens(int stateMask, Point cell) { + return fProgram != null && cell != null && (stateMask & SWT.SHIFT) == 0; + } + + /** + * 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 program 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 program) { + 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 ((program & 1 << button) != 0) { + return button; + } + } + } + return held ? -1 : 0; + } +} 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..45e5f583898 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,6 +42,7 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; +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; @@ -66,6 +67,8 @@ public class TextCanvas extends GridCanvas { private ResizeListener fResizeListener; private final List fMouseListeners; private SelectionMode fSelMode = SelectionMode.NONE; + // whose each gesture of the mouse is, the program's or the terminal's + private final MouseRouter fMouse = new MouseRouter(); private enum SelectionMode { NONE, DRAG, WORD, LINE @@ -151,6 +154,42 @@ public void focusLost(FocusEvent e) { fCellCanvasModel.setCursorEnabled(false); } }); + // Before every other mouse listener: a press the program takes is the program's + // alone, and so is all that follows from it. 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). + Listener reporter = event -> { + Point cell = cell(event.x, event.y); + boolean program = switch (event.type) { + case SWT.MouseDown -> fMouse.press(event.button, event.stateMask, cell); + case SWT.MouseUp -> fMouse.release(event.button, event.stateMask, cell); + default -> fMouse.doubleClick(); // SWT.MouseDoubleClick + }; + if (!program) { + return; + } + if (event.type == SWT.MouseDown) { + // 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; + if (event.button == 1) { + fCellCanvasModel.setSelectionAnchor(cell); + } + } + 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 && fMouse.menuTaken()) { + event.doit = false; + } + }); fMouseListeners = new ArrayList<>(); addMouseListener(new MouseListener() { @Override @@ -202,11 +241,15 @@ public void mouseDown(MouseEvent e) { fHasSelection = false; if ((e.stateMask & SWT.SHIFT) != 0) { Point anchor = fCellCanvasModel.getSelectionAnchor(); + if (anchor == null) { + anchor = fMouse.clickAnchor(fCellCanvasModel.getTerminalText().getHeight()); + } if (anchor != null) { fDraggingStart = anchor; } } else { fCellCanvasModel.setSelectionAnchor(fDraggingStart); + fMouse.forgetClick(); } fDraggingEnd = null; } @@ -272,6 +315,9 @@ public void mouseUp(MouseEvent e) { } }); addMouseMoveListener(e -> { + if (fMouse.move(e.stateMask, cell(e.x, e.y), fDraggingStart != null)) { + return; + } if (fDraggingStart != null) { // Dragging past an edge keeps the lines beyond it coming into view. if (dragPast(e.y) != 0 && !fDragScrolling) { @@ -575,6 +621,55 @@ protected void repaintRange(int col, int line, int width, int height) { repaint(r); } + /** + * Hands the mouse 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 IMouseHandler { + /** @return whether the program took the press or release */ + boolean button(int button, int modifiers, Point cell, boolean pressed); + + /** + * @param button the button held, 0 for none + * @return whether the program took the move + */ + boolean moved(int button, int modifiers, Point cell); + + /** + * @param lines lines the wheel asked for, positive when scrolling up + * @return whether the program took it + */ + boolean wheel(int lines, int modifiers, Point cell); + } + + public void setMouseHandler(IMouseHandler handler) { + fMouse.setProgram(handler); + } + + /** + * A program started or stopped listening to the mouse: the last click it was told + * of is no longer where a shift-drag starts. + */ + public void forgetProgramClick() { + fMouse.forgetClick(); + } + + /** + * @return the cell of the text under the point, its line counting the history above + * the screen too; null while the canvas has no cells yet + */ + private Point cell(int x, int y) { + if (getCellWidth() <= 0 || getCellHeight() <= 0) { + return null; + } + return screenPointToCell(Math.max(0, x), Math.max(0, y)); + } + + @Override + protected boolean handleMouseWheel(int x, int y, int count, int stateMask) { + return fMouse.wheel(count, 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 @@ -657,6 +752,7 @@ public void selectAll() { */ public void clearSelection() { fCellCanvasModel.setSelection(-1, -1, -1, -1); + fMouse.forgetClick(); } /** 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..6f139b4066f 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,6 +21,7 @@ */ @Suite @SelectClasses({ // + MouseReportTest.class, // VT100EmulatorBackendTest.class, // VT100EmulatorTest.class, // }) 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..2de58f433b0 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 @@ -75,6 +75,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..41476091f4c --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/MouseReportTest.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * 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)); + // column 223 is the last byte, 255; past it, as xterm, a zero byte, so that a + // drag there still ends in a release + assertEquals(CSI + "M" + (char) 32 + (char) 255 + (char) 37, + VT100TerminalControl.mouseReport(false, 0, 5, 223, true)); + assertEquals(CSI + "M" + (char) 32 + (char) 0 + (char) 37, + VT100TerminalControl.mouseReport(false, 0, 5, 224, true)); + assertEquals(CSI + "M" + (char) 35 + (char) 42 + (char) 0, + VT100TerminalControl.mouseReport(false, 0, 300, 10, false)); + } + + @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..554b80d5997 --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/emulator/TerminalMouseWheelUITest.java @@ -0,0 +1,166 @@ +/******************************************************************************* + * 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) { + return wheelEvents(SWT.SCROLL_LINE, counts); + } + + private String wheelEvents(int detail, int... counts) { + Control canvas = terminal.getControl(); + for (int count : counts) { + Event event = new Event(); + event.detail = detail; + 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)); + } + + @Test + public void aPageAtATimeCountsNotches() { + // Windows set to scroll a page at a time gives the notches, not lines + assertEquals(UP, wheelEvents(SWT.SCROLL_PAGE, 1)); + assertEquals(DOWN + DOWN, wheelEvents(SWT.SCROLL_PAGE, -2)); + } +} 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..743f819b9a5 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 @@ -678,4 +678,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/textcanvas/TextCanvasMouseFuzzUITest.java b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseFuzzUITest.java new file mode 100644 index 00000000000..8cb73f6bcdc --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseFuzzUITest.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * 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.setMouseHandler(new TextCanvas.IMouseHandler() { + @Override + public boolean button(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 moved(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; + } + + @Override + public boolean wheel(int lines, int modifiers, Point cell) { + assertFalse(shift, "the wheel with shift is 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(5)) { + 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; + case 2: + send(SWT.MouseWheel, 0, down); + 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); + event.count = random.nextInt(7) - 3; + 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..f838feb36ec --- /dev/null +++ b/terminal/tests/org.eclipse.terminal.test/src/org/eclipse/terminal/internal/textcanvas/TextCanvasMouseUITest.java @@ -0,0 +1,218 @@ +/******************************************************************************* + * 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.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; + +/** + * 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.setMouseHandler(new TextCanvas.IMouseHandler() { + @Override + public boolean button(int button, int modifiers, Point cell, boolean pressed) { + reported.add(button + (pressed ? " down" : " up")); + return true; + } + + @Override + public boolean moved(int button, int modifiers, Point cell) { + return true; + } + + @Override + public boolean wheel(int lines, int modifiers, Point cell) { + return false; + } + }); + // 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) { + return send(type, button, stateMask, 1, 1); + } + + private Event send(int type, int button, int stateMask, int x, int y) { + Event event = new Event(); + event.button = button; + event.stateMask = stateMask; + event.x = x; + event.y = y; + 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); + } + + @Test + public void aGestureTheTerminalStartedStaysItsOwn() { + // a shift-drag of the terminal's own, then the right button with shift let go + send(SWT.MouseDown, 1, SWT.SHIFT); + send(SWT.MouseDown, 3, SWT.BUTTON1); + send(SWT.MouseUp, 3, SWT.BUTTON1 | SWT.BUTTON3); + send(SWT.MouseUp, 1, SWT.BUTTON1); + assertTrue(reported.isEmpty(), "reported: " + reported); + } + + @Test + public void theMenuFollowsTheRightPressOnly() { + // the program took the right press; a shift-click while it is held is the terminal's + send(SWT.MouseDown, 3, 0); + send(SWT.MouseDown, 1, SWT.SHIFT | SWT.BUTTON3); + send(SWT.MouseUp, 1, SWT.SHIFT | SWT.BUTTON1 | SWT.BUTTON3); + send(SWT.MouseUp, 3, SWT.BUTTON3); + assertEquals(List.of("3 down", "3 up"), reported); + // Windows asks for the menu after the release: still not the terminal's to open + assertFalse(send(SWT.MenuDetect, 3, 0).doit); + } + + @Test + public void aShiftDragStartsAtTheLastLeftClickTheProgramTook() { + // a canvas of its own, whose model the test can ask for the selection + 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.setMouseHandler(new TextCanvas.IMouseHandler() { + @Override + public boolean button(int button, int modifiers, Point cell, boolean pressed) { + return true; + } + + @Override + public boolean moved(int button, int modifiers, Point cell) { + return true; + } + + @Override + public boolean wheel(int lines, int modifiers, Point cell) { + return false; + } + }); + int w = canvas.getCellWidth(), h = canvas.getCellHeight(); + // the program took a left click in the first cell, and a right one further on + send(SWT.MouseDown, 1, 0, 1, 1); + send(SWT.MouseUp, 1, SWT.BUTTON1, 1, 1); + send(SWT.MouseDown, 3, 0, 10 * w + 1, 1); + send(SWT.MouseUp, 3, SWT.BUTTON3, 10 * w + 1, 1); + // a shift-click on the third cell selects from the left click, not the right one + send(SWT.MouseDown, 1, SWT.SHIFT, 2 * w + 1, 1); + send(SWT.MouseUp, 1, SWT.SHIFT | SWT.BUTTON1, 2 * w + 1, 1); + assertEquals(new Point(0, 0), model.getSelectionStart()); + canvas.clearSelection(); + // once the program stops listening (the control then tells the canvas), its last + // click is no anchor any more + send(SWT.MouseDown, 1, 0, 1, 1); + send(SWT.MouseUp, 1, SWT.BUTTON1, 1, 1); + canvas.forgetProgramClick(); + send(SWT.MouseDown, 1, SWT.SHIFT, 2 * w + 1, h + 1); + send(SWT.MouseUp, 1, SWT.SHIFT | SWT.BUTTON1, 2 * w + 1, h + 1); + assertEquals(null, model.getSelectionStart()); + } +} 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, // })