Skip to content

Commit

Permalink
JBR-7481 Work around mouse entered/exited bug
Browse files Browse the repository at this point in the history
To fix missing mouse entered/exited events when
using rounded corners, we keep track of mouse moved events. When a mouse moved event is detected, and the current peer under the cursor belongs to a different window, we send fake mouse entered/exit events to the old and new windows. We also filter late mouse exited events.

The workaround is enabled by default with the VM option "awt.mac.enableMouseEnteredExitedWorkaround" to disable it in case something breaks.

About the test:
Use the robot to find the points when the mouse
entered event is sent to the popup when the mouse
enters through a rounded corner, and the similar
point for entering the outer window when exiting
through such a corner.

Once the points are found, move the mouse back
and forth to that point, but not beyond.
The correct behavior is that when the mouse
enters the popup, a mouse exited event is sent
to the outer frame and vice versa.
Therefore, every mouse entered/exited event
should be received exactly once.

Use reflection to set the rounded corners,
as JBR API isn't available in tests.
  • Loading branch information
Sergei Tachenov authored and jbrbot committed Nov 8, 2024
1 parent 170a7cf commit 0b5beaf
Show file tree
Hide file tree
Showing 2 changed files with 343 additions and 2 deletions.
141 changes: 139 additions & 2 deletions src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.MenuBar;
import java.awt.Point;
import java.awt.Rectangle;
Expand All @@ -65,7 +64,6 @@

import sun.awt.AWTAccessor;
import sun.awt.AWTAccessor.ComponentAccessor;
import sun.awt.AppContext;
import sun.awt.CGraphicsDevice;
import sun.awt.DisplayChangedListener;
import sun.awt.ExtendedKeyCodes;
Expand Down Expand Up @@ -160,6 +158,8 @@ public enum PeerType {
*/
private LWWindowPeer blocker;

Jbr7481MouseEnteredExitedFix jbr7481MouseEnteredExitedFix = null;

public LWWindowPeer(Window target, PlatformComponent platformComponent,
PlatformWindow platformWindow, PeerType peerType)
{
Expand Down Expand Up @@ -812,6 +812,18 @@ public void notifyNCMouseDown() {
*/
@Override
public void notifyMouseEvent(int id, long when, int button,
int x, int y, int absX, int absY,
int modifiers, int clickCount, boolean popupTrigger,
byte[] bdata) {
if (Jbr7481MouseEnteredExitedFix.isEnabled) {
mouseEnteredExitedBugWorkaround().apply(id, when, button, x, y, absX, absY, modifiers, clickCount, popupTrigger, bdata);
}
else {
doNotifyMouseEvent(id, when, button, x, y, absX, absY, modifiers, clickCount, popupTrigger, bdata);
}
}

void doNotifyMouseEvent(int id, long when, int button,
int x, int y, int absX, int absY,
int modifiers, int clickCount, boolean popupTrigger,
byte[] bdata)
Expand Down Expand Up @@ -960,6 +972,13 @@ public void notifyMouseEvent(int id, long when, int button,
notifyUpdateCursor();
}

private Jbr7481MouseEnteredExitedFix mouseEnteredExitedBugWorkaround() {
if (jbr7481MouseEnteredExitedFix == null) {
jbr7481MouseEnteredExitedFix = new Jbr7481MouseEnteredExitedFix(this);
}
return jbr7481MouseEnteredExitedFix;
}

private void generateMouseEnterExitEventsForComponents(long when,
int button, int x, int y, int screenX, int screenY,
int modifiers, int clickCount, boolean popupTrigger,
Expand Down Expand Up @@ -1506,4 +1525,122 @@ public long getWindowHandle() {
}
return handle[0];
}

static class Jbr7481MouseEnteredExitedFix {
static final boolean isEnabled;

static {
boolean isEnabledLocal = false;

try {
isEnabledLocal = Boolean.parseBoolean(System.getProperty("awt.mac.enableMouseEnteredExitedWorkaround", "true"));
} catch (Exception ignored) {
}

isEnabled = isEnabledLocal;
}

private final LWWindowPeer peer;
long when;
int x;
int y;
int absX;
int absY;
int modifiers;

Jbr7481MouseEnteredExitedFix(LWWindowPeer peer) {
this.peer = peer;
}

void apply(
int id, long when, int button,
int x, int y, int absX, int absY,
int modifiers, int clickCount, boolean popupTrigger,
byte[] bdata
) {
this.when = when;
this.x = x;
this.y = y;
this.absX = absX;
this.absY = absY;
this.modifiers = modifiers;
switch (id) {
case MouseEvent.MOUSE_ENTERED -> {
var currentPeerWorkaround = getCurrentPeerWorkaroundOrNull();
// First, send a "mouse exited" to the current window, if any,
// to maintain a sensible "exited, entered" order.
if (currentPeerWorkaround != null && currentPeerWorkaround != this) {
currentPeerWorkaround.sendMouseExited();
}
// Then forward the "mouse entered" to this window, regardless of whether it's already current.
// Repeated "mouse entered" are allowed and may be even needed somewhere deep inside this call.
peer.doNotifyMouseEvent(id, when, button, x, y, absX, absY, modifiers, clickCount, popupTrigger, bdata);
}
case MouseEvent.MOUSE_EXITED -> {
var currentPeerWorkaround = getCurrentPeerWorkaroundOrNull();
// An "exited" event often arrives too late. Such events may cause the current window to get lost.
// And since we've already sent a "mouse exited" when entering the current window, we don't need another one.
if (currentPeerWorkaround == this) {
peer.doNotifyMouseEvent(id, when, button, x, y, absX, absY, modifiers, clickCount, popupTrigger, bdata);
}
}
case MouseEvent.MOUSE_MOVED -> {
var currentPeerWorkaround = getCurrentPeerWorkaroundOrNull();
if (currentPeerWorkaround != this) {
// Inconsistency detected: either the events arrived out of order or never did.
// First, send an "exited" event to the current window, if any.
if (currentPeerWorkaround != null) {
currentPeerWorkaround.sendMouseExited();
}
// Next, send a fake "mouse entered" to the new window.
sendMouseEntered();
}
peer.doNotifyMouseEvent(id, when, button, x, y, absX, absY, modifiers, clickCount, popupTrigger, bdata);
}
default -> {
peer.doNotifyMouseEvent(id, when, button, x, y, absX, absY, modifiers, clickCount, popupTrigger, bdata);
}
}
}

private static Jbr7481MouseEnteredExitedFix getCurrentPeerWorkaroundOrNull() {
var currentPeer = getCurrentWindowPeer();
return currentPeer == null ? null : currentPeer.jbr7481MouseEnteredExitedFix;
}

private static LWWindowPeer getCurrentWindowPeer() {
return LWWindowPeer.getWindowUnderCursor();
}

private void sendMouseEntered() {
peer.doNotifyMouseEvent(
MouseEvent.MOUSE_ENTERED, when, MouseEvent.NOBUTTON,
x, y, absX, absY,
modifiers, 0, false,
null
);
}

private void sendMouseExited() {
peer.doNotifyMouseEvent(
MouseEvent.MOUSE_EXITED, when, MouseEvent.NOBUTTON,
x, y, absX, absY,
modifiers, 0, false,
null
);
}

@Override
public String toString() {
return "Jbr7481MouseEnteredExitedFix{" +
"peer=" + peer +
", when=" + when +
", x=" + x +
", y=" + y +
", absX=" + absX +
", absY=" + absY +
", modifiers=" + modifiers +
'}';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/*
* Copyright 2024 JetBrains s.r.o.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.PopupFactory;
import javax.swing.WindowConstants;
import java.awt.Cursor;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Window;
import sun.lwawt.macosx.CPlatformWindow;

/*
* @test
* @key headful
* @requires (os.family == "mac")
* @modules java.desktop/sun.lwawt.macosx:+open java.desktop/sun.awt
* @summary Test mouse entered/exit events on macOS with rounded corners
* @run main MouseEnterExitMacRoundedCornersTest
*/
public class MouseEnterExitMacRoundedCornersTest {

private static MouseCounter windowMouseListener;
private static MouseCounter popupMouseListener;
private static Window window;
private static Window popupWindow;
private volatile static Point popupAt;

private static void showWindow() {
window = new JFrame();
windowMouseListener = new MouseCounter();
window.addMouseListener(windowMouseListener);
window.setSize(400, 300);
window.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
showPopup(window);
}
});
window.setVisible(true);
}

private static void showPopup(Component owner) {
var factory = PopupFactory.getSharedInstance();
var helloWorld = new JLabel();
helloWorld.setPreferredSize(new Dimension(200, 100));
helloWorld.setOpaque(true);
var popup = factory.getPopup(owner, helloWorld, 100, 100);
var window = getWindowParent(helloWorld);
popupMouseListener = new MouseCounter();
window.addMouseListener(popupMouseListener);
setRoundedCorners(window, new Object[] {8.0f, 1, Color.BLACK});
popupWindow = window;
popup.show();
}

private static void setRoundedCorners(Window window, Object[] args) {
try {
var method = CPlatformWindow.class.getDeclaredMethod("setRoundedCorners", Window.class, Object.class);
method.setAccessible(true);
method.invoke(null, window, args);
} catch (java.lang.Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}

private static Window getWindowParent(JLabel helloWorld) {
Component window = helloWorld;
while (window != null) {
window = window.getParent();
if (window instanceof Window) {
break;
}
}
return (Window) window;
}

public static void main(String[] args) throws Exception {
try {
Robot robot = new Robot();
robot.setAutoDelay(100);
robot.setAutoWaitForIdle(true);

EventQueue.invokeAndWait(MouseEnterExitMacRoundedCornersTest::showWindow);
robot.waitForIdle();

EventQueue.invokeAndWait(() -> {
popupAt = popupWindow.getLocationOnScreen();
});

int popupEnterPoint = findPoint(robot, popupAt, -5, +10, () -> popupMouseListener.enteredCount.get() > 0);
moveBackAndForth(robot, popupAt, -5, popupEnterPoint);

int frameEnterPoint = findPoint(robot, popupAt, +10, -5, () -> windowMouseListener.enteredCount.get() > 0);
moveBackAndForth(robot, popupAt, +10, frameEnterPoint);

System.out.println("Test PASSED");
} finally {
EventQueue.invokeAndWait(() -> {
if (window != null) {
window.dispose();
}
if (popupWindow != null) {
popupWindow.dispose();
}
});
}
}

private static int findPoint(Robot robot, Point popupAt, int start, int end, Supplier<Boolean> condition) throws Exception {
robot.mouseMove(popupAt.x + start, popupAt.y + start);
robot.waitForIdle();
resetCounters();
return move(robot, popupAt, start, end, condition);
}

private static void moveBackAndForth(Robot robot, Point popupAt, int start, int end) throws Exception {
robot.mouseMove(popupAt.x + start, popupAt.y + start);
robot.waitForIdle();
resetCounters();
move(robot, popupAt, start, end, null);
move(robot, popupAt, end, start, null);
assertEnteredExited();
}

private static void resetCounters() {
windowMouseListener.enteredCount.set(0);
windowMouseListener.exitedCount.set(0);
popupMouseListener.enteredCount.set(0);
popupMouseListener.exitedCount.set(0);
}

private static int move(Robot robot, Point popupAt, int start, int end, Supplier<Boolean> condition) throws Exception {
for (int offset = start; start < end ? offset <= end : offset >= end; offset = (start < end ? offset + 1 : offset - 1)) {
if (condition != null && condition.get()) {
return offset;
}
robot.mouseMove(popupAt.x + offset, popupAt.y + offset);
}
return -1;
}

private static void assertEnteredExited() {
var enteredWindow = windowMouseListener.enteredCount.get();
var exitedWindow = windowMouseListener.exitedCount.get();
var enteredPopup = popupMouseListener.enteredCount.get();
var exitedPopup = popupMouseListener.exitedCount.get();
if (enteredWindow != 1 || exitedWindow != 1 || enteredPopup != 1 || exitedPopup != 1) {
throw new RuntimeException(
"Moved the mouse back and forth, expected to enter/exit both the popup and window exactly once, but got: "
+ "enteredWindow=" + enteredWindow + ", exitedWindow=" + exitedWindow + ", "
+ "enteredPopup=" + enteredPopup + ", exitedPopup=" + exitedPopup
);
}
}

private static class MouseCounter extends MouseAdapter {
final AtomicInteger enteredCount = new AtomicInteger();
final AtomicInteger exitedCount = new AtomicInteger();

@Override
public void mouseEntered(MouseEvent e) {
enteredCount.incrementAndGet();
}

@Override
public void mouseExited(MouseEvent e) {
exitedCount.incrementAndGet();
}
};
}

0 comments on commit 0b5beaf

Please sign in to comment.