Add reusable native foreground application detection

This commit is contained in:
2026-11-08 09:16:29 +01:00
parent 8062b61ed6
commit 7893922df2
9 changed files with 580 additions and 1 deletions
@@ -0,0 +1,50 @@
package de.neitzel.core.desktop;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Supplier;
/** One daemon worker bounds caller wait and prevents overlapping or accumulating native queries. */
final class BoundedForegroundDetector implements ForegroundDetector {
private final ExecutorService worker = Executors.newSingleThreadExecutor(r -> {
Thread thread = new Thread(r, "desktop-observation"); thread.setDaemon(true); return thread;
});
private final Supplier<ForegroundDetector> factory;
private ForegroundDetector delegate;
private Future<?> active;
private boolean closed;
BoundedForegroundDetector(Supplier<ForegroundDetector> factory) { this.factory = factory; }
public synchronized Snapshot snapshot() {
return query(() -> detector().snapshot(), new Snapshot(null, null, false, limitation()));
}
public synchronized Inventory inventory() {
return query(() -> detector().inventory(), new Inventory(List.of(), List.of(), false, limitation()));
}
private String limitation() {
return closed ? "Foreground detection is closed." : "Desktop observation is unavailable or timed out; use Manual mode.";
}
private ForegroundDetector detector() {
if (delegate == null) delegate = factory.get();
return delegate;
}
private <T> T query(Callable<T> operation, T unavailable) {
if (closed || (active != null && !active.isDone())) return unavailable;
Future<T> next = worker.submit(operation); active = next;
try { return next.get(1500, TimeUnit.MILLISECONDS); }
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); return unavailable; }
catch (ExecutionException | TimeoutException failed) { return unavailable; }
}
public synchronized void close() {
if (closed) return;
closed = true;
// Native queries own/release their per-call resources. A stuck native call cannot queue more work.
worker.shutdownNow();
}
}
@@ -0,0 +1,53 @@
package de.neitzel.core.desktop;
import java.util.List;
import java.util.Map;
/** Local desktop observations; callers own polling and application-specific selection policy. */
public interface ForegroundDetector extends AutoCloseable {
/** A persistent application identity plus transient process information. */
record Application(String namespace, String identity, String name, long processId) { }
/** A transient window handle. A null title means that the title is unavailable. */
record Window(String id, Application application, String title) {
@Override public String toString() { return "Window[id=" + id + ", application=" + application + "]"; }
}
/** focusAvailable=true with a null application means no identifiable app is foreground. */
record Snapshot(Application application, Window window, boolean focusAvailable, String limitation) { }
/** Availability is independent of foreground detection; lists are immutable snapshots. */
record Inventory(List<Application> applications, List<Window> windows, boolean available, String limitation) {
public Inventory { applications = List.copyOf(applications); windows = List.copyOf(windows); }
}
Snapshot snapshot();
Inventory inventory();
@Override default void close() { }
static ForegroundDetector system() {
return forEnvironment(System.getProperty("os.name", ""), System.getenv());
}
/** Explicit environment selection also allows capability checks without probing unsupported desktops. */
static ForegroundDetector forEnvironment(String osName, Map<String, String> environment) {
String os = osName.toLowerCase(java.util.Locale.ROOT);
if (os.contains("mac")) return new BoundedForegroundDetector(MacForegroundDetector::new);
if (os.contains("windows")) return new BoundedForegroundDetector(WindowsForegroundDetector::new);
if (os.contains("linux")) {
if ("wayland".equalsIgnoreCase(environment.get("XDG_SESSION_TYPE"))
|| environment.containsKey("WAYLAND_DISPLAY")) return unavailable("Wayland foreground detection is not supported; use Manual mode.");
if (!environment.containsKey("DISPLAY")) return unavailable("No X11 display is available; use Manual mode.");
String display = environment.get("DISPLAY");
return new BoundedForegroundDetector(() -> new X11ForegroundDetector(display));
}
return unavailable("Foreground detection is unavailable on this operating system; use Manual mode.");
}
private static ForegroundDetector unavailable(String reason) {
return new ForegroundDetector() {
public Snapshot snapshot() { return new Snapshot(null, null, false, reason); }
public Inventory inventory() { return new Inventory(List.of(), List.of(), false, reason); }
};
}
}
@@ -0,0 +1,124 @@
package de.neitzel.core.desktop;
import com.sun.jna.*;
import com.sun.jna.ptr.PointerByReference;
import java.util.ArrayList;
import java.util.List;
/** AppKit application identity and optional Accessibility window observations, without prompting. */
final class MacForegroundDetector implements ForegroundDetector {
private final NativeLibrary objc = NativeLibrary.getInstance("objc");
@SuppressWarnings("unused") private final NativeLibrary appkit = NativeLibrary.getInstance("/System/Library/Frameworks/AppKit.framework/AppKit");
private final Function message = objc.getFunction("objc_msgSend");
private final CoreFoundation cf = Native.load("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", CoreFoundation.class);
private final Accessibility ax = Native.load("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices", Accessibility.class);
private static final int UTF8 = 0x08000100;
private static final String PERMISSION = "Window details unavailable. To enable them, open System Settings > Privacy & Security > Accessibility and allow this application. Application rules remain available.";
interface CoreFoundation extends Library {
Pointer CFStringCreateWithCString(Pointer allocator, String value, int encoding);
byte CFStringGetCString(Pointer value, byte[] buffer, long size, int encoding);
long CFGetTypeID(Pointer value);
long CFHash(Pointer value);
long CFStringGetTypeID();
long CFArrayGetCount(Pointer value);
Pointer CFArrayGetValueAtIndex(Pointer value, long index);
void CFRelease(Pointer value);
}
interface Accessibility extends Library {
byte AXIsProcessTrusted();
Pointer AXUIElementCreateApplication(int pid);
int AXUIElementSetMessagingTimeout(Pointer value, float timeout);
int AXUIElementCopyAttributeValue(Pointer value, Pointer attribute, PointerByReference result);
}
private Pointer cls(String name) { return objc.getFunction("objc_getClass").invokePointer(new Object[]{name}); }
private Pointer selector(String name) { return objc.getFunction("sel_registerName").invokePointer(new Object[]{name}); }
private Pointer send(Pointer target, String method, Object... args) { return message.invokePointer(arguments(target, method, args)); }
private long number(Pointer target, String method) { return message.invokeLong(arguments(target, method)); }
private Object[] arguments(Pointer target, String method, Object... args) {
Object[] all = new Object[args.length + 2]; all[0] = target; all[1] = selector(method); System.arraycopy(args, 0, all, 2, args.length); return all;
}
private String string(Pointer value) {
if (value == null) return null;
Pointer bytes = send(value, "UTF8String"); return bytes == null ? null : bytes.getString(0, "UTF-8");
}
private Pointer pool() { return send(send(cls("NSAutoreleasePool"), "alloc"), "init"); }
private void releasePool(Pointer pool) { message.invokeVoid(arguments(pool, "drain")); }
private Application application(Pointer app) {
if (app == null) return null;
String identity = string(send(app, "bundleIdentifier"));
if (identity == null || identity.isBlank()) return null;
String name = string(send(app, "localizedName"));
return new Application("macos.bundleId", identity, name == null ? identity : name, number(app, "processIdentifier"));
}
private Pointer attribute(Pointer element, String name) {
Pointer key = cf.CFStringCreateWithCString(null, name, UTF8);
try {
PointerByReference result = new PointerByReference();
return ax.AXUIElementCopyAttributeValue(element, key, result) == 0 ? result.getValue() : null;
} finally { cf.CFRelease(key); }
}
private String title(Pointer element) {
Pointer value = attribute(element, "AXTitle");
if (value == null) return null;
try {
if (cf.CFGetTypeID(value) != cf.CFStringGetTypeID()) return null;
byte[] bytes = new byte[16384];
return cf.CFStringGetCString(value, bytes, bytes.length, UTF8) != 0 ? Native.toString(bytes, "UTF-8") : null;
} finally { cf.CFRelease(value); }
}
private Window focusedWindow(Application app) {
if (app == null || ax.AXIsProcessTrusted() == 0) return null;
Pointer element = ax.AXUIElementCreateApplication((int)app.processId());
try {
ax.AXUIElementSetMessagingTimeout(element, .10f);
Pointer window = attribute(element, "AXFocusedWindow");
if (window == null) return null;
try { return new Window("ax:" + app.processId() + ":" + cf.CFHash(window), app, title(window)); }
finally { cf.CFRelease(window); }
} finally { cf.CFRelease(element); }
}
public Snapshot snapshot() {
Pointer pool = pool();
try {
Application app = application(send(send(cls("NSWorkspace"), "sharedWorkspace"), "frontmostApplication"));
Window window = focusedWindow(app);
String limitation = "";
if (app != null && (window == null || window.title() == null))
limitation = ax.AXIsProcessTrusted() == 0 ? PERMISSION : "The active application does not expose its focused window or title.";
return new Snapshot(app, window, true, limitation);
} finally { releasePool(pool); }
}
public Inventory inventory() {
Pointer pool = pool();
try {
List<Application> apps = new ArrayList<>(); List<Window> windows = new ArrayList<>();
Pointer running = send(send(cls("NSWorkspace"), "sharedWorkspace"), "runningApplications");
long count = number(running, "count");
boolean trusted = ax.AXIsProcessTrusted() != 0;
for (long i = 0; i < count; i++) {
Pointer nativeApp = send(running, "objectAtIndex:", new NativeLong(i));
if (number(nativeApp, "activationPolicy") != 0) continue;
Application app = application(nativeApp); if (app == null) continue; apps.add(app);
if (!trusted) continue;
Pointer element = ax.AXUIElementCreateApplication((int)app.processId());
try {
ax.AXUIElementSetMessagingTimeout(element, .05f);
Pointer values = attribute(element, "AXWindows");
if (values == null) continue;
try {
long size = cf.CFArrayGetCount(values);
for (long j = 0; j < size; j++) {
Pointer window = cf.CFArrayGetValueAtIndex(values, j);
windows.add(new Window("ax:" + app.processId() + ":" + cf.CFHash(window), app, title(window)));
}
} finally { cf.CFRelease(values); }
} finally { cf.CFRelease(element); }
}
return new Inventory(apps, windows, true, trusted ? "" : PERMISSION);
} finally { releasePool(pool); }
}
}
@@ -0,0 +1,68 @@
package de.neitzel.core.desktop;
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
/** Win32 top-level windows; unavailable process identity is never replaced by a guessed name. */
final class WindowsForegroundDetector implements ForegroundDetector {
interface WindowCallback extends StdCallLibrary.StdCallCallback { boolean invoke(Pointer window, Pointer data); }
interface User32 extends StdCallLibrary {
Pointer GetForegroundWindow();
int GetWindowThreadProcessId(Pointer window, IntByReference pid);
int GetWindowTextW(Pointer window, char[] text, int size);
boolean IsWindowVisible(Pointer window);
boolean EnumWindows(WindowCallback callback, Pointer data);
}
interface Kernel32 extends StdCallLibrary {
Pointer OpenProcess(int access, boolean inherit, int pid);
boolean QueryFullProcessImageNameW(Pointer process, int flags, char[] path, IntByReference size);
boolean CloseHandle(Pointer handle);
}
private final User32 user = Native.load("user32", User32.class);
private final Kernel32 kernel = Native.load("kernel32", Kernel32.class);
private Window window(Pointer handle) {
if (handle == null) return null;
IntByReference pid = new IntByReference(); user.GetWindowThreadProcessId(handle, pid);
Pointer process = kernel.OpenProcess(0x1000, false, pid.getValue());
if (process == null) return null;
String path;
try {
char[] value = new char[32768]; IntByReference size = new IntByReference(value.length);
if (!kernel.QueryFullProcessImageNameW(process, 0, value, size)) return null;
path = new String(value, 0, size.getValue());
} finally { kernel.CloseHandle(process); }
// A generic host executable does not identify the packaged application it is displaying.
if (path.toLowerCase(Locale.ROOT).endsWith("\\applicationframehost.exe")) return null;
int slash = path.lastIndexOf('\\');
Application app = new Application("windows.exe", path.toLowerCase(Locale.ROOT), path.substring(slash + 1), Integer.toUnsignedLong(pid.getValue()));
char[] text = new char[8192]; int count = user.GetWindowTextW(handle, text, text.length);
return new Window("hwnd:" + Long.toUnsignedString(Pointer.nativeValue(handle)), app, count > 0 ? new String(text, 0, count) : null);
}
public Snapshot snapshot() {
Pointer handle = user.GetForegroundWindow();
Window window = window(handle);
return new Snapshot(window == null ? null : window.application(), window, true,
handle != null && window == null ? "Foreground application identity is unavailable or hosted; use a supported application or Manual mode." : "");
}
public Inventory inventory() {
List<Window> windows = new ArrayList<>();
var apps = new LinkedHashMap<String, Application>();
boolean available = user.EnumWindows((handle, data) -> {
if (user.IsWindowVisible(handle)) {
Window window = window(handle);
if (window != null) { windows.add(window); apps.putIfAbsent(window.application().identity(), window.application()); }
}
return true;
}, null);
return new Inventory(new ArrayList<>(apps.values()), windows, available,
available ? "Some hosted or protected application identities may be unavailable." : "Window enumeration is unavailable.");
}
}
@@ -0,0 +1,120 @@
package de.neitzel.core.desktop;
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import com.sun.jna.ptr.PointerByReference;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
/** EWMH on a private X connection. Never selected merely because XWayland exports DISPLAY. */
final class X11ForegroundDetector implements ForegroundDetector {
interface XErrorHandler extends Callback { int invoke(Pointer display, Pointer event); }
interface X11 extends Library {
Pointer XOpenDisplay(String name);
int XCloseDisplay(Pointer display);
NativeLong XDefaultRootWindow(Pointer display);
NativeLong XInternAtom(Pointer display, String name, boolean onlyIfExists);
int XGetWindowProperty(Pointer display, NativeLong window, NativeLong property, NativeLong offset,
NativeLong length, boolean delete, NativeLong type, NativeLongByReference actualType,
IntByReference format, NativeLongByReference count, NativeLongByReference remaining, PointerByReference data);
int XFree(Pointer value);
Pointer XSetErrorHandler(XErrorHandler handler);
}
private final X11 x = Native.load("X11", X11.class);
private final String displayName;
private Pointer display;
private static final Object ERROR_LOCK = new Object();
X11ForegroundDetector(String displayName) { this.displayName = displayName; }
private record Property(int format, byte[] bytes, long[] numbers) { }
private Property property(long window, String name) {
NativeLong atom = x.XInternAtom(display, name, true);
if (atom.longValue() == 0) return null;
NativeLongByReference actual = new NativeLongByReference(), count = new NativeLongByReference(), remaining = new NativeLongByReference();
IntByReference format = new IntByReference(); PointerByReference data = new PointerByReference();
int result = x.XGetWindowProperty(display, new NativeLong(window), atom, new NativeLong(0), new NativeLong(4096), false,
new NativeLong(0), actual, format, count, remaining, data);
Pointer bytes = data.getValue();
if (bytes == null) return null;
try {
if (result != 0 || remaining.getValue().longValue() != 0) return null;
int size = (int)Math.min(count.getValue().longValue(), 16384);
if (format.getValue() == 8) return new Property(8, bytes.getByteArray(0, size), null);
if (format.getValue() == 32) {
long[] values = new long[size];
for (int i = 0; i < size; i++) values[i] = bytes.getNativeLong((long)i * NativeLong.SIZE).longValue();
return new Property(32, null, values);
}
return null;
} finally { x.XFree(bytes); }
}
private String text(long window, String name, java.nio.charset.Charset encoding) {
Property value = property(window, name);
if (value == null || value.bytes == null) return null;
int size = value.bytes.length; while (size > 0 && value.bytes[size - 1] == 0) size--;
return new String(value.bytes, 0, size, encoding);
}
private long[] numbers(long window, String name) {
Property value = property(window, name); return value == null || value.numbers == null ? new long[0] : value.numbers;
}
private Window window(long id) {
if (id == 0) return null;
String wmClass = text(id, "WM_CLASS", StandardCharsets.ISO_8859_1);
if (wmClass == null || wmClass.isBlank()) return null;
int split = wmClass.indexOf('\0');
String identity = split >= 0 ? wmClass.substring(split + 1) : wmClass;
if (identity.isBlank()) return null;
long[] pid = numbers(id, "_NET_WM_PID");
Application app = new Application("x11.wmClass", identity, identity, pid.length == 0 ? -1 : pid[0]);
String title = text(id, "_NET_WM_NAME", StandardCharsets.UTF_8);
if (title == null) title = text(id, "WM_NAME", StandardCharsets.ISO_8859_1);
return new Window("x11:" + Long.toUnsignedString(id), app, title);
}
private <T> T connected(java.util.function.Supplier<T> operation, T unavailable) {
synchronized (ERROR_LOCK) {
display = x.XOpenDisplay(displayName);
if (display == null) return unavailable;
// A window can disappear between enumeration and a property request. Preserve the
// process's handler for other displays and suppress errors only on our private display.
Pointer[] previous = {null};
XErrorHandler handler = (connection, event) -> {
if (connection.equals(display) || previous[0] == null) return 0;
return Function.getFunction(previous[0]).invokeInt(new Object[]{connection, event});
};
previous[0] = x.XSetErrorHandler(handler);
try { return operation.get(); }
finally {
x.XCloseDisplay(display);
XErrorHandler restore = previous[0] == null ? null : (XErrorHandler)CallbackReference.getCallback(XErrorHandler.class, previous[0]);
x.XSetErrorHandler(restore); display = null;
java.lang.ref.Reference.reachabilityFence(handler);
}
}
}
public Snapshot snapshot() {
return connected(() -> {
long root = x.XDefaultRootWindow(display).longValue();
Property active = property(root, "_NET_ACTIVE_WINDOW");
if (active == null || active.numbers == null) return new Snapshot(null, null, false, "The X11 window manager does not expose foreground context.");
Window window = active.numbers.length == 0 ? null : window(active.numbers[0]);
return new Snapshot(window == null ? null : window.application(), window, true, "");
}, new Snapshot(null, null, false, "Cannot connect to the X11 display."));
}
public Inventory inventory() {
return connected(() -> {
long root = x.XDefaultRootWindow(display).longValue();
Property clients = property(root, "_NET_CLIENT_LIST");
if (clients == null || clients.numbers == null) return new Inventory(List.of(), List.of(), false, "The X11 window manager does not expose a window list.");
List<Window> windows = new ArrayList<>(); var apps = new LinkedHashMap<String, Application>();
for (long id : clients.numbers) {
Window window = window(id);
if (window != null) { windows.add(window); apps.putIfAbsent(window.application().identity(), window.application()); }
}
return new Inventory(new ArrayList<>(apps.values()), windows, true, "");
}, new Inventory(List.of(), List.of(), false, "Cannot connect to the X11 display."));
}
}
@@ -0,0 +1,57 @@
package de.neitzel.core.desktop;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import static org.junit.jupiter.api.Assertions.*;
class ForegroundDetectorTest {
@Test void waylandDoesNotClaimFullFocusSupportEvenWithAnXwaylandDisplay() {
try (var detector = ForegroundDetector.forEnvironment("Linux", Map.of(
"XDG_SESSION_TYPE", "wayland", "WAYLAND_DISPLAY", "wayland-0", "DISPLAY", ":0"))) {
var snapshot = detector.snapshot();
assertFalse(snapshot.focusAvailable());
assertNull(snapshot.application());
assertTrue(snapshot.limitation().contains("Wayland"));
assertFalse(detector.inventory().available());
}
}
@Test void aClosedNativeDetectorDoesNotStartOrResumeObservation() {
var detector = ForegroundDetector.forEnvironment("Mac OS X", Map.of());
detector.close();
assertFalse(detector.snapshot().focusAvailable());
assertTrue(detector.snapshot().limitation().contains("closed"));
assertFalse(detector.inventory().available());
detector.close();
}
@Test void unsupportedSessionsRemainUsableWithoutNativeLibraries() {
try (var detector = ForegroundDetector.forEnvironment("Linux", Map.of())) {
assertFalse(detector.snapshot().focusAvailable());
assertTrue(detector.snapshot().limitation().contains("X11"));
}
try (var detector = ForegroundDetector.forEnvironment("Unknown", Map.of())) {
assertFalse(detector.snapshot().focusAvailable());
assertFalse(detector.inventory().available());
}
}
@Test @EnabledIfSystemProperty(named = "desktop.native.tests", matches = "true")
void nativeForegroundAndInventoryAreObservableWithoutLoggingTitles() {
try (var detector = ForegroundDetector.system()) {
var snapshot = detector.snapshot();
assertTrue(snapshot.focusAvailable(), snapshot.limitation());
assertNotNull(snapshot.application(), "Run this smoke check with an external application in the foreground");
assertFalse(snapshot.application().identity().isBlank());
var inventory = detector.inventory();
assertTrue(inventory.available(), inventory.limitation());
assertFalse(inventory.applications().isEmpty());
if (snapshot.window() != null && snapshot.window().title() != null && !snapshot.window().title().isEmpty())
assertFalse(snapshot.window().toString().contains(snapshot.window().title()));
System.out.println("Native desktop smoke: namespace=" + snapshot.application().namespace()
+ ", appCount=" + inventory.applications().size() + ", windowCount=" + inventory.windows().size()
+ ", titleAvailable=" + (snapshot.window() != null && snapshot.window().title() != null));
}
}
}