diff --git a/build.zig b/build.zig
index 471ba26..b2b12e6 100644
--- a/build.zig
+++ b/build.zig
@@ -29,7 +29,6 @@ pub fn build(b: *std.Build) void {
const check_step = b.step("check", "Compile library and core tests without running them");
check_step.dependOn(&lib.step);
check_step.dependOn(&unit.step);
- if (target.result.os.tag == .linux) @import("src/linux/build.zig").addTests(b, lib, target, optimize, check_step);
const unit_run = b.addRunArtifact(unit);
b.step("test", "Run core library tests").dependOn(&unit_run.step);
diff --git a/src/linux/README.md b/src/linux/README.md
index 4d322f7..8076c38 100644
--- a/src/linux/README.md
+++ b/src/linux/README.md
@@ -49,13 +49,12 @@ failure requests shutdown and cancels pending work; it never switches backends.
NixOS does not normally expose every desktop library through the conventional
runtime linker search path. The optional package-owned shell supplies the pinned
-scanner, Python (including dbus-next for fixtures), dbus-daemon, clang-format
-and runtime library paths:
+scanner, Python, clang-format and runtime library paths:
```sh
nix-shell
-# Run a native application or the native tests from this shell.
-zig build test-linux-native
+# Run a native application from this shell.
+zig build
```
Zig 0.16.0 should already be on PATH. The shell is optional for compilation.
@@ -219,49 +218,8 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
From the package directory:
```sh
-zig build check # also compile the native harness
+zig build check # compile the library and core tests
zig build test # non-graphical core and file URI tests
-zig build test-linux-native # opens windows in the active session
-zig build linux-test-bin
-python3 src/linux/tests/startup.py zig-out/bin/linux-native-tests
-python3 src/linux/tests/disconnect.py zig-out/bin/linux-native-tests
-# In the optional nix-shell, or with dbus-next/dbus-daemon installed:
-python3 src/linux/tests/wayland_fixture.py zig-out/bin/linux-service-tests
-python3 src/linux/tests/editing_fixture.py zig-out/bin/linux-service-tests
-python3 src/linux/tests/window_state_fixture.py zig-out/bin/linux-service-tests
-python3 src/linux/tests/portal_fixture.py zig-out/bin/linux-service-tests
-python3 src/linux/tests/menu_fixture.py zig-out/bin/linux-service-tests
-python3 src/linux/tests/popup_fixture.py zig-out/bin/linux-service-tests
-# Opens a supplied app that exports a Quit or Quit … item, then activates that item:
-python3 src/linux/tests/menu_live.py /path/to/menu-enabled-app
-zig-out/bin/linux-service-tests desktop # live portal discovery/icons/file watches
python3 src/linux/tools/protocols.py --check
python3 src/linux/tools/bitmap-font.py --check
```
-
-The native harness exercises repeated application/window lifetimes, cancellation,
-shutdown with queued creation, show/hide/remapping, resize, GL context recreation,
-actual GL version, pixel readback and byte-preserving file URIs. The startup test
-uses isolated sockets for absent, disconnected and unresponsive servers. The
-runtime-disconnect test proxies and closes only its own client connection; it
-does not stop or modify the desktop compositor.
-
-The service fixtures own their compositor socket and D-Bus daemon. They exercise
-keys/repeat/dead-key composition, IME revisions/deletion/preedit, scrolling,
-clipboard size limits/cancellation/invalid UTF-8/early reader exit, URI drops,
-activation, portal open/save options, live settings, response-before-reply,
-cancellation with a late alternate handle, parent destruction and portal restart.
-The popup fixture checks shared-memory pixels, configure/scale handling,
-press-serial grabs, nested teardown order, disabled items, pointer/keyboard
-selection, scrolling, live flags, cancellation, outside clicks, parent destruction
-and input suppression across focus restoration. It saves a rendered menu to
-`/tmp/uhdk-popup.ppm` for inspection. Live right-click behavior still needs a
-manual compositor check; the fixture does not establish that by itself.
-The menu fixture covers D-BusMenu layout/properties/errors, state signals, window
-overrides/defaults, retained trees, stale paths, consumer restarts, 64-bit command
-IDs, role dispatch, shortcut consumption, missing protocol/bus and bus loss. The live menu check verifies KWin
-association and D-Bus round trips, not visual panel/titlebar presentation. They never open a real chooser
-or browser or inject input into the user's desktop. The live service mode checks
-portal discovery, icon submission and atomic-save watch behavior without touching
-the user's clipboard. These fixtures supplement live desktop testing; they do
-not establish compatibility with every compositor or input-method engine.
diff --git a/src/linux/build.zig b/src/linux/build.zig
index 6989635..dd2cc8e 100644
--- a/src/linux/build.zig
+++ b/src/linux/build.zig
@@ -20,28 +20,3 @@ pub fn configure(b: *std.Build, module: *std.Build.Module, target: std.Build.Res
}
module.linkSystemLibrary("dl", .{});
}
-
-pub fn addTests(b: *std.Build, lib: *std.Build.Step.Compile, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, check: *std.Build.Step) void {
- const test_module = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true });
- test_module.addIncludePath(b.path("include"));
- test_module.addCSourceFile(.{ .file = b.path("src/linux/tests/native.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-UNDEBUG" } });
- test_module.linkLibrary(lib);
- const exe = b.addExecutable(.{ .name = "linux-native-tests", .root_module = test_module });
- check.dependOn(&exe.step);
- b.step("test-linux-native", "Exercise Wayland/EGL lifecycle in the active desktop session").dependOn(&b.addRunArtifact(exe).step);
- const install = b.addInstallArtifact(exe, .{});
- b.step("linux-test-bin", "Install the Linux native test harnesses").dependOn(&install.step);
- addServiceTests(b, lib, target, optimize, check);
-}
-
-// Kept separate from automatic native smoke: fixture tests supply an isolated
-// compositor/session bus, and the live mode explicitly checks installed portals.
-pub fn addServiceTests(b: *std.Build, lib: *std.Build.Step.Compile, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, check: *std.Build.Step) void {
- const module = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true });
- module.addIncludePath(b.path("include"));
- module.addCSourceFile(.{ .file = b.path("src/linux/tests/services.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-UNDEBUG" } });
- module.linkLibrary(lib);
- const exe = b.addExecutable(.{ .name = "linux-service-tests", .root_module = module });
- check.dependOn(&exe.step);
- b.top_level_steps.get("linux-test-bin").?.step.dependOn(&b.addInstallArtifact(exe, .{}).step);
-}
diff --git a/src/linux/font/README.md b/src/linux/font/README.md
index f557748..c4dfb89 100644
--- a/src/linux/font/README.md
+++ b/src/linux/font/README.md
@@ -22,7 +22,7 @@ reserved byte). Row-major coverage uses two 4-bit samples per byte, low nibble
first. A byte with its high bit set encodes 1–128 zero bytes; otherwise it gives
the number of following literal bytes. The low seven bits hold length minus one.
-From the package directory:
+this file exists to implement the fallback right click menus in wayland desktops
```sh
python3 src/linux/tools/bitmap-font.py --check
diff --git a/src/linux/tests/disconnect.py b/src/linux/tests/disconnect.py
deleted file mode 100644
index 1f33b5d..0000000
--- a/src/linux/tests/disconnect.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/env python3
-"""Drop only a test client's proxied Wayland connection after startup."""
-import array
-import os
-from pathlib import Path
-import select
-import socket
-import subprocess
-import sys
-import threading
-
-binary = str(Path(sys.argv[1]).resolve())
-display = os.environ.get('WAYLAND_DISPLAY', 'wayland-0')
-if not os.path.isabs(display):
- display = os.path.join(os.environ['XDG_RUNTIME_DIR'], display)
-upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-upstream.connect(display)
-client, proxy = socket.socketpair()
-
-
-def relay(source, destination):
- try:
- while True:
- data, ancillary, flags, _ = source.recvmsg(65536, socket.CMSG_SPACE(256 * 4))
- if not data:
- break
- assert not flags & socket.MSG_CTRUNC
- descriptors = []
- for level, kind, value in ancillary:
- if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
- fds = array.array('i')
- fds.frombytes(value)
- descriptors.extend(fds)
- try:
- sent = destination.sendmsg([data], ancillary)
- if sent < len(data):
- destination.sendall(data[sent:])
- finally:
- for fd in descriptors:
- os.close(fd)
- except OSError:
- pass
-
-
-threads = [threading.Thread(target=relay, args=pair, daemon=True)
- for pair in [(proxy, upstream), (upstream, proxy)]]
-for thread in threads:
- thread.start()
-process = subprocess.Popen([binary, '--disconnect'],
- env=dict(os.environ, WAYLAND_SOCKET=str(client.fileno())),
- pass_fds=(client.fileno(),), stdout=subprocess.PIPE, text=True)
-client.close()
-try:
- assert select.select([process.stdout], [], [], 15)[0], 'Startup timed out'
- assert process.stdout.readline().strip() == 'connected'
- for sock in (proxy, upstream):
- sock.shutdown(socket.SHUT_RDWR)
- assert process.wait(timeout=10) == 0
- print('Runtime display disconnect: PASS')
-finally:
- if process.poll() is None:
- process.kill()
- process.wait()
- for sock in (proxy, upstream):
- sock.close()
- for thread in threads:
- thread.join(timeout=1)
diff --git a/src/linux/tests/editing_fixture.py b/src/linux/tests/editing_fixture.py
deleted file mode 100644
index d5945eb..0000000
--- a/src/linux/tests/editing_fixture.py
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env python3
-"""Forward isolated XKB keys to verify edit defaults without an application menu."""
-import sys
-from wayland_fixture import Compositor, run
-
-
-class EditingCompositor(Compositor):
- # evdev code, XKB depressed-mask (Shift=1, Control=4, Mod1=8).
- gestures = [(14, 4), (111, 4), (103, 4), (108, 5), (104, 1), (109, 0),
- (15, 1), (28, 1), (111, 1), (110, 4), (110, 1), (46, 4),
- (44, 5), (14, 12), (15, 4)]
-
- def timers(self):
- # The fixture tests forwarded keys, not compositor-owned IME input.
- pass
-
- def request(self, obj, iface, name, args):
- if iface == 'xdg_toplevel' and name == 'set_title' and args[0].startswith('edit:'):
- index = int(args[0].split(':')[1])
- code, mask = self.gestures[index]
- keyboard = self.ids['wl_keyboard']
- if index == 0:
- self.event(keyboard, 'enter', 200, next(iter(self.surfaces)), b'')
- self.event(keyboard, 'modifiers', 201, mask, 0, 0, 0)
- self.event(keyboard, 'key', 202, index * 2, code, 1)
- self.event(keyboard, 'key', 203, index * 2 + 1, code, 0)
- self.event(keyboard, 'modifiers', 204, 0, 0, 0, 0)
- super().request(obj, iface, name, args)
-
-
-if __name__ == '__main__':
- run(sys.argv[1], 'editing', compositor_type=EditingCompositor)
diff --git a/src/linux/tests/menu_fixture.py b/src/linux/tests/menu_fixture.py
deleted file mode 100644
index 919dcaa..0000000
--- a/src/linux/tests/menu_fixture.py
+++ /dev/null
@@ -1,193 +0,0 @@
-#!/usr/bin/env python3
-"""Plasma surface association and D-BusMenu on a private bus/compositor.
-
-The consumer is replaced mid-test; menu exports must not depend on its lifetime.
-No input or menu actions are sent to the user's desktop.
-"""
-import asyncio
-import os
-from pathlib import Path
-import queue
-import subprocess
-import sys
-import tempfile
-
-from dbus_next import Message, MessageType, Variant
-from dbus_next.aio import MessageBus
-from wayland_fixture import Compositor, run
-
-IFACE = 'com.canonical.dbusmenu'
-
-
-async def main(binary):
- config = tempfile.NamedTemporaryFile(mode='w', suffix='.conf')
- config.write('sessionunix:tmpdir=/tmpEXTERNAL')
- config.flush()
- daemon = subprocess.Popen(['dbus-daemon', '--config-file=' + config.name, '--nofork', '--print-address=1'], stdout=subprocess.PIPE, text=True)
- bus = None
- runner = None
- loop = asyncio.get_running_loop()
- notifications = asyncio.Queue()
- commands = queue.Queue()
- addresses = {}
- surfaces = {}
- signals = []
-
- class MenuCompositor(Compositor):
- globals = Compositor.globals + [('org_kde_kwin_appmenu_manager', 2)]
-
- def request(self, obj, iface, name, args):
- super().request(obj, iface, name, args)
- if iface == 'org_kde_kwin_appmenu_manager' and name == 'create':
- surfaces[args[0]] = args[1]
- elif iface == 'org_kde_kwin_appmenu' and name == 'set_address':
- loop.call_soon_threadsafe(notifications.put_nowait, ('address', surfaces[obj], tuple(args)))
- elif iface == 'xdg_toplevel' and name == 'set_title' and args[0].endswith('-ready'):
- loop.call_soon_threadsafe(notifications.put_nowait, ('phase', args[0]))
-
- def timers(self):
- # Only inject explicitly requested keys into this client's private socket.
- while not commands.empty():
- surface, code, press, enter, future = commands.get_nowait()
- keyboard = self.ids['wl_keyboard']
- if enter:
- self.event(keyboard, 'enter', 200, surface, b'')
- self.event(keyboard, 'modifiers', 201, 4, 0, 0, 0)
- self.event(keyboard, 'key', 202, 1, code, int(press))
- loop.call_soon_threadsafe(future.set_result, None)
-
- async def phase(name):
- while True:
- item = await asyncio.wait_for(notifications.get(), 5)
- if item[0] == 'address': addresses[item[1]] = item[2]
- else:
- assert item == ('phase', name), item
- return
-
- async def key(surface, code, press, enter=False):
- future = loop.create_future()
- commands.put((surface, code, press, enter, future))
- await future
- await asyncio.sleep(.06)
-
- async def call(address, member, signature='', body=None, interface=IFACE, error=None):
- reply = await asyncio.wait_for(bus.call(Message(destination=address[0], path=address[1], interface=interface, member=member, signature=signature, body=body or [])), 3)
- if error:
- assert reply.message_type == MessageType.ERROR and reply.error_name.endswith(error), reply
- else:
- assert reply.message_type == MessageType.METHOD_RETURN, (reply.error_name, reply.body)
- return reply.body
-
- async def layout(address, depth=-1, props=None):
- return (await call(address, 'GetLayout', 'iias', [0, depth, props or []]))[1]
-
- async def click(address, item, kind='clicked'):
- await call(address, 'Event', 'isvu', [item, kind, Variant('i', 0), 0])
- await asyncio.sleep(.03)
-
- def flatten(node):
- return [node] + [item for child in node[2] for item in flatten(child.value)]
-
- async def connect(address):
- consumer = await MessageBus(bus_address=address).connect()
- consumer.add_message_handler(lambda m: signals.append(m) if m.message_type == MessageType.SIGNAL and m.interface == IFACE else None)
- reply = await consumer.call(Message(destination='org.freedesktop.DBus', path='/org/freedesktop/DBus', interface='org.freedesktop.DBus', member='AddMatch', signature='s', body=["type='signal',interface='com.canonical.dbusmenu'"]))
- assert reply.message_type == MessageType.METHOD_RETURN
- return consumer
-
- try:
- address = daemon.stdout.readline().strip()
- bus = await connect(address)
- no_bus_env = dict(os.environ)
- no_bus_env.pop('DBUS_SESSION_BUS_ADDRESS', None)
- await asyncio.to_thread(run, binary, 'menu-noprotocol', no_bus_env)
- await asyncio.to_thread(run, binary, 'menu-nobus', no_bus_env, MenuCompositor)
- runner = asyncio.create_task(asyncio.to_thread(run, binary, 'menu', dict(os.environ, DBUS_SESSION_BUS_ADDRESS=address), MenuCompositor))
- await phase('menus-ready')
- assert len(addresses) == 2
- a, b = list(addresses)
- first, override = addresses[a], addresses[b]
- tree = await layout(first)
- nodes = flatten(tree)
- by_label = {v[1]['label'].value: v[0] for v in nodes}
- assert by_label.keys() >= {'File', 'Open__file', 'Checked', 'Disabled', 'Copy', 'Quit', 'Next'}
- open_id, toggle, disabled, copy, quit_id, step = [by_label[k] for k in ['Open__file', 'Checked', 'Disabled', 'Copy', 'Quit', 'Next']]
- assert (await call(first, 'GetProperty', 'is', [open_id, 'shortcut']))[0].value == [['Control', 'O']]
- assert (await call(first, 'GetProperty', 'is', [toggle, 'toggle-state']))[0].value == 1
- assert len((await layout(first, 0))[2]) == 0
- shallow = await layout(first, 1, ['label'])
- assert all(set(v.value[1]) == {'label'} and not v.value[2] for v in shallow[2])
- groups = (await call(first, 'GetGroupProperties', 'aias', [[], ['label']]))[0]
- assert len(groups) == len(nodes)
- assert all(set(p) == {'label'} for _, p in groups)
- assert (await call(first, 'GetGroupProperties', 'aias', [[open_id, -1], ['enabled']]))[0] == [[open_id, {'enabled': Variant('b', True)}]]
- props = (await call(first, 'GetAll', 's', [IFACE], 'org.freedesktop.DBus.Properties'))[0]
- assert props['Version'].value == 3 and props['IconThemePath'].value == []
- xml = (await call(first, 'Introspect', interface='org.freedesktop.DBus.Introspectable'))[0]
- assert 'EventGroup' in xml
- await call(first, 'Ping', interface='org.freedesktop.DBus.Peer')
- await call(first, 'GetLayout', 'i', [0], error='InvalidArgs')
- await call(first, 'GetLayout', 'iias', [0, -2, []], error='InvalidArgs')
- await call(first, 'GetLayout', 'iias', [-1, -1, []], error='InvalidMenuItem')
- await call(first, 'GetProperty', 'is', [0, 'invented'], error='UnknownProperty')
- await call(first, 'MissingMethod', error='UnknownMethod')
- assert await call(first, 'AboutToShow', 'i', [0]) == [False]
- assert await call(first, 'AboutToShowGroup', 'ai', [[0, -1]]) == [[], [-1]]
- await call(first, 'AboutToShowGroup', 'ai', [[-1]], error='InvalidMenuItem')
- assert await call(first, 'EventGroup', 'a(isvu)', [[[0, 'opened', Variant('s', ''), 0], [-1, 'clicked', Variant('i', 0), 0]]]) == [[-1]]
- await call(first, 'EventGroup', 'a(isvu)', [[[-1, 'clicked', Variant('i', 0), 0]]], error='InvalidMenuItem')
- for i in [0, by_label['File'], disabled] + [v[0] for v in nodes if v[1]['type'].value == 'separator']:
- await click(first, i)
- await click(first, open_id, 'hovered')
- await click(first, open_id)
- await click(first, copy)
- await click(first, quit_id)
- await click(override, 1)
- await click(first, step)
- await phase('flags-ready')
- assert any(m.member == 'ItemsPropertiesUpdated' for m in signals)
- assert not (await call(first, 'GetProperty', 'is', [open_id, 'enabled']))[0].value
- assert (await call(first, 'GetProperty', 'is', [toggle, 'toggle-type']))[0].value == ''
- await click(first, open_id) # Disabled ancestor blocks activation.
- await key(a, 24, True, True)
- await key(a, 24, False) # Disabled shortcut must reach raw key handling.
- await click(first, step)
- await phase('restored-ready')
- inherited = addresses[b]
- assert inherited != override
- await call(override, 'GetLayout', 'iias', [0, -1, []], error='UnknownObject')
- # A newly started consumer can obtain complete state without registration.
- bus.disconnect()
- bus = await connect(address)
- assert (await layout(inherited))[1]['children-display'].value == 'submenu'
- await key(a, 24, True, True)
- await asyncio.sleep(.1) # Repeated accelerator downs remain consumed.
- await key(a, 24, False)
- await key(a, 46, True)
- await key(a, 46, False)
- await key(b, 24, True, True)
- await key(b, 24, False)
- await click(first, step)
- await phase('detached-ready')
- await call(first, 'GetLayout', 'iias', [0, -1, []], error='UnknownObject')
- await call(inherited, 'GetLayout', 'iias', [0, -1, []], error='UnknownObject')
- bus.disconnect()
- bus = None
- daemon.terminate()
- daemon.wait(timeout=5)
- await asyncio.sleep(.1)
- # Bus loss removes the capability/association, but local shortcuts survive.
- await key(b, 49, True, True) # Ctrl+N invokes the retained window override.
- await asyncio.wait_for(runner, 5)
- print('D-BusMenu layout/errors/state/consumer restart and KDE association: PASS')
- finally:
- if bus: bus.disconnect()
- daemon.terminate()
- daemon.wait(timeout=5)
- config.close()
- if runner:
- await runner
-
-
-if __name__ == '__main__':
- asyncio.run(main(str(Path(sys.argv[1]).resolve())))
diff --git a/src/linux/tests/menu_live.py b/src/linux/tests/menu_live.py
deleted file mode 100644
index 2ce12fe..0000000
--- a/src/linux/tests/menu_live.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env python3
-"""Open a supplied menu-enabled app on Plasma, query its export, then choose Quit.
-
-The app must export a literal 'Quit' or 'Quit …' item. This checks real KWin association and
-session-bus transport; it does not assert panel or titlebar menu rendering.
-"""
-import asyncio
-import os
-import re
-import sys
-
-from dbus_next import Message, MessageType, Variant
-from dbus_next.aio import MessageBus
-
-
-async def main(binary):
- process = await asyncio.create_subprocess_exec(binary, env=dict(os.environ, WAYLAND_DEBUG='client'), stderr=asyncio.subprocess.PIPE)
- bus = None
- try:
- async def address():
- while line := await process.stderr.readline():
- match = re.search(rb'set_address\("([^"]+)", "([^"]+)"\)', line)
- if match: return [part.decode() for part in match.groups()]
- raise AssertionError('Application exited without a KDE menu association')
- service, path = await asyncio.wait_for(address(), 10)
- # Keep draining Wayland diagnostics so a full pipe cannot stall the app.
- drain = asyncio.create_task(process.stderr.read())
- bus = await MessageBus().connect()
- reply = await asyncio.wait_for(bus.call(Message(destination=service, path=path, interface='com.canonical.dbusmenu', member='GetLayout', signature='iias', body=[0, -1, []])), 5)
- assert reply.message_type == MessageType.METHOD_RETURN, reply.body
- def flatten(node):
- return [node] + [item for child in node[2] for item in flatten(child.value)]
- nodes = flatten(reply.body[1])
- labels = [node[1]['label'].value for node in nodes]
- quit_id = next(node[0] for node in nodes if node[1]['label'].value == 'Quit' or node[1]['label'].value.startswith('Quit '))
- print('Live KWin association and menu layout:', labels)
- reply = await bus.call(Message(destination=service, path=path, interface='com.canonical.dbusmenu', member='Event', signature='isvu', body=[quit_id, 'clicked', Variant('i', 0), 0]))
- assert reply.message_type == MessageType.METHOD_RETURN
- assert await asyncio.wait_for(process.wait(), 5) == 0
- await drain
- print('Live Plasma menu export / Quit activation: PASS')
- finally:
- if bus: bus.disconnect()
- if process.returncode is None:
- process.kill()
- await process.wait()
-
-
-if __name__ == '__main__':
- asyncio.run(main(sys.argv[1]))
diff --git a/src/linux/tests/menus.c b/src/linux/tests/menus.c
deleted file mode 100644
index af1c6e2..0000000
--- a/src/linux/tests/menus.c
+++ /dev/null
@@ -1,148 +0,0 @@
-/* Included by the service harness: all desktop traffic uses private fixtures. */
-#define OPEN_ID UINT64_C(0x1234567800000065)
-static void menu_phase(uhdk_session *app, uhdk_window *w, const char *phase) {
- OK(uhdk_window_set_title(w, text(phase)));
- uhdk_window_invalidate(w);
- for (;;) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t i = 0; i < events.len; ++i)
- if (events.ptr[i].type == UHDK_EVENT_WINDOW_REDRAW && events.ptr[i].window == w)
- return;
- }
-}
-static void menus(uhdk_session *app) {
- wait_capability(app, UHDK_CAP_APP_MENU);
- assert(!uhdk_has_capability(app, UHDK_CAP_CONTEXT_MENU));
- uhdk_menu_item children[] = {
- {.command_id = OPEN_ID,
- .label = {"Open_file", 9},
- .shortcut_key = 'o',
- .shortcut_modifiers = UHDK_MOD_CONTROL},
- {.command_id = 102, .label = {"Checked", 7}, .flags = UHDK_MENU_CHECKED},
- {.command_id = 103, .label = {"Disabled", 8}, .flags = UHDK_MENU_DISABLED},
- {.role = UHDK_MENU_ROLE_COPY,
- .label = {"Copy", 4},
- .shortcut_key = 'c',
- .shortcut_modifiers = UHDK_MOD_CONTROL},
- {.role = UHDK_MENU_ROLE_QUIT, .label = {"Quit", 4}},
- {.flags = UHDK_MENU_SEPARATOR},
- };
- uhdk_menu *child, *root;
- OK(uhdk_menu_create(app, children, sizeof(children) / sizeof(*children), &child));
- uhdk_menu_item roots[] = {
- {.command_id = 10, .label = {"File", 4}, .submenu = child},
- {.command_id = 900, .label = {"Next", 4}},
- };
- OK(uhdk_menu_create(app, roots, 2, &root));
- uhdk_menu_release(child);
- uint64_t id;
- OK(uhdk_set_menu(app, root));
- uhdk_window *a = window(app), *b = window(app);
- uhdk_menu_item overrides[] = {
- {.command_id = 200, .label = {"Window action", 13}},
- {.command_id = 900,
- .label = {"Next", 4},
- .shortcut_key = 'n',
- .shortcut_modifiers = UHDK_MOD_CONTROL},
- };
- uhdk_menu *override;
- OK(uhdk_menu_create(app, overrides, 2, &override));
- OK(uhdk_window_set_menu(b, override));
- uhdk_menu_release(override); // The attachment must keep its model alive.
- OK(uhdk_window_set_text_input(a, 1));
- OK(uhdk_menu_popup_async(root, a, (uhdk_point){0, 0}, (id = 1)));
- assert(wait_result(app, id).status == UHDK_STATUS_UNSUPPORTED);
- menu_phase(app, a, "menus-ready");
- unsigned stage = 0, opens_a = 0, opens_b = 0, copies = 0, quits = 0, overrides_seen = 0,
- raw_o = 0;
- uint64_t end = deadline(app);
- while (stage < 4 && uhdk_get_time_ns(app) < end) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- int next = 0;
- for (uint64_t i = 0; i < events.len; ++i) {
- const uhdk_event *e = &events.ptr[i];
- if (e->type == UHDK_EVENT_MENU_COMMAND) {
- uint64_t command = ((const uhdk_menu_event *)e->data)->command_id;
- if (command == OPEN_ID) {
- assert(stage == 0 || stage == 2);
- if (e->window == a)
- ++opens_a;
- else {
- assert(e->window == b);
- ++opens_b;
- }
- } else if (command == 200) {
- assert(e->window == b);
- ++overrides_seen;
- } else {
- assert(command == 900);
- next = 1;
- }
- } else if (e->type == UHDK_EVENT_EDIT_COMMAND) {
- const uhdk_edit_event *edit = e->data;
- assert(edit->command == UHDK_EDIT_COPY && e->window == a && e->input_id != 0);
- ++copies;
- } else if (e->type == UHDK_EVENT_QUIT_REQUESTED)
- ++quits;
- else if (e->type == UHDK_EVENT_TEXT_COMMIT)
- assert(!"accelerator leaked text");
- else if (e->type == UHDK_EVENT_KEY) {
- const uhdk_key_event *key = e->data;
- if (key->logical_key == 'o' || key->logical_key == 'O') {
- assert(stage == 1);
- ++raw_o;
- }
- assert(key->logical_key != 'c' && key->logical_key != 'C');
- }
- }
- if (!next)
- continue;
- ++stage;
- if (stage == 1) {
- assert(
- opens_a == 1 && opens_b == 0 && copies == 1 && quits == 1 && overrides_seen == 1
- );
- OK(uhdk_menu_set_item_flags(root, 10, UHDK_MENU_DISABLED));
- OK(uhdk_menu_set_item_flags(root, 102, 0));
- menu_phase(app, a, "flags-ready");
- } else if (stage == 2) {
- assert(raw_o >= 2);
- OK(uhdk_menu_set_item_flags(root, 10, 0));
- OK(uhdk_window_set_menu(b, NULL));
- menu_phase(app, a, "restored-ready");
- } else if (stage == 3) {
- assert(opens_a == 2 && opens_b == 1 && copies == 2);
- // Override survives clearing the app default, then the first window dies.
- OK(uhdk_menu_create(app, overrides, 2, &override));
- OK(uhdk_window_set_menu(b, override));
- uhdk_menu_release(override);
- OK(uhdk_set_menu(app, NULL));
- uhdk_menu_release(root);
- uhdk_window_destroy(a);
- menu_phase(app, b, "detached-ready");
- }
- }
- assert(stage == 4);
- assert(!uhdk_has_capability(app, UHDK_CAP_APP_MENU));
- uhdk_window_destroy(b);
- puts("Plasma menu routing/state/lifetime/shortcut fixture: PASS");
-}
-#undef OPEN_ID
-
-static void menus_unavailable(uhdk_session *app, int no_bus) {
- uhdk_window *w = window(app);
- uhdk_menu_item item = {.command_id = 1, .label = {"Unavailable", 11}};
- uhdk_menu *menu;
- OK(uhdk_menu_create(app, &item, 1, &menu));
- (void)no_bus;
- OK(uhdk_set_menu(app, menu));
- OK(uhdk_window_set_menu(w, menu));
- assert(!uhdk_has_capability(app, UHDK_CAP_APP_MENU));
- OK(uhdk_menu_set_item_flags(menu, 1, UHDK_MENU_CHECKED));
- OK(uhdk_set_menu(app, NULL));
- uhdk_menu_release(menu);
- uhdk_window_destroy(w);
- puts("Unavailable menu protocol/session bus: PASS");
-}
diff --git a/src/linux/tests/native.c b/src/linux/tests/native.c
deleted file mode 100644
index d1e5fce..0000000
--- a/src/linux/tests/native.c
+++ /dev/null
@@ -1,133 +0,0 @@
-#define UHDK_ENABLE_OPENGL
-#define UHDK_ENABLE_NATIVE
-#include "uhdk.h"
-#include "../../test_frame.h"
-#include
-#include
-#include
-#include
-
-#define OK(expr) assert((expr) == UHDK_STATUS_OK)
-
-static uhdk_text text(const char *s) {
- return (uhdk_text){s, strlen(s)};
-}
-static uhdk_window_metrics metrics(uhdk_window *window) {
- uhdk_window_metrics result = {0};
- result.struct_size = sizeof(result);
- OK(uhdk_window_get_metrics(window, &result));
- return result;
-}
-static void wait_metrics(uhdk_session *session, uhdk_window *window, int visible, int width) {
- uint64_t deadline = uhdk_get_time_ns(session) + 10000000000ULL;
- for (;;) {
- uhdk_window_metrics m = metrics(window);
- if (m.visible == visible && m.logical_size.width == width)
- return;
- assert(uhdk_get_time_ns(session) < deadline);
- uhdk_event_list events;
- OK(test_frame_events(session, &events));
- }
-}
-static void windows(uhdk_session *session) {
- uhdk_window_desc desc = {0};
- desc.struct_size = sizeof(desc);
- desc.title = text("UHDK additional window");
- desc.style = (uhdk_window_style){sizeof(uhdk_window_style), 1, 1, 0};
- desc.content_size = (uhdk_size){320, 240};
- uhdk_window *window = NULL;
- OK(uhdk_window_create(session, &desc, &window));
- assert(metrics(window).logical_size.width == 320); /* Ready on return. */
- assert(!metrics(window).visible);
- uhdk_native_window native = {0};
- native.struct_size = sizeof(native);
- OK(uhdk_window_get_native(window, &native));
- assert(native.backend == UHDK_BACKEND_WAYLAND && native.primary && native.secondary);
- uhdk_window_style style = {sizeof(style), 0, 0, 0};
- OK(uhdk_window_set_style(window, &style));
- style.decorated = style.resizable = 1;
- OK(uhdk_window_set_style(window, &style));
- desc.parent = window;
- uhdk_window *child = NULL;
- OK(uhdk_window_create(session, &desc, &child));
- OK(uhdk_window_destroy(child));
- for (int pass = 0; pass < 3; ++pass) {
- OK(uhdk_window_set_size(window, (uhdk_size){320 + pass * 20, 240}));
- OK(uhdk_window_set_visible(window, 1));
- wait_metrics(session, window, 1, 320 + pass * 20);
- OK(uhdk_window_set_visible(window, 0));
- wait_metrics(session, window, 0, 320 + pass * 20);
- }
- OK(uhdk_window_destroy(window));
- assert(uhdk_window_destroy(uhdk_get_window(session)) == UHDK_STATUS_INVALID_ARGUMENT);
- const uint8_t path[] = "/tmp/uhdk file-%\xff";
- uhdk_file *file;
- OK(uhdk_file_create_from_native_path(session, (uhdk_bytes){path, sizeof(path) - 1}, &file));
- uint8_t uri[256];
- uint64_t len;
- OK(uhdk_file_copy_representation(file, UHDK_FILE_URI, uri, sizeof(uri), &len));
- assert(len == strlen("file:///tmp/uhdk%20file-%25%FF"));
- assert(memcmp(uri, "file:///tmp/uhdk%20file-%25%FF", len) == 0);
- uhdk_file_release(file);
-}
-static void render(uhdk_session *session) {
- const uhdk_gl_functions *gl = uhdk_get_gl(session);
- assert(gl && gl->VERSION_3_3);
- for (int i = 0; i < 4; ++i) {
- uhdk_frame frame;
- assert(uhdk_next_frame(session, &frame));
- if (frame.drawable) {
- gl->ClearColor(0.25f, 0.5f, 0.75f, 1);
- gl->Clear(GL_COLOR_BUFFER_BIT);
- unsigned char pixel[4];
- gl->ReadPixels(10, 10, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
- assert(
- pixel[0] >= 63 && pixel[0] <= 65 && pixel[1] >= 127 && pixel[1] <= 129 &&
- pixel[2] >= 190 && pixel[2] <= 192
- );
- }
- OK(uhdk_end_frame(session));
- }
-}
-int main(int argc, char **argv) {
- int failure = argc > 1 && strcmp(argv[1], "--startup-failure") == 0;
- int windows_only = argc > 1 && strcmp(argv[1], "--windows-only") == 0;
- int disconnect = argc > 1 && strcmp(argv[1], "--disconnect") == 0;
- for (int pass = 0; pass < (disconnect ? 1 : 2); ++pass) {
- uhdk_options options = {0};
- options.struct_size = sizeof(options);
- options.title = text("UHDK Linux session test");
- options.application_id = text("org.uhdk.LifecycleTest");
- options.no_opengl = windows_only || disconnect || failure;
- options.preferred_backend = UHDK_BACKEND_X11;
- uhdk_session *session = NULL;
- assert(uhdk_open(&options, &session) == UHDK_STATUS_UNSUPPORTED);
- assert(!session);
- options.preferred_backend = UHDK_BACKEND_AUTO;
- uhdk_status status = uhdk_open(&options, &session);
- if (failure) {
- assert(status != UHDK_STATUS_OK && !session);
- continue;
- }
- OK(status);
- assert(uhdk_get_backend(session) == UHDK_BACKEND_WAYLAND);
- if (disconnect) {
- puts("connected");
- fflush(stdout);
- uint64_t deadline = uhdk_get_time_ns(session) + 5000000000ULL;
- uhdk_frame frame;
- while (uhdk_next_frame(session, &frame)) {
- assert(uhdk_get_time_ns(session) < deadline);
- OK(uhdk_end_frame(session));
- }
- assert(uhdk_get_status(session) != UHDK_STATUS_OK);
- } else {
- windows(session);
- if (!windows_only)
- render(session);
- }
- uhdk_close(session);
- }
- puts("Linux session/window lifecycle: PASS");
- return 0;
-}
diff --git a/src/linux/tests/popup_fixture.py b/src/linux/tests/popup_fixture.py
deleted file mode 100644
index 7467216..0000000
--- a/src/linux/tests/popup_fixture.py
+++ /dev/null
@@ -1,187 +0,0 @@
-#!/usr/bin/env python3
-"""Strict private Wayland popup peer; captures actual pixels to /tmp/uhdk-popup.ppm.
-
-No session bus, EGL rendering, or desktop input injection is used.
-"""
-import mmap
-import os
-from pathlib import Path
-import struct
-import sys
-import time
-from wayland_fixture import Compositor, run
-
-
-class Popups(Compositor):
- globals = Compositor.globals + [('wl_shm', 1)]
-
- def __init__(self, sock, inject=False):
- super().__init__(sock, False)
- self.stage = -1
- self.tasks = []
- self.positions = {}
- self.popup_surfaces = {}
- self.xdg_surfaces = {}
- self.stack = []
- self.pools = {}
- self.buffers = {}
- self.attached = {}
- self.trigger_serial = 500
-
- def schedule(self, delay, action):
- self.tasks.append((time.monotonic() + delay, action))
-
- def timers(self):
- ready = [x for x in self.tasks if x[0] <= time.monotonic()]
- self.tasks = [x for x in self.tasks if x[0] > time.monotonic()]
- for _, action in ready: action()
-
- def keyboard(self, code):
- keyboard = self.ids['wl_keyboard']
- self.event(keyboard, 'key', 551, 1, code, 1)
- self.event(keyboard, 'key', 552, 2, code, 0)
-
- def pointer(self, surface, x, y, click=False):
- pointer = self.ids['wl_pointer']
- self.event(pointer, 'enter', 550, surface, x * 256, y * 256)
- if click:
- self.event(pointer, 'button', 551, 1, 0x110, 1)
- self.event(pointer, 'button', 552, 2, 0x110, 0)
-
- def trigger(self):
- surface = next(iter(self.surfaces))
- self.event(self.ids['wl_keyboard'], 'enter', 499, surface, b'')
- self.event(self.ids['wl_keyboard'], 'modifiers', 499, 0, 0, 0, 0)
- self.event(self.ids['wl_pointer'], 'enter', 499, surface, 12 * 256, 16 * 256)
- self.trigger_serial += 10
- self.event(self.ids['wl_pointer'], 'button', self.trigger_serial, 1, 0x111, 1)
- self.event(self.ids['wl_pointer'], 'button', self.trigger_serial + 1, 2, 0x111, 0)
-
- def actions(self, surface, p):
- self.event(self.ids['wl_keyboard'], 'enter', 549, surface, b'')
- self.event(self.ids['wl_keyboard'], 'modifiers', 549, 0, 0, 0, 0)
- if p['child']:
- if self.stage == 10: self.schedule(.05, lambda: self.pointer(surface, 35, 15, True))
- else: self.schedule(.05, lambda: self.keyboard(28))
- elif self.stage == 0:
- # Split popup geometry from the surface configure. Hover dirties the
- # menu during the gap; the client must wait for the configure serial.
- width, height = p['size']
- self.event(p['popup'], 'configure', 10, 20, width + 4, height)
- p['pending_configure'] = True
- def acknowledge():
- p['pending_configure'] = False
- self.serial += 1
- self.event(p['xdg'], 'configure', self.serial)
- self.schedule(.06, acknowledge)
- self.pointer(surface, 35, 15)
- self.schedule(.12, lambda: self.pointer(surface, 35, 15, True))
- elif self.stage == 1:
- self.keyboard(108)
- self.keyboard(108) # Skip disabled/separator; select Checked.
- self.schedule(.05, lambda: self.event(self.ids['wl_keyboard'], 'key', 551, 1, 28, 1))
- elif self.stage == 2:
- self.keyboard(107) # End = Copy.
- self.keyboard(103) # Up = More.
- self.schedule(.05, lambda: self.keyboard(106))
- elif self.stage == 3:
- self.keyboard(1)
- elif self.stage == 4:
- self.event(p['popup'], 'popup_done')
- elif self.stage == 6:
- self.schedule(.2, lambda: self.pointer(surface, 35, 15, True))
- self.schedule(.3, lambda: self.keyboard(1))
- elif self.stage in (7, 8):
- self.keyboard(107) # Copy, or final item in the tall scrolling menu.
- self.schedule(.05, lambda: self.keyboard(28))
- elif self.stage == 9:
- self.pointer(next(iter(self.surfaces)), 15, 15, True)
- elif self.stage == 10:
- self.pointer(surface, 35, 102) # Hover opens More after a short delay.
- # Stages 5/11 are cancelled by the application after 100ms.
-
- def request(self, obj, iface, name, args):
- if iface == 'wl_surface' and name == 'commit' and obj in self.popup_surfaces:
- p = self.popup_surfaces[obj]
- assert not p.get('pending_configure', False), 'Commit before xdg_surface.configure'
- if not p['configured']:
- p['configured'] = True
- width, height = p['size']
- if self.stage == 8: height = 120
- if self.stage == 1: self.event(obj, 'preferred_buffer_scale', 2)
- self.event(p['popup'], 'configure', 10, 20, width, height)
- self.serial += 1
- self.event(p['xdg'], 'configure', self.serial)
- elif obj in self.attached:
- buf = self.attached[obj]
- meta = self.buffers[buf]
- pixels = bytes(meta['mapping'][meta['offset']:meta['offset'] + meta['stride'] * meta['height']])
- words = struct.unpack('=' + 'I' * (len(pixels) // 4), pixels)
- colors = set(words)
- assert len(colors) > 15, 'Expected antialiased bitmap text in wl_shm pixels'
- assert all((color >> 24) == 255 for color in colors)
- if self.stage == 0 and not p['child']:
- rgb = bytes(channel for color in words for channel in [(color >> 16) & 255, (color >> 8) & 255, color & 255])
- Path('/tmp/uhdk-popup.ppm').write_bytes(f"P6\n{meta['width']} {meta['height']}\n255\n".encode() + rgb)
- if self.stage == 1: assert meta['width'] == p['size'][0] * 2
- def release():
- if buf in self.objects: self.event(buf, 'release')
- self.schedule(.03, release)
- if not p['mapped']:
- p['mapped'] = True
- self.schedule(.03, lambda: self.actions(obj, p))
- return
- super().request(obj, iface, name, args)
- if iface == 'xdg_toplevel' and name == 'set_title' and args[0].startswith('popup-stage-'):
- assert not self.stack
- self.stage = int(args[0].split('-')[-1])
- self.schedule(.03, self.trigger)
- elif iface == 'xdg_wm_base' and name == 'get_xdg_surface':
- self.xdg_surfaces[args[0]] = args[1]
- elif iface == 'xdg_wm_base' and name == 'create_positioner':
- self.positions[args[0]] = {}
- elif iface == 'xdg_positioner':
- if name == 'set_size': self.positions[obj]['size'] = tuple(args)
- elif name == 'set_anchor_rect': self.positions[obj]['anchor'] = tuple(args)
- elif iface == 'xdg_surface' and name == 'get_popup':
- popup, parent, position = args
- surface = self.xdg_surfaces[obj]
- self.popup_surfaces[surface] = dict(popup=popup, xdg=obj, configured=False, mapped=False, child=bool(self.stack), **self.positions[position])
- if self.stack: assert parent == self.stack[-1][1]
- self.stack.append((popup, obj, surface))
- elif iface == 'xdg_popup' and name == 'grab':
- assert args[0] == self.ids['wl_seat'] and args[1] != 0
- assert self.stack[-1][0] == obj
- if len(self.stack) == 1: assert args[1] == self.trigger_serial, 'Must use press serial'
- elif iface == 'xdg_popup' and name == 'destroy':
- assert self.stack[-1][0] == obj, 'Destroy nested popups from the top down'
- _, _, surface = self.stack.pop()
- del self.popup_surfaces[surface]
- if self.stage == 1:
- keyboard = self.ids['wl_keyboard']
- parent = next(iter(self.surfaces))
- self.event(keyboard, 'leave', 552, surface)
- self.event(keyboard, 'enter', 553, parent, struct.pack('=I', 28))
- self.event(keyboard, 'modifiers', 553, 0, 0, 0, 0)
- self.event(keyboard, 'key', 554, 2, 28, 0) # Consumed key's release stays consumed.
- elif iface == 'wl_shm' and name == 'create_pool':
- pool, fd, size = args
- self.pools[pool] = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
- os.close(fd)
- elif iface == 'wl_shm_pool' and name == 'create_buffer':
- buf, offset, width, height, stride, fmt = args
- assert fmt == 0 and stride == width * 4
- self.buffers[buf] = dict(mapping=self.pools[obj], offset=offset, width=width, height=height, stride=stride)
- elif iface == 'wl_surface' and name == 'attach':
- self.attached[obj] = args[0]
- elif iface == 'wl_buffer' and name == 'destroy':
- self.buffers.pop(obj, None)
- elif iface == 'wl_surface' and name == 'destroy':
- self.surfaces.pop(obj, None)
-
-
-if __name__ == '__main__':
- environment = dict(os.environ)
- environment.pop('DBUS_SESSION_BUS_ADDRESS', None)
- run(sys.argv[1], 'popup', environment, Popups)
- print('Wayland popup grab/stack/configure/scale and software pixels: PASS')
diff --git a/src/linux/tests/popups.c b/src/linux/tests/popups.c
deleted file mode 100644
index 5f050b7..0000000
--- a/src/linux/tests/popups.c
+++ /dev/null
@@ -1,110 +0,0 @@
-/* Included by services.c; driven by popup_fixture.py on a private compositor. */
-#define POPUP_OPEN UINT64_C(0x1234567800000001)
-#define POPUP_CHILD UINT64_C(0xfedcba9800000002)
-static void popups(uhdk_session *app) {
- uhdk_window *w = window(app);
- wait_capability(app, UHDK_CAP_CONTEXT_MENU);
- assert(!uhdk_has_capability(app, UHDK_CAP_APP_MENU));
- uint64_t id;
- OK(uhdk_window_set_visible(w, 1));
- OK(uhdk_window_set_text_input(w, 1));
- uhdk_menu_item child_items[] = {{.command_id = POPUP_CHILD, .label = {"Child café", 11}}};
- uhdk_menu *child, *root;
- OK(uhdk_menu_create(app, child_items, 1, &child));
- uhdk_menu_item items[] = {
- {.command_id = POPUP_OPEN,
- .label = {"Open…", 7},
- .shortcut_key = 'o',
- .shortcut_modifiers = UHDK_MOD_CONTROL},
- {.command_id = 102, .label = {"Disabled", 8}, .flags = UHDK_MENU_DISABLED},
- {.flags = UHDK_MENU_SEPARATOR},
- {.command_id = 103, .label = {"Checked", 7}, .flags = UHDK_MENU_CHECKED},
- {.command_id = 104, .label = {"More", 4}, .submenu = child},
- {.label = {"Copy", 4}, .role = UHDK_MENU_ROLE_COPY},
- };
- OK(uhdk_menu_create(app, items, 6, &root));
- uhdk_menu_release(child);
- OK(uhdk_menu_popup_async(root, w, (uhdk_point){4, 4}, (id = 1)));
- assert(wait_result(app, id).status == UHDK_STATUS_UNAVAILABLE); // No input action yet.
- for (unsigned stage = 0; stage < 12; ++stage) {
- uhdk_menu *menu = root;
- if (stage == 8) {
- uhdk_menu_item many[32] = {0};
- for (unsigned j = 0; j < 32; ++j) {
- many[j].command_id = 1000 + j;
- many[j].label = text("Scrollable item");
- }
- OK(uhdk_menu_create(app, many, 32, &menu));
- }
- char title[64];
- snprintf(title, sizeof(title), "popup-stage-%u", stage);
- OK(uhdk_window_set_title(w, text(title)));
- uint64_t popup = 0, busy = 0, started = 0;
- unsigned commands = 0, complete = 0, busy_done = 0, changed = 0;
- uint64_t end = deadline(app);
- while (!complete && uhdk_get_time_ns(app) < end) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t j = 0; j < events.len; ++j) {
- const uhdk_event *e = &events.ptr[j];
- if (e->type == UHDK_EVENT_POINTER_BUTTON) {
- const uhdk_pointer_event *p = e->data;
- assert(p->button == UHDK_BUTTON_SECONDARY);
- if (p->pressed) {
- assert(popup == 0);
- OK(uhdk_menu_popup_async(menu, w, p->position, (popup = 2)));
- started = uhdk_get_time_ns(app);
- if (stage == 0)
- OK(uhdk_menu_popup_async(menu, w, p->position, (busy = 3)));
- }
- } else if (e->type == UHDK_EVENT_MENU_COMMAND) {
- uint64_t command = ((const uhdk_menu_event *)e->data)->command_id;
- uint64_t expected = stage == 0 ? POPUP_OPEN
- : stage == 1 ? 103
- : (stage == 2 || stage == 10) ? POPUP_CHILD
- : 1031;
- assert(stage == 0 || stage == 1 || stage == 2 || stage == 8 || stage == 10);
- assert(command == expected && e->window == w);
- ++commands;
- } else if (e->type == UHDK_EVENT_EDIT_COMMAND) {
- assert(stage == 7 && e->window == w && e->input_id != 0);
- assert(((const uhdk_edit_event *)e->data)->command == UHDK_EDIT_COPY);
- ++commands;
- } else if (e->type == UHDK_EVENT_REQUEST_DONE) {
- const uhdk_request_result *r = e->data;
- if (r->tag == popup && popup) {
- int selected = stage <= 2 || stage == 7 || stage == 8 || stage == 10;
- assert(r->status == (selected ? UHDK_STATUS_OK : UHDK_STATUS_CANCELLED));
- assert(commands == (unsigned)selected); // Ordering and exactly one action.
- ++complete;
- } else if (r->tag == busy && busy) {
- assert(r->status == UHDK_STATUS_BUSY);
- ++busy_done;
- } else
- OK(r->status);
- } else if (e->type == UHDK_EVENT_KEY || e->type == UHDK_EVENT_TEXT_COMMIT)
- assert(!"popup input leaked to application");
- }
- if (popup && !changed && uhdk_get_time_ns(app) - started > 100000000ull) {
- if (stage == 5)
- OK(uhdk_request_cancel(app, popup));
- if (stage == 6) {
- OK(uhdk_menu_set_item_flags(root, POPUP_OPEN, UHDK_MENU_DISABLED));
- OK(uhdk_menu_set_item_flags(root, 103, 0));
- }
- if (stage == 11)
- uhdk_window_destroy(w);
- changed = 1;
- }
- }
- assert(complete == 1);
- if (stage == 0)
- assert(busy_done == 1);
- if (stage == 8)
- uhdk_menu_release(menu);
- }
- uhdk_menu_release(root);
- puts("software popup selection/roles/submenus/cancellation/input/scroll/lifetime: PASS");
-}
-#undef POPUP_OPEN
-#undef POPUP_CHILD
diff --git a/src/linux/tests/portal_fixture.py b/src/linux/tests/portal_fixture.py
deleted file mode 100644
index bc5a834..0000000
--- a/src/linux/tests/portal_fixture.py
+++ /dev/null
@@ -1,129 +0,0 @@
-#!/usr/bin/env python3
-"""Exercise portal races on a private session bus and private Wayland socket.
-
-Needs dbus-daemon and Python dbus-next (provided by the optional shell.nix).
-Never calls the user's portal, opens a real dialog, or launches a URL handler.
-"""
-import asyncio
-import os
-from pathlib import Path
-import subprocess
-import sys
-
-from dbus_next import Message, MessageType, Variant
-from dbus_next.aio import MessageBus
-from wayland_fixture import run
-
-DESKTOP = 'org.freedesktop.portal.Desktop'
-PATH = '/org/freedesktop/portal/desktop'
-REQUEST = 'org.freedesktop.portal.Request'
-
-
-async def main(binary):
- daemon = subprocess.Popen(['dbus-daemon', '--session', '--nofork', '--print-address=1'], stdout=subprocess.PIPE, text=True)
- bus = None
- tasks = set()
- closed = []
- seen = set()
- try:
- address = daemon.stdout.readline().strip()
- assert address
- bus = await MessageBus(bus_address=address).connect()
- await bus.request_name(DESKTOP)
-
- def response(handle, code=0, results=None):
- bus.send(Message.new_signal(handle, REQUEST, 'Response', 'ua{sv}', [code, results or {}]))
-
- async def delayed_reply(message, handle, delay, is_url=False):
- await asyncio.sleep(delay)
- bus.send(Message.new_method_return(message, 'o', [handle]))
- if is_url:
- for key, value in [('color-scheme', 2), ('contrast', 0), ('reduced-motion', 0)]:
- bus.send(Message.new_signal(PATH, 'org.freedesktop.portal.Settings', 'SettingChanged', 'ssv', ['org.freedesktop.appearance', key, Variant('u', value)]))
- response(handle)
-
- async def restart():
- await bus.release_name(DESKTOP)
- await asyncio.sleep(.1)
- await bus.request_name(DESKTOP)
-
- def schedule(coro):
- task = asyncio.create_task(coro)
- tasks.add(task)
- task.add_done_callback(tasks.discard)
-
- def handle(message):
- if message.message_type != MessageType.METHOD_CALL:
- return False
- if message.interface == 'org.freedesktop.DBus.Properties' and message.member == 'Get':
- assert message.body == ['org.freedesktop.portal.FileChooser', 'version']
- bus.send(Message.new_method_return(message, 'v', [Variant('u', 4)]))
- elif message.interface == 'org.freedesktop.portal.Settings' and message.member == 'ReadAll':
- assert message.body == [['org.freedesktop.appearance']]
- bus.send(Message.new_method_return(message, 'a{sa{sv}}', [{'org.freedesktop.appearance': {
- 'color-scheme': Variant('u', 1), 'contrast': Variant('u', 1), 'reduced-motion': Variant('u', 1)}}]))
- elif message.interface in ('org.freedesktop.portal.FileChooser', 'org.freedesktop.portal.OpenURI'):
- parent, title, options = message.body
- token = options['handle_token'].value
- handle_path = PATH + '/request/' + message.sender[1:].replace('.', '_') + '/' + token
- if message.member == 'OpenURI':
- assert title == 'https://example.org/test'
- assert options['activation_token'].value == 'fixture-token'
- schedule(delayed_reply(message, handle_path, .35, True))
- seen.add('url')
- return True
- seen.add(title)
- assert message.signature == 'ssa{sv}'
- if message.member == 'OpenFile':
- assert options['multiple'].value and not options['directory'].value
- assert options['filters'].value == [['Text', [[0, '*.txt'], [0, '*.md']]]]
- if title == 'success':
- assert parent == 'wayland:fixture-parent'
- assert options['modal'].value
- # A fast response can beat the method return. The frontend
- # must already be subscribed using its chosen handle token.
- response(handle_path, results={'uris': Variant('as', ['file:///tmp/a%20b%25%FF.txt', 'file:///tmp/second'])})
- bus.send(Message.new_method_return(message, 'o', [handle_path]))
- elif title == 'save':
- assert message.member == 'SaveFile'
- assert options['current_name'].value == 'book.txt'
- assert options['accept_label'].value == 'Store'
- assert bytes(options['current_folder'].value) == b'/tmp\0'
- bus.send(Message.new_method_return(message, 'o', [handle_path]))
- response(handle_path, results={'uris': Variant('as', ['file:///tmp/save.txt'])})
- elif title == 'cancel':
- # Return a different handle after local cancellation; both
- # the predicted and returned paths need Close calls.
- schedule(delayed_reply(message, handle_path + '_late', .2))
- elif title == 'parent':
- bus.send(Message.new_method_return(message, 'o', [handle_path]))
- elif title == 'restart':
- schedule(restart())
- elif title == 'dismiss':
- bus.send(Message.new_method_return(message, 'o', [handle_path]))
- response(handle_path, 1)
- else:
- raise AssertionError(title)
- elif message.interface == REQUEST and message.member == 'Close':
- closed.append(message.path)
- bus.send(Message.new_method_return(message))
- else:
- return False
- return True
-
- bus.add_message_handler(handle)
- await asyncio.to_thread(run, binary, 'portal', dict(os.environ, DBUS_SESSION_BUS_ADDRESS=address))
- await asyncio.sleep(.1)
- assert {'success', 'save', 'cancel', 'url', 'restart', 'dismiss'} <= seen, seen
- assert any(p.endswith('_late') for p in closed), closed
- assert len(closed) >= 2, closed
- print('private portal protocol/cancellation/restart fixture: PASS')
- finally:
- for task in tasks: task.cancel()
- if bus: bus.disconnect()
- daemon.terminate()
- daemon.wait(timeout=5)
-
-
-if __name__ == '__main__':
- asyncio.run(main(str(Path(sys.argv[1]).resolve())))
diff --git a/src/linux/tests/services.c b/src/linux/tests/services.c
deleted file mode 100644
index 71a92c5..0000000
--- a/src/linux/tests/services.c
+++ /dev/null
@@ -1,511 +0,0 @@
-#define _GNU_SOURCE
-#include "uhdk.h"
-#include "../../test_frame.h"
-#include
-#include
-#include
-#include
-#include
-
-#define OK(expr) \
- do { \
- uhdk_status status_ = (expr); \
- if (status_ != UHDK_STATUS_OK) { \
- fprintf(stderr, "%d: %s: status %u\n", __LINE__, #expr, status_); \
- abort(); \
- } \
- } while (0)
-static uhdk_text text(const char *s) {
- return (uhdk_text){s, strlen(s)};
-}
-static uint64_t deadline(uhdk_session *app) {
- return uhdk_get_time_ns(app) + 8000000000ull;
-}
-static uhdk_request_result wait_result(uhdk_session *app, uint64_t id) {
- uint64_t end = deadline(app);
- while (uhdk_get_time_ns(app) < end) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t i = 0; i < events.len; ++i)
- if (events.ptr[i].type == UHDK_EVENT_REQUEST_DONE) {
- const uhdk_request_result *r = events.ptr[i].data;
- if (r->tag == id)
- return *r;
- }
- }
- fprintf(stderr, "request %lu timed out\n", (unsigned long)id);
- abort();
-}
-static uhdk_window *window(uhdk_session *app) {
- uhdk_window_desc desc = {0};
- desc.struct_size = sizeof(desc);
- desc.title = text("UHDK service tests");
- desc.content_size = (uhdk_size){320, 240};
- desc.style = (uhdk_window_style){sizeof(uhdk_window_style), 1, 1, 0};
- uhdk_window *result = NULL;
- OK(uhdk_window_create(app, &desc, &result));
- uint64_t end = deadline(app);
- while (uhdk_get_time_ns(app) < end) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t i = 0; i < events.len; ++i) {
- if (events.ptr[i].type == UHDK_EVENT_WINDOW_METRICS && events.ptr[i].window == result)
- return result;
- }
- }
- abort();
-}
-static void wait_capability(uhdk_session *app, uint32_t cap) {
- uint64_t end = deadline(app);
- while (!uhdk_has_capability(app, cap) && uhdk_get_time_ns(app) < end) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- }
- assert(uhdk_has_capability(app, cap));
-}
-static void write_file(const char *path, const char *bytes) {
- FILE *f = fopen(path, "wb");
- assert(f);
- assert(fwrite(bytes, 1, strlen(bytes), f) == strlen(bytes));
- assert(fclose(f) == 0);
-}
-static void wait_change(uhdk_session *app, uhdk_watch *watch, uint32_t flag) {
- uint64_t end = deadline(app);
- while (uhdk_get_time_ns(app) < end) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t i = 0; i < events.len; ++i)
- if (events.ptr[i].type == UHDK_EVENT_WATCH) {
- const uhdk_watch_event *e = events.ptr[i].data;
- if (e->watch == watch && (e->flags & flag)) {
- OK(e->status);
- return;
- }
- }
- }
- fprintf(stderr, "watch flag %x timed out\n", flag);
- abort();
-}
-static void watches(uhdk_session *app) {
- char directory[] = "/tmp/uhdk-watch-XXXXXX";
- assert(mkdtemp(directory));
- char path[256], replacement[256];
- snprintf(path, sizeof(path), "%s/document", directory);
- snprintf(replacement, sizeof(replacement), "%s/replacement", directory);
- write_file(path, "old");
- uhdk_file *file;
- OK(uhdk_file_create_from_native_path(
- app, (uhdk_bytes){(const uint8_t *)path, strlen(path)}, &file
- ));
- uint64_t id;
- OK(uhdk_watch_create_async(file, (id = 1)));
- uhdk_request_result result = wait_result(app, id);
- OK(result.status);
- uhdk_watch *watch = ((const uhdk_watch_result *)result.data)->watch;
- write_file(replacement, "new");
- assert(rename(replacement, path) == 0);
- wait_change(app, watch, UHDK_CHANGE_CREATED);
- write_file(path, "after replacement");
- wait_change(app, watch, UHDK_CHANGE_CONTENT);
- assert(unlink(path) == 0);
- wait_change(app, watch, UHDK_CHANGE_REMOVED);
- write_file(path, "recreated");
- wait_change(app, watch, UHDK_CHANGE_CREATED);
- assert(unlink(path) == 0);
- assert(rmdir(directory) == 0);
- wait_change(app, watch, UHDK_CHANGE_ROOT_INVALIDATED);
- uhdk_watch_destroy(watch);
- uhdk_file_release(file);
- puts("watch replacement/removal/recreation/invalidation: PASS");
-}
-static void real_desktop(uhdk_session *app) {
- wait_capability(app, UHDK_CAP_FILE_DIALOGS);
- uhdk_preferences prefs = {0};
- prefs.struct_size = sizeof(prefs);
- OK(uhdk_get_preferences(app, &prefs));
- printf(
- "Portal available; appearance=%u, reduced_motion=%d, high_contrast=%d\n",
- prefs.appearance,
- prefs.reduced_motion,
- prefs.high_contrast
- );
- watches(app);
- uhdk_window *w = window(app);
- uint8_t rgba[] = {255, 0, 0, 128, 0, 255, 0, 255};
- uhdk_image image = {0};
- image.struct_size = sizeof(image);
- image.width = 2;
- image.height = 1;
- image.pixels = (uhdk_bytes){rgba, sizeof(rgba)};
- OK(uhdk_set_icon(app, &image));
- // A hidden, unfocused window must not commandeer a later user's keystroke.
- OK(uhdk_clipboard_write_text(app, text("must not replace clipboard")));
- uhdk_window_destroy(w);
-}
-static void portals(uhdk_session *app) {
- wait_capability(app, UHDK_CAP_FILE_DIALOGS);
- uhdk_window *w = window(app);
- uhdk_file_dialog_desc desc = {0};
- desc.struct_size = sizeof(desc);
- desc.parent = w;
- desc.title = text("success");
- desc.kind = UHDK_DIALOG_OPEN_FILES;
- uhdk_text extensions[] = {text("txt"), text("md")};
- uhdk_file_filter filter = {text("Text"), {extensions, 2}};
- desc.filters = &filter;
- desc.filters_len = 1;
- uint64_t id;
- OK(uhdk_file_dialog_show_async(app, &desc, (id = 2)));
- uhdk_request_result r = wait_result(app, id);
- OK(r.status);
- const uhdk_file_list *files = r.data;
- assert(files->len == 2);
- uint8_t bytes[256];
- uint64_t len;
- OK(uhdk_file_copy_representation(
- files->ptr[0], UHDK_FILE_NATIVE_PATH, bytes, sizeof(bytes), &len
- ));
- assert(len == 14 && memcmp(bytes, "/tmp/a b%\xff.txt", 14) == 0);
- uhdk_preferences prefs = {0};
- prefs.struct_size = sizeof(prefs);
- OK(uhdk_get_preferences(app, &prefs));
- assert(prefs.appearance == UHDK_APPEARANCE_DARK && prefs.reduced_motion && prefs.high_contrast);
- uhdk_file *directory;
- OK(
- uhdk_file_create_from_native_path(app, (uhdk_bytes){(const uint8_t *)"/tmp", 4}, &directory)
- );
- desc.title = text("save");
- desc.kind = UHDK_DIALOG_SAVE_FILE;
- desc.suggested_name = text("book.txt");
- desc.accept_label = text("Store");
- desc.initial_directory = directory;
- OK(uhdk_file_dialog_show_async(app, &desc, (id = 3)));
- r = wait_result(app, id);
- OK(r.status);
- assert(((const uhdk_file_list *)r.data)->len == 1);
- uhdk_file_release(directory);
- desc.kind = UHDK_DIALOG_OPEN_FILES;
- desc.initial_directory = NULL;
- desc.suggested_name = text("");
- desc.accept_label = text("");
- desc.title = text("cancel");
- OK(uhdk_file_dialog_show_async(app, &desc, (id = 4)));
- // Allow method submission, then cancel while the mock withholds its reply.
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- OK(uhdk_request_cancel(app, id));
- assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
- OK(uhdk_shell_open_url_async(app, text("https://example.org/test"), (id = 5)));
- OK(wait_result(app, id).status);
- OK(uhdk_get_preferences(app, &prefs));
- assert(
- prefs.appearance == UHDK_APPEARANCE_LIGHT && !prefs.reduced_motion && !prefs.high_contrast
- );
- desc.title = text("parent");
- OK(uhdk_file_dialog_show_async(app, &desc, (id = 6)));
- uhdk_window_destroy(w);
- assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
-
- desc.parent = NULL;
- desc.title = text("restart");
- OK(uhdk_file_dialog_show_async(app, &desc, (id = 7)));
- assert(wait_result(app, id).status == UHDK_STATUS_UNAVAILABLE);
- wait_capability(app, UHDK_CAP_FILE_DIALOGS);
- desc.title = text("dismiss");
- OK(uhdk_file_dialog_show_async(app, &desc, (id = 8)));
- assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
- puts("portal results/cancellation/parent/restart: PASS");
-}
-static void window_observations(uhdk_session *app, int version) {
- uhdk_window *w = window(app);
- uhdk_window_metrics metrics = {0};
- metrics.struct_size = sizeof(metrics);
- OK(uhdk_window_get_metrics(w, &metrics));
- uint32_t known =
- UHDK_WINDOW_OBSERVE_RESIZING | (version >= 6 ? UHDK_WINDOW_OBSERVE_SUSPENDED : 0);
- assert(metrics.observations == known);
- assert(!metrics.minimized && !metrics.occluded && !metrics.suspended && !metrics.resizing);
- OK(uhdk_window_set_state(w, UHDK_WINDOW_MINIMIZED));
- OK(uhdk_window_set_state(w, UHDK_WINDOW_FULLSCREEN));
- for (int phase = 0; phase < 2; ++phase) {
- OK(uhdk_window_set_title(w, text(phase ? "fixture:resume" : "fixture:suspend")));
- uhdk_window_invalidate(w);
- int matched = 0, completed = 0;
- uint64_t end = deadline(app);
- while (uhdk_get_time_ns(app) < end && !(matched && completed)) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t i = 0; i < events.len; ++i) {
- if (events.ptr[i].type == UHDK_EVENT_WINDOW_METRICS) {
- const uhdk_window_metrics *m = events.ptr[i].data;
- assert(m->observations == known);
- assert(!m->minimized && !m->occluded);
- if (m->state == (phase ? UHDK_WINDOW_NORMAL : UHDK_WINDOW_FULLSCREEN) &&
- !!m->resizing == !phase && !!m->focused == !phase &&
- !!m->suspended == (!phase && version >= 6))
- matched = 1;
- } else if (events.ptr[i].type == UHDK_EVENT_WINDOW_REDRAW &&
- events.ptr[i].window == w)
- completed = 1;
- }
- }
- assert(matched && completed);
- }
- OK(uhdk_window_set_state(w, UHDK_WINDOW_MINIMIZED));
- OK(uhdk_window_get_metrics(w, &metrics));
- assert(!(metrics.observations & UHDK_WINDOW_OBSERVE_MINIMIZED));
- assert(metrics.state == UHDK_WINDOW_NORMAL); // Submission is not observation.
- uhdk_window_destroy(w);
- puts("Wayland versioned window observations/capabilities: PASS");
-}
-
-static void editing(uhdk_session *app) {
- uhdk_window *w = window(app);
- OK(uhdk_window_set_text_input(w, 1));
- const struct {
- uint32_t command;
- int extend;
- } cases[] = {
- {UHDK_EDIT_DELETE_WORD_BACKWARD, 0},
- {UHDK_EDIT_DELETE_WORD_FORWARD, 0},
- {UHDK_EDIT_PARAGRAPH_START, 0},
- {UHDK_EDIT_PARAGRAPH_END, 1},
- {UHDK_EDIT_PAGE_UP, 1},
- {UHDK_EDIT_PAGE_DOWN, 0},
- {UHDK_EDIT_BACKTAB, 0},
- {UHDK_EDIT_LINE_BREAK, 0},
- {UHDK_EDIT_CUT, 0},
- {UHDK_EDIT_COPY, 0},
- {UHDK_EDIT_PASTE, 0},
- {UHDK_EDIT_COPY, 0},
- {UHDK_EDIT_REDO, 0},
- {0, 0},
- {0, 0}
- };
- uint64_t acknowledged = 0;
- for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) {
- uhdk_text_state state = {0};
- state.struct_size = sizeof(state);
- state.surrounding_text = text("one two");
- state.selection_start = 7;
- state.revision = i + 1;
- state.acknowledged_input_id = acknowledged;
- OK(uhdk_window_set_text_state(w, &state));
- char title[32];
- snprintf(title, sizeof(title), "edit:%u", i);
- OK(uhdk_window_set_title(w, text(title)));
- uhdk_window_invalidate(w);
- int released = 0, completed = 0;
- unsigned commands = 0;
- uint64_t end = deadline(app);
- while (uhdk_get_time_ns(app) < end && !(released && completed)) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t j = 0; j < events.len; ++j) {
- const uhdk_event *event = &events.ptr[j];
- assert(event->type != UHDK_EVENT_TEXT_COMMIT);
- if (event->type == UHDK_EVENT_KEY) {
- const uhdk_key_event *key = event->data;
- if (!key->pressed)
- released = 1;
- } else if (event->type == UHDK_EVENT_EDIT_COMMAND) {
- const uhdk_edit_event *edit = event->data;
- assert(edit->command == cases[i].command);
- assert(!!edit->extend_selection == cases[i].extend);
- acknowledged = event->input_id;
- ++commands;
- } else if (event->type == UHDK_EVENT_WINDOW_REDRAW && event->window == w)
- completed = 1;
- }
- }
- assert(released && completed && commands == (cases[i].command ? 1u : 0u));
- }
- uhdk_window_destroy(w);
- puts("Wayland editing defaults/selection/AltGr/no duplicate text: PASS");
-}
-
-static void input(uhdk_session *app) {
- uhdk_window *w = window(app);
- uint64_t id;
- OK(uhdk_window_set_text_input(w, 1));
- OK(uhdk_window_set_drop_enabled(w, 1));
- uhdk_text_state state = {0};
- state.struct_size = sizeof(state);
- state.surrounding_text = text("abc");
- state.revision = 77;
- state.selection_start = 1;
- state.selection_len = 1;
- OK(uhdk_window_set_text_state(w, &state));
- unsigned key = 0, repeat = 0, commit = 0, preedit = 0, pointer = 0, scroll = 0, dropped = 0,
- copy = 0, compose = 0, captured = 0, released = 0;
- uint64_t acknowledged = 0;
- int published = 0;
- uint64_t end = deadline(app);
- while (uhdk_get_time_ns(app) < end &&
- !(key && repeat && commit >= 2 && preedit && pointer && scroll && dropped && copy &&
- compose && captured && released)) {
- uhdk_event_list events;
- OK(test_frame_events(app, &events));
- for (uint64_t i = 0; i < events.len; ++i) {
- const uhdk_event *e = &events.ptr[i];
- if (e->input_id > acknowledged)
- acknowledged = e->input_id;
- switch (e->type) {
- case UHDK_EVENT_KEY: {
- const uhdk_key_event *k = e->data;
- if (k->physical_key == 4 && k->logical_key == 'a' && k->pressed)
- key++;
- if (k->physical_key == 224)
- assert(!!(k->modifiers & UHDK_MOD_CONTROL) == !!k->pressed);
- if (k->logical_key == 'A' && k->pressed)
- assert(!(k->modifiers & UHDK_MOD_SHIFT));
- if (k->repeat)
- repeat++;
- break;
- }
- case UHDK_EVENT_EDIT_COMMAND:
- if (((const uhdk_edit_event *)e->data)->command == UHDK_EDIT_COPY)
- copy++;
- break;
- case UHDK_EVENT_TEXT_COMMIT: {
- const uhdk_text_event *t = e->data;
- if (t->text.len == 1 && t->text.ptr[0] == 'a')
- commit++;
- if (t->text.len == 2 && memcmp(t->text.ptr, "é", 2) == 0)
- compose++;
- if (t->has_replacement) {
- assert(
- t->revision == 77 && t->replacement_start == 0 && t->replacement_len == 3
- );
- commit++;
- }
- break;
- }
- case UHDK_EVENT_TEXT_PREEDIT: {
- const uhdk_text_event *t = e->data;
- assert(t->text.len == 2 && memcmp(t->text.ptr, "é", 2) == 0);
- preedit++;
- break;
- }
- case UHDK_EVENT_POINTER_BUTTON:
- if (((const uhdk_pointer_event *)e->data)->pressed)
- OK(uhdk_window_set_pointer_mode(w, UHDK_POINTER_CAPTURE));
- break;
- case UHDK_EVENT_POINTER_MODE_CHANGED:
- if (((const uhdk_pointer_mode_event *)e->data)->mode == UHDK_POINTER_CAPTURE)
- captured++;
- else
- released++;
- break;
- case UHDK_EVENT_POINTER_MOVE: {
- const uhdk_pointer_event *p = e->data;
- if (p->position.x == 12 && p->position.y == 18)
- pointer++;
- break;
- }
- case UHDK_EVENT_SCROLL: {
- const uhdk_scroll_event *s = e->data;
- assert(s->unit == UHDK_SCROLL_LINES && s->delta.y == 0.5f);
- scroll++;
- break;
- }
- case UHDK_EVENT_DROP_FILES: {
- const uhdk_drop_files_event *d = e->data;
- assert(d->files.len == 1 && d->position.x == 12);
- dropped++;
- break;
- }
- default:
- break;
- }
- }
- if (repeat && !published) {
- state.surrounding_text = text("abcd");
- state.revision = 78;
- state.acknowledged_input_id = acknowledged;
- OK(uhdk_window_set_text_state(w, &state));
- published = 1;
- }
- }
- fprintf(
- stderr,
- "input: key=%u repeat=%u commit=%u preedit=%u pointer=%u scroll=%u drop=%u copy=%u\n",
- key,
- repeat,
- commit,
- preedit,
- pointer,
- scroll,
- dropped,
- copy
- );
- assert(
- key && repeat && commit >= 2 && preedit && pointer && scroll && dropped && copy && compose
- );
- OK(uhdk_clipboard_read_text_async(app, 3, (id = 9)));
- assert(wait_result(app, id).status == UHDK_STATUS_BUFFER_TOO_SMALL);
- OK(uhdk_clipboard_read_text_async(app, 100, (id = 10)));
- uhdk_request_result r = wait_result(app, id);
- OK(r.status);
- const uhdk_text *t = r.data;
- assert(t->len == 11 && memcmp(t->ptr, "hello café", 11) == 0);
- OK(uhdk_clipboard_read_text_async(app, 100, (id = 11)));
- uhdk_event_list pause;
- OK(test_frame_events(app, &pause));
- OK(uhdk_request_cancel(app, id));
- assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
- OK(uhdk_clipboard_read_text_async(app, 100, (id = 12)));
- assert(wait_result(app, id).status == UHDK_STATUS_INVALID_ARGUMENT);
- OK(uhdk_clipboard_read_text_async(app, 0, (id = 13)));
- r = wait_result(app, id);
- OK(r.status);
- assert(((const uhdk_text *)r.data)->len == 0);
- OK(uhdk_clipboard_write_text(app, text("local copy")));
- OK(uhdk_window_request_focus(w));
- uhdk_window_destroy(w);
- puts("input/IME/clipboard/drop/activation: PASS");
-}
-#include "menus.c"
-#include "popups.c"
-
-static void run(uhdk_session *app, void *mode) {
- if (strcmp(mode, "popup") == 0) {
- popups(app);
- return;
- }
- if (strcmp(mode, "menu-noprotocol") == 0 || strcmp(mode, "menu-nobus") == 0) {
- menus_unavailable(app, strcmp(mode, "menu-nobus") == 0);
- return;
- }
- if (strcmp(mode, "menu") == 0) {
- menus(app);
- return;
- }
- if (strncmp(mode, "window-state-v", 14) == 0) {
- window_observations(app, atoi(mode + 14));
- return;
- }
- if (strcmp(mode, "editing") == 0) {
- editing(app);
- return;
- }
- if (strcmp(mode, "input") == 0)
- input(app);
- else if (strcmp(mode, "portal") == 0)
- portals(app);
- else
- real_desktop(app);
-}
-int main(int argc, char **argv) {
- assert(argc == 2);
- uhdk_options options = {0};
- options.struct_size = sizeof(options);
- options.title = text("UHDK service tests");
- options.application_id = text("org.uhdk.ServiceTests");
- options.no_opengl = UHDK_TRUE;
- uhdk_session *app;
- OK(uhdk_open(&options, &app));
- run(app, argv[1]);
- uhdk_close(app);
- return 0;
-}
diff --git a/src/linux/tests/startup.py b/src/linux/tests/startup.py
deleted file mode 100644
index acce75d..0000000
--- a/src/linux/tests/startup.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python3
-"""Exercise failed Wayland startup without opening windows or changing a desktop."""
-import os
-from pathlib import Path
-import socket
-import subprocess
-import sys
-import tempfile
-import time
-
-binary = str(Path(sys.argv[1]).resolve())
-with tempfile.TemporaryDirectory(prefix='uhdk-startup-') as directory:
- env = dict(os.environ, WAYLAND_DISPLAY=directory + '/missing', XDG_RUNTIME_DIR=directory)
- env.pop('WAYLAND_SOCKET', None)
- subprocess.run([binary, '--startup-failure'], env=env, check=True, timeout=15)
- for scenario in ('disconnected', 'unresponsive'):
- client, server = socket.socketpair()
- env['WAYLAND_SOCKET'] = str(client.fileno())
- if scenario == 'disconnected':
- server.close()
- start = time.monotonic()
- subprocess.run([binary, '--startup-failure'], env=env,
- pass_fds=(client.fileno(),), check=True, timeout=15)
- elapsed = time.monotonic() - start
- client.close()
- server.close()
- if scenario == 'unresponsive':
- assert 4 <= elapsed < 12, elapsed
- print(f'{scenario}: PASS ({elapsed:.2f}s)')
diff --git a/src/linux/tests/wayland_fixture.py b/src/linux/tests/wayland_fixture.py
deleted file mode 100644
index efab365..0000000
--- a/src/linux/tests/wayland_fixture.py
+++ /dev/null
@@ -1,299 +0,0 @@
-#!/usr/bin/env python3
-"""Minimal isolated Wayland peer for protocol tests, driven by the pinned XML.
-
-This never attaches to the real compositor or injects input into other clients.
-It deliberately sends delayed IME batches, selection pipes and copy-only drops.
-"""
-import array
-import ctypes
-import ctypes.util
-import fcntl
-import os
-from pathlib import Path
-import select
-import socket
-import struct
-import subprocess
-import sys
-import tempfile
-import time
-import xml.etree.ElementTree as ET
-
-XML = Path(__file__).resolve().parents[1] / 'protocols/xml'
-INTERFACES = {}
-for filename in XML.glob('*.xml'):
- for interface in ET.parse(filename).getroot().findall('interface'):
- INTERFACES[interface.get('name')] = interface
-
-
-def keymap():
- lib = ctypes.CDLL(ctypes.util.find_library('xkbcommon') or 'libxkbcommon.so.0')
- lib.xkb_context_new.restype = ctypes.c_void_p
- lib.xkb_keymap_new_from_names.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
- lib.xkb_keymap_new_from_names.restype = ctypes.c_void_p
- lib.xkb_keymap_get_as_string.argtypes = [ctypes.c_void_p, ctypes.c_int]
- lib.xkb_keymap_get_as_string.restype = ctypes.c_void_p
- lib.xkb_context_unref.argtypes = [ctypes.c_void_p]
- lib.xkb_keymap_unref.argtypes = [ctypes.c_void_p]
- names = (ctypes.c_char_p * 5)(None, None, b'us', b'intl', None)
- context = lib.xkb_context_new(0)
- mapping = lib.xkb_keymap_new_from_names(context, names, 0)
- assert mapping
- pointer = lib.xkb_keymap_get_as_string(mapping, 1)
- result = ctypes.string_at(pointer) + b'\0'
- libc = ctypes.CDLL(None)
- libc.free.argtypes = [ctypes.c_void_p]
- libc.free(pointer)
- lib.xkb_keymap_unref(mapping)
- lib.xkb_context_unref(context)
- return result
-
-
-class Compositor:
- globals = [('wl_compositor', 6), ('xdg_wm_base', 6),
- ('zxdg_decoration_manager_v1', 1), ('wl_seat', 8),
- ('wp_cursor_shape_manager_v1', 1), ('zwp_text_input_manager_v3', 1),
- ('wl_data_device_manager', 3), ('zxdg_exporter_v2', 1),
- ('xdg_activation_v1', 1)]
-
- def __init__(self, sock, inject=False):
- self.sock = sock
- self.inject = inject
- self.buffer = b''
- self.fds = []
- self.objects = {1: 'wl_display'}
- self.ids = {}
- self.server_id = 0xfeffffff
- self.surfaces = {}
- self.serial = 100
- self.text_serial = 0
- self.surrounding = ''
- self.injected = False
- self.later = None
- self.tokens = False
- self.finished_drop = False
- self.outgoing = None
- self.receives = 0
- self.held = []
-
- def event(self, obj, name, *values):
- interface = INTERFACES[self.objects[obj]]
- events = interface.findall('event')
- description = next(e for e in events if e.get('name') == name)
- body, fds = b'', []
- for arg, value in zip(description.findall('arg'), values, strict=True):
- kind = arg.get('type')
- if kind in ('uint', 'object', 'new_id'):
- body += struct.pack('=I', value or 0)
- elif kind in ('int', 'fixed'):
- body += struct.pack('=i', value)
- elif kind in ('string', 'array'):
- data = (value.encode() + b'\0') if kind == 'string' and value is not None else (value or b'')
- body += struct.pack('=I', len(data)) + data + b'\0' * (-len(data) % 4)
- elif kind == 'fd':
- fds.append(value)
- else:
- raise AssertionError(kind)
- wire = struct.pack('=II', obj, ((len(body) + 8) << 16) | events.index(description)) + body
- self.sock.sendmsg([wire], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array('i', fds))] if fds else [])
-
- def new_offer(self, mime):
- self.server_id += 1
- obj = self.server_id
- self.objects[obj] = 'wl_data_offer'
- self.event(self.ids['wl_data_device'], 'data_offer', obj)
- self.event(obj, 'offer', mime)
- return obj
-
- def dispatch(self):
- try:
- data, ancillary, _, _ = self.sock.recvmsg(65536, socket.CMSG_SPACE(64 * 4))
- except ConnectionResetError:
- return False
- if not data:
- return False
- self.buffer += data
- for level, kind, payload in ancillary:
- if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
- values = array.array('i'); values.frombytes(payload[:len(payload) // 4 * 4]); self.fds.extend(values)
- while len(self.buffer) >= 8:
- obj, header = struct.unpack_from('=II', self.buffer)
- length, opcode = header >> 16, header & 65535
- if len(self.buffer) < length:
- break
- payload, self.buffer = self.buffer[8:length], self.buffer[length:]
- iface = self.objects[obj]
- request = INTERFACES[iface].findall('request')[opcode]
- args, offset = [], 0
- for arg in request.findall('arg'):
- kind = arg.get('type')
- if kind == 'new_id' and arg.get('interface') is None:
- size = struct.unpack_from('=I', payload, offset)[0]; offset += 4
- dynamic = payload[offset:offset + size - 1].decode(); offset += (size + 3) & ~3
- version, value = struct.unpack_from('=II', payload, offset); offset += 8
- self.objects[value] = dynamic; self.ids[dynamic] = value
- args.extend([dynamic, version, value])
- continue
- if kind == 'fd':
- value = self.fds.pop(0)
- elif kind in ('string', 'array'):
- size = struct.unpack_from('=I', payload, offset)[0]; offset += 4
- value = payload[offset:offset + size]; offset += (size + 3) & ~3
- if kind == 'string': value = value[:-1].decode() if size else None
- else:
- value = struct.unpack_from('=i' if kind in ('int', 'fixed') else '=I', payload, offset)[0]; offset += 4
- if kind == 'new_id':
- self.objects[value] = arg.get('interface'); self.ids[arg.get('interface')] = value
- args.append(value)
- self.request(obj, iface, request.get('name'), args)
- if request.get('type') == 'destructor':
- if obj < 0xff000000:
- self.event(1, 'delete_id', obj)
- del self.objects[obj]
- return True
-
- def request(self, obj, iface, name, args):
- if iface == 'wl_display' and name == 'get_registry':
- for index, (interface, version) in enumerate(self.globals, 1): self.event(args[0], 'global', index, interface, version)
- elif iface == 'wl_display' and name == 'sync':
- self.event(args[0], 'done', self.serial)
- self.event(1, 'delete_id', args[0]); del self.objects[args[0]]
- elif iface == 'wl_registry' and name == 'bind' and args[1] == 'wl_seat':
- self.event(args[-1], 'capabilities', 3); self.event(args[-1], 'name', 'fixture')
- elif iface == 'wl_seat' and name == 'get_keyboard':
- contents = keymap(); fd = os.memfd_create('uhdk-test-keymap'); os.write(fd, contents)
- self.event(args[0], 'keymap', 1, fd, len(contents)); os.close(fd)
- self.event(args[0], 'repeat_info', 40, 20)
- elif iface == 'xdg_wm_base' and name == 'get_xdg_surface':
- self.surfaces[args[1]] = args[0]
- elif iface == 'wl_surface' and name == 'commit' and obj in self.surfaces:
- self.serial += 1; self.event(self.surfaces[obj], 'configure', self.serial)
- elif iface == 'zxdg_decoration_manager_v1' and name == 'get_toplevel_decoration':
- self.event(args[0], 'configure', 2)
- elif iface == 'zwp_text_input_v3' and name == 'set_surrounding_text':
- self.surrounding = args[0]
- elif iface == 'zwp_text_input_v3' and name == 'commit':
- self.text_serial += 1
- if self.inject and not self.injected and self.surrounding == 'abc': self.start_input(obj)
- elif iface == 'wl_data_offer' and name == 'receive':
- mime, fd = args
- assert not fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_NONBLOCK
- if mime == 'text/uri-list':
- payload = b'file:///tmp/drop%20file\r\n'
- else:
- self.receives += 1
- if self.receives == 3:
- self.held.append(fd)
- return
- payload = b'\xff' if self.receives == 4 else b'' if self.receives == 5 else 'hello café'.encode()
- os.write(fd, payload)
- os.close(fd)
- elif iface == 'wl_data_offer' and name == 'finish':
- self.finished_drop = True
- elif iface == 'wl_data_device' and name == 'set_selection':
- source = args[0]
- closed_read, closed_write = os.pipe()
- os.close(closed_read)
- self.event(source, 'send', 'text/plain;charset=utf-8', closed_write)
- os.close(closed_write)
- read, write = os.pipe()
- self.event(source, 'send', 'text/plain;charset=utf-8', write)
- os.close(write); self.outgoing = read
- elif iface == 'xdg_activation_token_v1' and name == 'commit':
- self.event(obj, 'done', 'fixture-token')
- elif iface == 'xdg_activation_v1' and name == 'activate':
- assert args[0] == 'fixture-token'; self.tokens = True
- elif iface == 'zxdg_exporter_v2' and name == 'export_toplevel':
- self.event(args[0], 'handle', 'fixture-parent')
-
- def start_input(self, text_input):
- self.injected = True
- surface = next(iter(self.surfaces))
- keyboard, pointer = self.ids['wl_keyboard'], self.ids['wl_pointer']
- self.event(keyboard, 'enter', 200, surface, b'')
- self.event(keyboard, 'modifiers', 200, 0, 0, 0, 0)
- self.event(keyboard, 'key', 201, 1, 30, 1)
- self.event(keyboard, 'key', 202, 2, 30, 0)
- self.event(keyboard, 'key', 203, 3, 48, 1)
- self.event(pointer, 'enter', 204, surface, 10 * 256, 10 * 256)
- self.event(pointer, 'motion', 4, 12 * 256, 18 * 256)
- self.event(pointer, 'button', 204, 4, 0x110, 1)
- self.event(pointer, 'axis_source', 0)
- self.event(pointer, 'axis', 5, 0, 5 * 256)
- self.event(pointer, 'axis_value120', 0, 60)
- self.event(pointer, 'frame')
- selection = self.new_offer('text/plain;charset=utf-8')
- self.event(self.ids['wl_data_device'], 'selection', selection)
- drop = self.new_offer('text/uri-list')
- self.event(drop, 'source_actions', 1)
- self.event(self.ids['wl_data_device'], 'enter', 205, surface, 12 * 256, 18 * 256, drop)
- self.event(drop, 'action', 1)
- self.event(self.ids['wl_data_device'], 'drop')
- self.later = (time.monotonic() + .15, text_input, self.text_serial)
-
- def timers(self):
- # Text input enter precedes the application's first surrounding snapshot.
- text = self.ids.get('zwp_text_input_v3')
- if text and self.surfaces and not getattr(self, 'text_entered', False):
- self.text_entered = True
- surface = next(iter(self.surfaces))
- self.event(text, 'enter', surface)
- if not self.inject:
- keyboard = self.ids['wl_keyboard']
- self.event(keyboard, 'enter', 190, surface, b'')
- self.event(keyboard, 'key', 191, 1, 30, 1)
- self.event(keyboard, 'key', 192, 2, 30, 0)
- if self.later and time.monotonic() >= self.later[0]:
- _, text, serial = self.later; self.later = None
- assert self.text_serial > serial, (self.text_serial, serial)
- self.event(self.ids['wl_pointer'], 'button', 206, 6, 0x110, 0)
- keyboard = self.ids['wl_keyboard']
- self.event(keyboard, 'key', 206, 6, 48, 0)
- self.event(keyboard, 'key', 207, 7, 29, 1)
- self.event(keyboard, 'modifiers', 207, 4, 0, 0, 0)
- self.event(keyboard, 'key', 208, 7, 46, 1)
- self.event(keyboard, 'key', 209, 8, 46, 0)
- self.event(keyboard, 'key', 210, 9, 29, 0)
- self.event(keyboard, 'modifiers', 210, 0, 0, 0, 0)
- self.event(keyboard, 'modifiers', 210, 0, 1, 0, 0)
- self.event(keyboard, 'key', 210, 9, 30, 1)
- self.event(keyboard, 'modifiers', 210, 0, 0, 0, 0)
- self.event(keyboard, 'key', 210, 9, 30, 0)
- self.event(keyboard, 'key', 211, 9, 40, 1)
- self.event(keyboard, 'key', 212, 10, 40, 0)
- self.event(keyboard, 'key', 213, 11, 18, 1)
- self.event(keyboard, 'key', 214, 12, 18, 0)
- self.event(text, 'preedit_string', 'é', 0, 2)
- self.event(text, 'done', serial)
- self.event(text, 'preedit_string', '', 0, 0)
- self.event(text, 'delete_surrounding_text', 1, 1)
- self.event(text, 'commit_string', 'λ')
- self.event(text, 'done', serial)
-
-
-def run(binary, mode, env=None, compositor_type=Compositor):
- client, server = socket.socketpair()
- environment = dict(os.environ if env is None else env, WAYLAND_SOCKET=str(client.fileno()))
- if mode == 'input': environment.pop('DBUS_SESSION_BUS_ADDRESS', None)
- process = subprocess.Popen([str(Path(binary).resolve()), mode], env=environment, pass_fds=(client.fileno(),))
- client.close()
- compositor = compositor_type(server, mode == 'input')
- end = time.monotonic() + 20
- try:
- while process.poll() is None and time.monotonic() < end:
- if select.select([server], [], [], .01)[0] and not compositor.dispatch(): break
- compositor.timers()
- assert process.wait(timeout=2) == 0, process.returncode
- if mode == 'input':
- assert compositor.finished_drop and compositor.tokens
- assert compositor.outgoing is not None
- assert os.read(compositor.outgoing, 1024) == b'local copy'
- finally:
- if process.poll() is None: process.kill(); process.wait()
- server.close()
- for fd in compositor.fds + compositor.held: os.close(fd)
- if compositor.outgoing is not None: os.close(compositor.outgoing)
-
-
-if __name__ == '__main__':
- run(sys.argv[1], 'input')
diff --git a/src/linux/tests/window_state_fixture.py b/src/linux/tests/window_state_fixture.py
deleted file mode 100644
index 4463f76..0000000
--- a/src/linux/tests/window_state_fixture.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python3
-"""Exercise xdg-shell versioned observations and capability changes in isolation."""
-import struct
-import sys
-from wayland_fixture import Compositor, run
-
-
-class WindowStateCompositor(Compositor):
- version = 6
-
- def __init__(self, sock, inject=False):
- super().__init__(sock, inject)
- self.top = None
- self.states = []
- self.caps = [2] # Maximize only; minimize/fullscreen must be rejected.
- self.minimized = False
-
- def configure(self):
- self.event(self.top, 'wm_capabilities', struct.pack('=' + 'I' * len(self.caps), *self.caps))
- self.event(self.top, 'configure', 320, 240, struct.pack('=' + 'I' * len(self.states), *self.states))
- self.serial += 1
- self.event(next(iter(self.surfaces.values())), 'configure', self.serial)
-
- def request(self, obj, iface, name, args):
- if iface == 'xdg_surface' and name == 'get_toplevel':
- self.top = args[0]
- elif iface == 'wl_surface' and name == 'commit' and obj in self.surfaces:
- self.configure()
- return
- elif iface == 'xdg_toplevel' and name == 'set_title':
- if args[0] == 'fixture:suspend':
- self.states = [2, 3, 4] + ([9] if self.version >= 6 else [])
- self.configure()
- elif args[0] == 'fixture:resume':
- self.states = []
- self.caps = [2, 3, 4]
- self.configure()
- elif iface == 'xdg_toplevel' and name == 'set_minimized':
- assert 4 in self.caps, 'client sent an unavailable minimize request'
- self.minimized = True
- elif iface == 'xdg_toplevel' and name == 'destroy':
- assert self.minimized, 'accepted minimize request was not submitted'
- elif iface == 'xdg_toplevel' and name == 'set_fullscreen':
- assert 3 in self.caps, 'client sent an unavailable fullscreen request'
- super().request(obj, iface, name, args)
-
-
-if __name__ == '__main__':
- for version in (5, 6):
- class Versioned(WindowStateCompositor):
- globals = [(name, version if name == 'xdg_wm_base' else v)
- for name, v in Compositor.globals]
- Versioned.version = version
- run(sys.argv[1], 'window-state-v' + str(version), compositor_type=Versioned)