Compare commits

..

36 Commits

Author SHA1 Message Date
Peter Li da1f67d347 fixes for linux and macos 2026-10-11 16:14:38 -07:00
Peterino2 8c99ac7912 fix to linux xdg token 2026-10-11 12:34:43 -07:00
Peter Li 29fd33965f saving 2026-10-05 12:50:25 -07:00
Peter Li 22dc0fb3eb zig build upgrade to 0.17 and removed a lot of ai generated tests 2026-10-05 12:17:18 -07:00
Peter Li d86f81ce2c uha 0.17 upgrade 2026-10-05 11:21:15 -07:00
Peterino2 883b1b7961 updated wayland scanner headers 2026-10-04 23:30:18 +00:00
Peter Li 21171592fd fixes for macos, submitting to linux machine for regenerating protocols 2026-10-04 16:14:22 -07:00
Peter Li 8dabc0ffb9 updating uhdk to 0.17.0 2026-10-04 15:41:02 -07:00
Peter Li 019d08cbfc massively removed a lot of dead code 2026-09-28 11:36:24 -07:00
Peter Li 0231794f5b saving 2026-09-27 18:17:43 -07:00
Peter Li 3851a6e0b0 macos argv 2026-09-27 17:43:27 -07:00
Peterino2 c8180456f0 adding pointer containment and cursor styles 2026-09-27 14:14:00 -07:00
Peterino2 2278d9829a UHA initial work added, also adding tray icons 2026-09-26 12:26:45 -07:00
Peterino2 177c4429a7 saving 2026-09-25 20:18:14 -07:00
Peterino2 7cc2a5302b changed some wording, then added build-docs.sh 2026-09-23 21:25:20 -07:00
Peterino2 29d6109bdf uhdk c# documentation 2026-09-23 01:49:36 +00:00
Peterino2 9fa0a88e43 saving 2026-09-22 12:27:51 -07:00
Peterino2 ce76333d32 saving 2026-09-21 19:33:44 +00:00
Peterino2 b55bcb3050 more aggressive formatting changes 2026-09-21 09:58:51 -07:00
Peterino2 fec5dc297a styling changes 2026-09-21 09:55:27 -07:00
Peterino2 4c3decfa7f far smaller zig skills 2026-09-21 09:44:28 -07:00
Peterino2 ddb1aac088 api updates and new validators, fixing up some naming inconsistencies in linux 2026-09-21 09:07:31 -07:00
Peterino2 51ca8bd438 header and documentation updeates 2026-09-20 23:30:23 -07:00
Peterino2 fcf4c7ec4c headers spacing 2026-09-20 02:00:59 -07:00
Peterino2 7353322a74 massive overhauls to documentation 2026-09-20 01:58:19 -07:00
Peterino2 c4dc26d3f3 generation 2026-09-20 00:41:29 -07:00
Peterino2 4c7c96a8a9 documentation update 2026-09-19 15:34:37 -07:00
Peterino2 d24b46f883 tagged lifetime requests 2026-09-19 15:29:04 -07:00
Peterino2 091fcee4ed fixes after big api changes 2026-09-19 13:55:05 -07:00
Peterino2 2e2a810615 removed dead loaders and bringing back in glad 2026-09-19 13:43:11 -07:00
Peterino2 22a462481a big overhual to lifecycle and opting for significant simplification of api 2026-09-19 13:09:20 -07:00
Peterino2 f6686e66ec big api overhaul, moved unsupported bindings to archive 2026-09-19 12:22:23 -07:00
Peterino2 97bb36827f added strata demo, C Sharp bindings, and bitmap font generator 2026-09-19 09:35:04 -07:00
Peter Li 6d9a0acf9a Merge app startup and shutdown into create and destroy 2026-09-18 21:10:34 -07:00
Peter Li 894e3dee59 Support caller-owned application threads and asynchronous file execution 2026-09-18 19:58:34 -07:00
Peter Li 858bf52a09 some cleanup 2026-09-18 18:39:21 -07:00
100 changed files with 8331 additions and 4353 deletions

268
README.md
View File

@ -1,13 +1,20 @@
# Uhdk
A small desktop platform library written in Zig 0.16.0 with a C99 ABI.
It provides windows, input and IME, clipboard, file dialogs, drag and drop, menus,
A small desktop platform library written in Zig 0.17.0 with a C99 ABI.
It provides windows, input and IME, clipboard, file dialogs, incoming file drops, menus, tray icons,
async file operations, file watching, and OpenGL context creation. The macOS
backend uses AppKit, OpenGL, and FSEvents through a private Objective-C bridge.
File dialog filters accept suffixes without a leading dot, including compound
suffixes such as `level.json`.
Internal naming: `z_` means **Zig bridge**, identifying private bridge functions,
types, and helpers connecting the Zig runtime with native platform code. Public
C API symbols use `uhdk_`.
macOS builds require Xcode Command Line Tools. The Windows Win32/WGL backend
cross-compiles for `x86_64-windows-gnu`; runtime verification on Windows is pending. It requires
Windows 10 version 1703 or later and an OpenGL 3.3-capable driver.
targets `x86_64-windows-gnu`. Demo applications have been tested under Wine and
on a Windows 11 host with no issues observed so far. The backend requires
Windows 10 version 1703 or later and an OpenGL 3.3-capable driver for GL sessions.
The Linux Wayland preview implements windows, EGL/OpenGL, keyboard/pointer and
text input, clipboard/file drops, portal dialogs/preferences, activation, icons,
@ -18,6 +25,52 @@ ABI headers/protocol bindings and runtime-loaded system libraries. Normal
builds need Zig alone; the optional `shell.nix` supplies maintainer tools and
NixOS runtime library paths. See [Linux support and limitations](src/linux/README.md).
Window decoration and resizing are selected through `uhdk_window_style` when a
window is created and can be changed later with `uhdk_window_set_style`.
Set `decorated` to false for application-drawn chrome; on Wayland this requests
client-side decoration instead of the compositor's usual title bar and border.
The primary application path is `uhdk_open` followed by one
`uhdk_next_frame`/`uhdk_end_frame` loop. It creates a visible window and current
OpenGL context before returning, reports events and framebuffer metrics together,
and handles presentation at the frame boundary. All services accept that same
session handle. Additional native windows can be created synchronously between
iterations for external rendering; they do not have independent UHDK GL contexts.
On macOS, UHDK disables AppKit's conversion of command-line arguments into
`UHDK_EVENT_OPEN_FILES` by default. Applications handle their own arguments;
document-open requests from Finder and the Dock still arrive as events.
## Tray icons
Create a session-owned `uhdk_tray` with `uhdk_tray_create`, replace its complete
description with `uhdk_tray_update`, and remove it with `uhdk_tray_destroy`.
Create/update belong between frames. The descriptor copies UTF-8 text and a
1–512 pixel RGBA8 image, and retains its optional `uhdk_menu`. Keep its nonempty
`id` stable across updates and unique within the session. Set `hidden` to remove
it temporarily, `menu_on_primary` to open its menu on primary activation, or
`template_image` for a macOS template icon. Other backends ignore that hint.
`UHDK_EVENT_TRAY_ACTIVATE` carries the tray and primary/secondary action.
Menu commands carry their origin in `uhdk_menu_event.tray`, with a NULL window;
ordinary window menu commands have a NULL tray. Tray menus support ordinary
commands, submenus, separators, enabled/checked flags and the QUIT role. Other
window-dependent roles are rejected. Menu shortcuts are not global shortcuts.
Query `uhdk_tray_get_state` and handle `UHDK_EVENT_TRAY_STATE`. `available` means
registered with the host, not guaranteed onscreen: the desktop may hide icons.
`UHDK_CAP_TRAY` reports mechanism/host availability. On Linux, discovery is
asynchronous; creation can succeed before a StatusNotifier host exists, then
register automatically when one appears. Keep processing frames while windows
are hidden. The session still opens with a visible primary window, which the
application may hide once it has an available tray item.
Backends use AppKit `NSStatusItem`, Win32 `Shell_NotifyIconW` (including Explorer
restart recovery), and Linux StatusNotifierItem plus D-BusMenu. Linux needs a
session bus and a compatible tray host; no GTK or Qt dependency is added.
Session close removes all items. Destroy invalidates the handle immediately and
suppresses queued tray events; native removal occurs at the next frame or close.
## Experimental desktop input and window observations
macOS uses AppKit editing selectors. Windows and Wayland share Ctrl-based defaults
@ -51,9 +104,9 @@ state or directly undo minimization, and suspension is not proof of occlusion.
Explicitly unavailable Wayland window-manager actions complete with `UNSUPPORTED`.
Render hints do not replace presentation pacing or event processing.
This library is unreleased and experimental; the changed C struct layout requires
rebuilding consumers, without ABI compatibility guarantees. Windows and Linux
runtime qualification must accompany cross-compilation checks.
UHDK is experimental and does not guarantee API or ABI compatibility between
revisions. Rebuild consumers when updating the library and headers. Demo testing
does not qualify every IME, window manager, display configuration or driver.
## Build
@ -94,6 +147,8 @@ must arrange its runtime location/rpath.
## C interface
- Guide and API reference: the full repository generates them from `uhdk.h`
with `zig build docs-uhdk` (into `build/docs/uhdk/`).
- [uhdk.h](include/uhdk.h): desktop API, lifecycle, ownership, and threading contracts.
- [OPENGL-SOURCES.md](include/OPENGL-SOURCES.md): GLAD generation recipe and Khronos header provenance and licenses.
@ -109,19 +164,17 @@ native-window handle API:
```
Presence enables each flag; leave it undefined to disable it. These flags select
header declarations, not library backends. UHDK's own context-management API is
always declared. The supplied Zig module enables both sections. The vendored GL
header declarations, not library backends. The session API is always declared. The supplied Zig module enables both sections. The vendored GL
headers remain unmodified dependencies rather than being pasted into `uhdk.h`.
The public interface uses pointer-and-length text, `char` booleans, and `float`
coordinates. The native bridge is private; consumers do not need Objective-C.
The library includes the GLAD loader implementation. With a current context inside
`uhdk_gl_context_begin_frame` / `uhdk_gl_context_end_frame`, call
`gladLoadGLContextUserPtr` with a callback that resolves names using
`uhdk_gl_context_get_proc`. Keep a `GladGLContext` per native context; its members
are named `Clear`, `DrawArrays`, etc. Check `VERSION_3_3` after loading. Do not define
`GLAD_GL_IMPLEMENTATION` in your application when linking libuhdk.
UHDK loads and owns the GL function table returned by `uhdk_get_gl` and
`frame.gl`. Its members are named `Clear`, `DrawArrays`, etc. Use
`uhdk_get_gl_proc(session, name, &proc)` for extension procedures and
`uhdk_set_vsync(session, enabled)` to change presentation policy. No application
loader implementation or current-context management is needed.
On Windows, the static artifact is `zig-out/lib/uhdk.lib`; shared builds install
`zig-out/bin/uhdk.dll` and its import library under `zig-out/lib/`. Keep the DLL
@ -132,6 +185,99 @@ are not implemented. Native UTF-16 path bytes are kept separately from the WTF-8
paths passed to Zig I/O. If a native path cannot be exported losslessly as a shell
URI, URI export returns `UNSUPPORTED`; native-path export still preserves it.
## Session loop
`uhdk_open` is the default setup path. Pass NULL for defaults, or zero-initialize
`uhdk_options`, set `struct_size`, and override the options you need. Successful
setup returns a visible window, a current OpenGL 3.3-or-newer core context, and a
loaded GL function table. Setup failures unwind all resources.
```c
#define UHDK_ENABLE_OPENGL
#include "uhdk.h"
int main(void) {
uhdk_options options = {0};
options.struct_size = sizeof(options);
options.title = (uhdk_text){"Hello UHDK", 10};
options.content_size = (uhdk_size){800, 600};
uhdk_session *session = 0;
if (uhdk_open(&options, &session) != UHDK_STATUS_OK)
return 1;
/* Create shaders, textures, etc. using uhdk_get_gl(session) here. */
uhdk_frame frame;
uhdk_status status = UHDK_STATUS_OK;
while (uhdk_next_frame(session, &frame)) {
for (uint64_t i = 0; i < frame.events.len; ++i) {
uint32_t type = frame.events.ptr[i].type;
if (type == UHDK_EVENT_WINDOW_CLOSE_REQUESTED ||
type == UHDK_EVENT_QUIT_REQUESTED)
uhdk_quit(session);
}
if (frame.drawable) {
frame.gl->Viewport(0, 0, frame.metrics.framebuffer_width,
frame.metrics.framebuffer_height);
frame.gl->ClearColor(0.1f, 0.15f, 0.2f, 1.0f);
frame.gl->Clear(GL_COLOR_BUFFER_BIT);
}
status = uhdk_end_frame(session);
if (status != UHDK_STATUS_OK)
break;
}
if (status == UHDK_STATUS_OK)
status = uhdk_get_status(session);
/* Delete application GL resources here, while the context is current. */
uhdk_close(session);
return status == UHDK_STATUS_OK ? 0 : 1;
}
```
All session/application/GL work stays on OS main. `next_frame` releases native GL
locks, pumps native work and worker completions, then restores the current context.
`end_frame` presents drawable iterations. Every successful `next_frame` needs an
`end_frame`, including event-only iterations. `close` can discard an unfinished
iteration without presenting it. The primary window belongs to the session and must not be destroyed separately.
Continuous mode is the default and requests vsync. `UHDK_RENDER_ON_DEMAND` waits
for events or wake deadlines after the first iteration. Repaint the complete
framebuffer whenever `drawable` is true. Hidden/minimized windows still receive
events, and `uhdk_wake` or a wake deadline can schedule application work.
The first iteration never waits. Session GL calls are valid before, during and
after iterations until close; drawing to the window is conditional on `drawable`.
A fatal native/driver error may prevent further GL work, including cleanup.
On macOS, vsync waits for a per-window CoreVideo display link before presenting,
with the native OpenGL swap interval disabled. The link follows the window's
display. Present waits only while no refresh has passed since the previous present,
so a frame the driver already held until a refresh is not delayed by another. Each
wait is bounded to 100 ms so a sleeping display cannot indefinitely block the frame
loop; disabling vsync bypasses the wait.
Accept close/quit requests with `uhdk_quit`. Keep iterating to drain request
completions and `STOPPED`; then `next_frame` returns false and `get_status` returns
OK. Failures also end the loop, with a non-OK status. An early `close` abandons
undelivered results and drains internal teardown. File workers stay independent,
although their results reach the application at frame boundaries. Long main-thread
updates delay native event handling.
## Native-only sessions and additional windows
Set `uhdk_options.no_opengl` for an external renderer or native-only integration.
The event/frame lifecycle stays the same; `get_gl` and `frame.gl` return NULL,
`end_frame` does not present, and procedure lookup/vsync return UNSUPPORTED.
`uhdk_window_create` synchronously creates an additional hidden native window.
Call it between iterations; a call during a frame returns BUSY. Creation may pump
native work but preserves the current borrowed batch. No additional GL context is
created. Use native handles to attach an external renderer. The session's primary
window belongs to `close`; `uhdk_window_destroy` rejects attempts to destroy it.
File reads/writes/info and watch preparation execute serially on an internal I/O
worker. Up to 64 such requests can be outstanding; further submissions return
BUSY without accepting an ID. Cancellation is best effort; final close may wait
for an active filesystem call. Native dispatch delivers results at frame boundaries.
## Borrowed event payloads
Events and request results carry `const void *data` plus `data_size` instead of
@ -150,16 +296,14 @@ if (event->type == UHDK_EVENT_KEY &&
```
One library-owned scratch arena holds the returned batch, its payload structs,
and nested spans. The next valid application-thread poll resets it, even if that
poll is empty or returns an error. Invalid arguments and wrong-thread calls do
not reset it. App destruction also invalidates everything. Rendering does not
and nested spans. The next valid next_frame call resets it, even if it returns an empty batch
or an error. Invalid arguments and wrong-thread calls do
not reset it. Session close also invalidates everything. Rendering does not
advance this lifetime. Copy data you need to keep; copying an envelope alone
copies only its pointers. Retain file/menu references when needed beyond a poll,
copies only its pointers. Retain file/menu references when needed beyond an iteration,
but even retained handles cannot outlive the app.
UHDK is pre-release: API and ABI compatibility with earlier revisions is not
guaranteed. Set creation descriptors to `UHDK_ABI_VERSION`. Event envelopes have
a fixed array stride within each returned batch.
Event envelopes have a fixed array stride within each returned batch.
The scratch arena is maintained as UHDK-owned code in
[src/arenas.zig](src/arenas.zig), including its supporting storage and tests.
@ -188,3 +332,83 @@ On-demand capture omits allocations made before connection, so it is not a full
live-heap snapshot. Failed allocations emit nothing; in-place resizes emit
free + alloc. Moving reallocations use alloc/copy/free to preserve event ordering.
Disabled builds use the original allocator directly.
### Caller-chosen async request tags
Every async operation takes a nonzero `uhdk_request_tag` chosen by the caller.
Completions return it as `uhdk_request_result.tag`; cancellation takes the same tag.
Tags are unique among requests whose completion has not yet been delivered,
including completed requests queued for the next frame. Repeated tags return
`BUSY`. Reuse a tag while handling its completion, or choose distinct tags for
concurrent operations. Failure to start reserves nothing and produces no event.
```c
enum { ReadModel = 1, ReadTexture = 2 };
uhdk_status status = uhdk_file_read_all_async(file, 128 * 1024 * 1024, ReadModel);
/* Later, in REQUEST_DONE handling: switch (result->tag) { ... } */
```
Components sharing a session must coordinate tags; pass a dedicated tag to each
component that starts asynchronous work.
### Function-key policy
Use `uhdk_window_set_function_key_policy(window, UHDK_FUNCTION_KEYS_APPLICATION)`
to suppress Windows native defaults for unmodified F1–F24, including F10 menu
activation. Key events still reach the application. `UHDK_FUNCTION_KEYS_NATIVE`
restores the default behavior. Set the policy before the relevant press; it is
applied at the next frame boundary, and a held key retains the handling selected
at its initial press through repeats and release.
Shift/Control/Alt/Super combinations, including Alt+F4, keep native handling.
Registered UHDK menu shortcuts retain priority over raw key events. This policy
is accepted on macOS and Wayland without an effect; it does not override global
shortcuts, IME interception, or keyboard media-key settings.
### Cursor confinement
Windows and Wayland compositors with pointer-constraints-v1 support keeping the
cursor inside the window's content area. macOS currently reports this capability
as unavailable. Request confinement while the window is visible and focused and
the pointer is inside:
```c
if (uhdk_has_capability(session, UHDK_CAP_POINTER_CONFINEMENT)) {
uhdk_status status = uhdk_window_set_pointer_mode(window, UHDK_POINTER_CONFINED);
/* Handle submission failure. POINTER_MODE_CHANGED confirms activation. */
(void)status;
}
```
Set `UHDK_POINTER_NORMAL` to release active confinement or cancel a pending
request. Confinement follows the content area as the window moves/resizes and
preserves cursor shape and absolute pointer motion. Wayland activation depends
on compositor policy and may never occur. Focus loss, hiding/minimizing, or native
cancellation restores normal mode without automatic reactivation. Destruction
and session close also release it. Capture and confinement are mutually exclusive.
### Errors and input lifecycles
`uhdk_status_message(status)` returns a static UTF-8 text span, usable without a
session and from any thread. It does not allocate or maintain a last-error slot.
Failed async results always contain a nonempty `diagnostic`: native detail when
available, otherwise the status message. Use status codes for decisions and text
for display; successful requests may have an empty diagnostic.
`uhdk_event.cycle_id` associates events within a pointer drag/capture/confinement,
phased scroll gesture, or IME preedit composition. These library-generated IDs are
unique per session and separate from caller request tags and native edit
`input_id` values.
Hover, discrete wheel events, ordinary typing and unrelated events use zero.
Track the ID from the first relevant event; ignore updates from other cycles.
`UHDK_EVENT_CYCLE_END` carries the ID, window, and a `uhdk_cycle_end_event` payload.
Its `reason` distinguishes completion, cancellation, capture/confinement release
or loss, focus loss, hiding, replacement and shutdown. It reports the first observed ending
cause and retires the interaction, without deciding whether
the application should commit or undo its work. Destruction invalidates cycles
immediately; fatal errors or early close may prevent delivery of queued endings.
The C API exposes spans and plain event payloads. `UHDK_EVENT_PAYLOAD` checks an
event's type and payload size before returning a typed pointer; languages that
cannot use C macros perform those checks explicitly.

View File

@ -2,12 +2,15 @@ const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
if (target.result.os.tag != .macos and target.result.os.tag != .windows and target.result.os.tag != .linux) @panic("Uhdk supports macOS, Windows and Linux.");
const optimize = b.standardOptimizeOption(.{});
const use_llvm = b.option(bool, "use_llvm", "Use LLVM for Zig compilation") orelse null;
const shared = b.option(bool, "shared", "Build libuhdk as a shared library instead of static") orelse false;
const tracy = b.option(bool, "tracy", "Emit Tracy 0.14.1 on-demand hooks; consumer must link the client") orelse false;
if (tracy and shared) @panic("Tracy instrumentation requires static linking");
const lib = createLibraryNamed(b, target, optimize, shared, tracy, "uhdk");
const lib = createLibraryNamed(b, target, optimize, use_llvm, shared, tracy, "uhdk");
const module = lib.root_module;
const install_lib = b.addInstallArtifact(lib, .{});
const install_headers = b.addInstallDirectory(.{
@ -15,18 +18,22 @@ pub fn build(b: *std.Build) void {
.install_dir = .header,
.install_subdir = "",
});
const lib_step = b.step("lib", "Build and install the Uhdk library and headers");
lib_step.dependOn(&install_lib.step);
lib_step.dependOn(&install_headers.step);
b.getInstallStep().dependOn(&install_lib.step);
b.getInstallStep().dependOn(&install_headers.step);
const unit = b.addTest(.{ .root_module = module });
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);
const public_c = b.addTranslateC(.{
.root_source_file = b.path("include/uhdk.h"),
.target = target,
@ -35,7 +42,10 @@ pub fn build(b: *std.Build) void {
public_c.defineCMacro("UHDK_ENABLE_OPENGL", "1");
public_c.defineCMacro("UHDK_ENABLE_NATIVE", "1");
public_c.addIncludePath(b.path("include"));
if (shared) public_c.defineCMacro("UHDK_SHARED", "1");
if (shared)
public_c.defineCMacro("UHDK_SHARED", "1");
const public_module = b.addModule("uhdk", .{
.root_source_file = public_c.getOutput(),
.target = target,
@ -46,29 +56,37 @@ pub fn build(b: *std.Build) void {
// Create a library artifact without installing it. Instrumented static builds
// require the consumer to link a matching Tracy client.
pub fn createLibrary(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, shared: bool, instrumented: bool) *std.Build.Step.Compile {
return createLibraryNamed(b, target, optimize, shared, instrumented, if (instrumented) "uhdk-instrumented" else "uhdk");
pub fn createLibrary(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, use_llvm: ?bool, shared: bool, instrumented: bool) *std.Build.Step.Compile {
return createLibraryNamed(b, target, optimize, use_llvm, shared, instrumented, if (instrumented) "uhdk-instrumented" else "uhdk");
}
fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, shared: bool, instrumented: bool, artifact_name: []const u8) *std.Build.Step.Compile {
fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, use_llvm: ?bool, shared: bool, instrumented: bool, artifact_name: []const u8) *std.Build.Step.Compile {
std.debug.assert(!shared or !instrumented);
const module = b.createModule(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
.unwind_tables = if (optimize == .small) .none else null,
});
const native = b.addTranslateC(.{
.root_source_file = b.path("src/native.h"),
.target = target,
.optimize = optimize,
});
native.defineCMacro("UHDK_ENABLE_OPENGL", "1");
native.addIncludePath(b.path("include"));
module.addImport("native", native.createModule());
module.addImport("profile", createProfileModule(b, target, optimize, instrumented));
module.addIncludePath(b.path("include"));
module.addIncludePath(b.path("src"));
if (instrumented) module.addCMacro("UHDK_INTERNAL_TRACY", "1");
if (instrumented)
module.addCMacro("UHDK_INTERNAL_TRACY", "1");
if (target.result.os.tag == .macos) {
module.addCSourceFile(.{
.file = b.path("src/macos/native.m"),
@ -80,24 +98,36 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
module.linkFramework("Cocoa", .{});
module.linkFramework("OpenGL", .{});
module.linkFramework("CoreServices", .{});
module.linkFramework("CoreVideo", .{});
} else if (target.result.os.tag == .linux) {
@import("src/linux/build.zig").configure(b, module, target, optimize);
} else {
module.addCSourceFile(.{ .file = b.path("src/windows/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DUNICODE", "-D_UNICODE" } });
for ([_][]const u8{ "user32", "gdi32", "opengl32", "shell32", "ole32", "uuid", "imm32", "comctl32", "shlwapi", "advapi32" }) |name| module.linkSystemLibrary(name, .{});
for ([_][]const u8{ "user32", "gdi32", "opengl32", "shell32", "ole32", "uuid", "imm32", "comctl32", "shlwapi", "advapi32", "api-ms-win-core-synch-l1-2-0" }) |name| module.linkSystemLibrary(name, .{});
}
module.addCSourceFile(.{ .file = b.path("src/glad.c"), .flags = if (shared) &.{ "-std=c99", "-DGLAD_API_CALL_EXPORT", "-DGLAD_API_CALL_EXPORT_BUILD" } else &.{"-std=c99"} });
module.addCSourceFile(.{ .file = b.path("src/gl_loader.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } });
module.addCSourceFile(.{ .file = b.path("src/platform_io.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
const lib = b.addLibrary(.{
.name = artifact_name,
.linkage = if (shared) .dynamic else .static,
.use_llvm = use_llvm,
.root_module = module,
});
if (shared and target.result.os.tag == .linux)
lib.version_script = b.path("src/linux/exports.map");
// temp
// lib.root_module.strip = false;
return lib;
}
pub fn createProfileModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, enabled: bool) *std.Build.Module {
pub fn createProfileModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, enabled: bool) *std.Build.Module {
const options = b.addOptions();
options.addOption(bool, "enabled", enabled);
const profile = b.createModule(.{
.root_source_file = b.path("src/Profile.zig"),
.target = target,

View File

@ -2,7 +2,7 @@
.name = .uhdk,
.fingerprint = 0xe0900359a69bf43d,
.version = "0.1.0",
.minimum_zig_version = "0.16.0",
.minimum_zig_version = "0.17.0",
.dependencies = .{},
.paths = .{ "build.zig", "build.zig.zon", "src", "include", "README.md", "shell.nix" },
}

View File

@ -2,11 +2,7 @@
## GLAD 2.0.8
`uhdk.h` with `UHDK_ENABLE_OPENGL` includes the generated `glad/gl.h`:
OpenGL 3.3 core, no
extensions, header-only output, explicit per-context tables (`--mx`), and no
platform loader. `src/glad.c` compiles its implementation into libuhdk. Applications
load a `GladGLContext` through their adapter for `uhdk_gl_context_get_proc`.
`uhdk.h` with `UHDK_ENABLE_OPENGL` includes the generated `glad/gl.h`, no extensions, core 3.3 api
Generated unmodified with the pinned generator and its bundled Khronos snapshot:

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,9 @@ pkgs.mkShell {
pkgs.dbus
pkgs.wayland-scanner
pkgs.clang-tools
pkgs.rustc
pkgs.cargo
pkgs.libpulseaudio
];
# NixOS does not put desktop libraries in the conventional loader search path.
# This affects running an unwrapped development executable, not compilation.
@ -16,4 +19,6 @@ pkgs.mkShell {
pkgs.libxkbcommon
pkgs.dbus.lib
];
UHA_PULSE_LIBRARY = "${pkgs.libpulseaudio}/lib/libpulse.so.0";
}

View File

@ -9,57 +9,95 @@ const Resource = @import("Resource.zig");
const arenas = @import("arenas.zig");
const Application = @This();
gpa: std.mem.Allocator,
io: std.Io,
io_backend: ?*std.Io.Threaded = null,
mutex: std.Io.Mutex = .init,
available: std.Io.Event = .unset,
in_tick: bool = false,
in_dispatch: bool = false,
next_cycle: u64 = 1,
objects: ?*Resource = null,
queue_head: ?*Request = null,
queue_tail: ?*Request = null,
requests: ?*Request = null,
io_active: ?*Request = null,
io_completed_head: ?*Request = null,
io_completed_tail: ?*Request = null,
io_pending: usize = 0,
io_worker: ?std.Thread = null,
io_available: std.Io.Event = .unset,
io_exit: bool = false,
// Test-only gate permits deterministic blocked-filesystem scheduling tests.
io_test_hook: if (@import("builtin").is_test) ?struct {
context: *anyopaque,
before: *const fn (*anyopaque) void,
} else void = if (@import("builtin").is_test) null else {},
io_head: ?*Request = null,
io_tail: ?*Request = null,
pending_head: ?*Event = null,
pending_tail: ?*Event = null,
published: ?*Event = null,
scratch: arenas.BumpArena,
name: []u8,
application_id: []const u8 = "",
epoch: u64,
deadline: u64 = 0,
next_id: u64 = 1,
running: bool = false,
has_run: bool = false,
native_started: bool = false,
native_error: abi.Status = abi.OK,
stopping: bool = false,
stopped_sent: bool = false,
stopped_seen: bool = false,
worker_done: bool = false,
event_error: abi.Status = abi.OK,
worker_id: ?std.Thread.Id = null,
entry: c.uhdk_app_main_fn = null,
user: ?*anyopaque = null,
main_thread: ?std.Thread.Id = null,
preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences),
stats: c.uhdk_app_stats = std.mem.zeroes(c.uhdk_app_stats),
tick_start: ?u64 = null,
stats: c.uhdk_stats = std.mem.zeroes(c.uhdk_stats),
last_frame_time: ?u64 = null,
session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions),
session_window: ?*c.uhdk_window = null,
session_has_gl: bool = false,
session_status: abi.Status = abi.OK,
session_active: bool = false,
session_drawable: bool = false,
session_first: bool = true,
session_on_demand: bool = false,
startup_timeout_ns: u64 = 10 * std.time.ns_per_s,
pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application {
const self = try gpa.create(Application);
errdefer gpa.destroy(self);
const owned_name = try gpa.dupe(u8, name);
errdefer gpa.free(owned_name);
const scratch = try arenas.BumpArena.init(gpa, io);
self.* = .{ .gpa = gpa, .io = io, .name = owned_name, .scratch = scratch, .epoch = runtime.now(io) };
self.* = .{
.gpa = gpa,
.io = io,
.name = owned_name,
.scratch = scratch,
.epoch = runtime.now(io),
};
return self;
}
pub fn lock(self: *Application) void {
self.mutex.lockUncancelable(self.io);
}
pub fn unlock(self: *Application) void {
self.mutex.unlock(self.io);
}
pub fn notify(self: *Application) void {
self.available.set(self.io);
// Wake native dispatch for events and worker completions.
if (self.native_started) c.z_native_wake();
}

188
src/Cycles.zig Normal file
View File

@ -0,0 +1,188 @@
//! Shared identities for multi-event input interactions; called under the app lock.
const std = @import("std");
const c = @import("native");
const Cycles = @This();
pointer: u64 = 0,
scroll: u64 = 0,
composition: u64 = 0,
composition_committed: bool = false,
buttons: u32 = 0,
captured: bool = false,
pub const Ended = struct {
ids: [3]u64 = @splat(0),
reasons: [3]c.uhdk_cycle_end_reason = @splat(c.UHDK_CYCLE_COMPLETED),
len: usize = 0,
fn take(self: *Ended, id: *u64, reason: c.uhdk_cycle_end_reason) void {
if (id.* == 0) return;
self.ids[self.len] = id.*;
self.reasons[self.len] = reason;
self.len += 1;
id.* = 0;
}
};
fn begin(id: *u64, next: *u64) !void {
if (id.* != 0) return;
if (next.* == std.math.maxInt(u64)) return error.Exhausted;
id.* = next.*;
next.* += 1;
}
pub fn endAll(self: *Cycles, reason: c.uhdk_cycle_end_reason) Ended {
var ended: Ended = .{};
ended.take(&self.pointer, reason);
ended.take(&self.scroll, reason);
ended.take(&self.composition, reason);
self.buttons = 0;
self.captured = false;
self.composition_committed = false;
return ended;
}
pub fn apply(self: *Cycles, next: *u64, event: *c.z_event) !Ended {
var ended: Ended = .{};
event.cycle_id = 0;
switch (event.type) {
c.UHDK_EVENT_POINTER_BUTTON => {
const p = event.data.pointer;
if (p.button == 0 or p.button >= 32) return ended;
const bit = @as(u32, 1) << @as(u5, @intCast(p.button));
if (p.pressed != 0) {
try begin(&self.pointer, next);
self.buttons |= bit;
} else self.buttons &= ~bit;
event.cycle_id = self.pointer;
if (self.buttons == 0 and !self.captured) ended.take(&self.pointer, c.UHDK_CYCLE_COMPLETED);
},
c.UHDK_EVENT_POINTER_ENTER, c.UHDK_EVENT_POINTER_LEAVE, c.UHDK_EVENT_POINTER_MOVE => event.cycle_id = self.pointer,
c.UHDK_EVENT_POINTER_MODE_CHANGED => {
self.captured = event.data.pointer_mode != c.UHDK_POINTER_NORMAL;
if (self.captured) try begin(&self.pointer, next);
event.cycle_id = self.pointer;
if (!self.captured) {
self.buttons = 0;
ended.take(&self.pointer, event.cycle_end_reason);
}
},
c.UHDK_EVENT_SCROLL => {
const phase = event.data.scroll.phase;
if (phase != c.UHDK_SCROLL_DISCRETE) {
// A new native BEGIN retires an interrupted previous gesture.
if (phase == c.UHDK_SCROLL_BEGIN) ended.take(&self.scroll, c.UHDK_CYCLE_SUPERSEDED);
if (phase == c.UHDK_SCROLL_BEGIN or phase == c.UHDK_SCROLL_UPDATE) try begin(&self.scroll, next);
event.cycle_id = self.scroll;
if (phase == c.UHDK_SCROLL_END or phase == c.UHDK_SCROLL_CANCEL)
ended.take(&self.scroll, if (phase == c.UHDK_SCROLL_CANCEL) c.UHDK_CYCLE_CANCELLED else c.UHDK_CYCLE_COMPLETED);
}
},
c.UHDK_EVENT_TEXT_PREEDIT => {
if (self.composition == 0) self.composition_committed = false;
try begin(&self.composition, next);
event.cycle_id = self.composition;
},
c.UHDK_EVENT_TEXT_COMMIT => {
event.cycle_id = self.composition;
if (self.composition != 0) self.composition_committed = true;
},
c.UHDK_EVENT_TEXT_COMPOSITION_END => {
event.cycle_id = self.composition;
ended.take(&self.composition, if (self.composition_committed) c.UHDK_CYCLE_COMPLETED else c.UHDK_CYCLE_CANCELLED);
self.composition_committed = false;
},
c.UHDK_EVENT_WINDOW_METRICS => {
if (event.data.metrics.visible == 0) return self.endAll(c.UHDK_CYCLE_HIDDEN);
if (event.data.metrics.focused == 0) return self.endAll(c.UHDK_CYCLE_FOCUS_LOST);
},
else => {},
}
return ended;
}
test "drag and capture share a cycle and late releases cannot revive it" {
var state: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const drag = event.cycle_id;
try std.testing.expect(drag != 0);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_CAPTURE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(drag, event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_MOVE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(drag, event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_POINTER_MODE_CHANGED;
event.data.pointer_mode = c.UHDK_POINTER_NORMAL;
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 1), ended.len);
try std.testing.expectEqual(drag, ended.ids[0]);
event.type = c.UHDK_EVENT_POINTER_MOVE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer = std.mem.zeroes(c.uhdk_pointer_event);
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
try std.testing.expect(event.cycle_id != drag);
}
test "independent windows and kinds get distinct cycles and focus loss ends all" {
var state: Cycles = .{};
var other: Cycles = .{};
var next: u64 = 1;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
_ = try state.apply(&next, &event);
const pointer = event.cycle_id;
_ = try other.apply(&next, &event);
try std.testing.expect(event.cycle_id != pointer);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_BEGIN;
_ = try state.apply(&next, &event);
const scroll = event.cycle_id;
event.data.scroll.phase = c.UHDK_SCROLL_UPDATE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(scroll, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_PREEDIT;
_ = try state.apply(&next, &event);
const composition = event.cycle_id;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
event.type = c.UHDK_EVENT_TEXT_COMMIT;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(composition, event.cycle_id);
try std.testing.expect(pointer != scroll and scroll != composition);
event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.data.metrics = std.mem.zeroes(c.uhdk_window_metrics);
const ended = try state.apply(&next, &event);
try std.testing.expectEqual(@as(usize, 3), ended.len);
try std.testing.expectEqualSlices(u64, &.{ pointer, scroll, composition }, &ended.ids);
try std.testing.expectEqual(@as(usize, 0), (try state.apply(&next, &event)).len);
event.type = c.UHDK_EVENT_SCROLL;
event.data.scroll.phase = c.UHDK_SCROLL_DISCRETE;
_ = try state.apply(&next, &event);
try std.testing.expectEqual(@as(u64, 0), event.cycle_id);
}

View File

@ -2,7 +2,10 @@
const std = @import("std");
const c = @import("native");
const abi = @import("abi.zig");
const Data = struct { ptr: ?*const anyopaque = null, size: u64 = 0 };
const Data = struct {
ptr: ?*const anyopaque = null,
size: u64 = 0,
};
fn store(comptime T: type, allocator: std.mem.Allocator, value: T) !Data {
const ptr = try allocator.create(T);
@ -12,6 +15,7 @@ fn store(comptime T: type, allocator: std.mem.Allocator, value: T) !Data {
fn files(allocator: std.mem.Allocator, value: c.uhdk_file_list) !c.uhdk_file_list {
if (value.len == 0) return .{ .ptr = null, .len = 0 };
const ptr = try allocator.dupe(?*c.uhdk_file, value.ptr[0..@intCast(value.len)]);
return .{ .ptr = ptr.ptr, .len = ptr.len };
}
@ -22,22 +26,34 @@ fn result(allocator: std.mem.Allocator, source: c.z_request_result) !c.uhdk_requ
c.UHDK_REQUEST_CLIPBOARD_TEXT => try store(c.uhdk_text, allocator, try abi.copyText(allocator, source.value.text)),
c.UHDK_REQUEST_FILE_READ => try store(c.uhdk_bytes, allocator, try abi.copyBytes(allocator, source.value.bytes)),
c.UHDK_REQUEST_FILE_INFO => try store(c.uhdk_file_info, allocator, source.value.info),
c.UHDK_REQUEST_WINDOW => try store(c.uhdk_window_result, allocator, .{ .window = source.value.window }),
c.UHDK_REQUEST_GL_CONTEXT => try store(c.uhdk_gl_context_result, allocator, .{ .gl_context = source.value.gl_context }),
c.UHDK_REQUEST_WATCH => try store(c.uhdk_watch_result, allocator, .{ .watch = source.value.watch }),
else => .{},
};
return .{ .id = source.id, .kind = source.kind, .status = source.status, .diagnostic = try abi.copyText(allocator, source.diagnostic), .data = data.ptr, .data_size = data.size };
return .{
.tag = source.tag,
.kind = source.kind,
.status = source.status,
.diagnostic = if (source.status != abi.OK and source.diagnostic.len == 0)
abi.statusMessage(source.status)
else
try abi.copyText(allocator, source.diagnostic),
.data = data.ptr,
.data_size = data.size,
};
}
pub fn pack(allocator: std.mem.Allocator, source: c.z_event) !c.uhdk_event {
const data: Data = switch (source.type) {
c.UHDK_EVENT_APP_ACTIVATION => try store(c.uhdk_activation_event, allocator, .{ .active = source.data.active }),
c.UHDK_EVENT_APP_ACTIVATION => try store(c.uhdk_app_activation_event, allocator, .{ .active = source.data.active }),
c.UHDK_EVENT_OPEN_FILES => try store(c.uhdk_file_list, allocator, try files(allocator, source.data.files)),
c.UHDK_EVENT_WINDOW_METRICS => try store(c.uhdk_window_metrics, allocator, source.data.metrics),
c.UHDK_EVENT_PREFERENCES_CHANGED => try store(c.uhdk_preferences, allocator, source.data.preferences),
c.UHDK_EVENT_KEY => try store(c.uhdk_key_event, allocator, source.data.key),
c.UHDK_EVENT_POINTER_ENTER, c.UHDK_EVENT_POINTER_LEAVE, c.UHDK_EVENT_POINTER_MOVE, c.UHDK_EVENT_POINTER_BUTTON => try store(c.uhdk_pointer_event, allocator, source.data.pointer),
c.UHDK_EVENT_POINTER_ENTER,
c.UHDK_EVENT_POINTER_LEAVE,
c.UHDK_EVENT_POINTER_MOVE,
c.UHDK_EVENT_POINTER_BUTTON,
=> try store(c.uhdk_pointer_event, allocator, source.data.pointer),
c.UHDK_EVENT_POINTER_MODE_CHANGED => try store(c.uhdk_pointer_mode_event, allocator, .{ .mode = source.data.pointer_mode }),
c.UHDK_EVENT_SCROLL => try store(c.uhdk_scroll_event, allocator, source.data.scroll),
c.UHDK_EVENT_TEXT_COMMIT, c.UHDK_EVENT_TEXT_PREEDIT => data: {
@ -52,9 +68,21 @@ pub fn pack(allocator: std.mem.Allocator, source: c.z_event) !c.uhdk_event {
break :data try store(c.uhdk_drop_files_event, allocator, drop);
},
c.UHDK_EVENT_MENU_COMMAND => try store(c.uhdk_menu_event, allocator, source.data.menu),
c.UHDK_EVENT_TRAY_ACTIVATE => try store(c.uhdk_tray_event, allocator, source.data.tray),
c.UHDK_EVENT_TRAY_STATE => try store(c.uhdk_tray_state_event, allocator, source.data.tray_state),
c.UHDK_EVENT_WATCH => try store(c.uhdk_watch_event, allocator, source.data.watch),
c.UHDK_EVENT_CYCLE_END => try store(c.uhdk_cycle_end_event, allocator, source.data.cycle_end),
c.UHDK_EVENT_REQUEST_DONE => try store(c.uhdk_request_result, allocator, try result(allocator, source.data.request)),
else => .{},
};
return .{ .struct_size = @sizeOf(c.uhdk_event), .type = source.type, .time_ns = source.time_ns, .input_id = source.input_id, .window = source.window, .data = data.ptr, .data_size = data.size };
return .{
.struct_size = @sizeOf(c.uhdk_event),
.type = source.type,
.time_ns = source.time_ns,
.input_id = source.input_id,
.cycle_id = source.cycle_id,
.window = source.window,
.data = data.ptr,
.data_size = data.size,
};
}

View File

@ -1,44 +1,55 @@
//! One platform-thread file operation. Each step transfers at most one chunk.
//! One I/O-worker file operation. Each step transfers at most one chunk. may need more work to do batched chunking
const FileOperation = @This();
const std = @import("std");
const Io = std.Io;
const c = @import("native");
const Allocator = std.mem.Allocator;
pub const Kind = enum { read, write, info };
pub const FileKind = enum { file, directory, other };
pub const Info = struct {
size: u64,
modified_ns: i64,
kind: FileKind,
};
pub const Result = union(enum) {
pending,
bytes: []const u8,
info: Io.File.Stat,
info: Info,
written,
};
kind: Kind,
gpa: Allocator,
io: Io,
path: []const u8,
input: []const u8 = &.{},
limit: u64 = 0,
file: ?Io.File = null,
atomic_file: ?Io.File.Atomic = null,
reader: ?*anyopaque = null,
writer: ?*anyopaque = null,
contents: std.ArrayList(u8) = .empty,
offset: u64 = 0,
started: bool = false,
pub fn init(
gpa: Allocator,
io: Io,
kind: Kind,
path: []const u8,
input: []const u8,
limit: u64,
) FileOperation {
return .{ .gpa = gpa, .io = io, .kind = kind, .path = path, .input = input, .limit = limit };
return .{ .gpa = gpa, .kind = kind, .path = path, .input = input, .limit = limit };
}
pub fn close(self: *FileOperation) void {
if (self.reader) |reader| c.z_file_reader_close(reader);
self.reader = null;
if (self.writer) |writer| c.z_file_writer_close(writer);
self.writer = null;
}
pub fn deinit(self: *FileOperation) void {
if (self.file) |file| file.close(self.io);
if (self.atomic_file) |*file| file.deinit(self.io);
self.close();
self.contents.deinit(self.gpa);
self.* = undefined;
}
@ -46,49 +57,27 @@ pub fn deinit(self: *FileOperation) void {
/// The caller checks cancellation before each step. A successful replacement is
/// the commit point; subsequent cancellation must not change its successful result.
pub fn step(self: *FileOperation) !Result {
const cwd = Io.Dir.cwd();
if (self.kind == .info) {
return .{ .info = try cwd.statFile(self.io, self.path, .{}) };
return .{ .info = try metadata(self.path, true) };
}
if (!self.started) {
switch (self.kind) {
.read => {
// Reject nonregular files and do not follow the final symlink.
// Filesystem metadata remains advisory under concurrent changes.
const stat = try cwd.statFile(self.io, self.path, .{ .follow_symlinks = false });
const stat = try metadata(self.path, false);
if (stat.kind != .file) return error.NotRegularFile;
const file = try cwd.openFile(self.io, self.path, .{ .follow_symlinks = false });
errdefer file.close(self.io);
const opened = try file.stat(self.io);
if (opened.kind != .file) return error.NotRegularFile;
if (opened.size > self.limit) return error.StreamTooLong;
self.file = file;
if (stat.size > self.limit) return error.StreamTooLong;
try statusError(c.z_file_reader_open(pathSpan(self.path), &self.reader));
},
.write => {
const stat: ?Io.File.Stat = cwd.statFile(self.io, self.path, .{
.follow_symlinks = false,
}) catch |err| switch (err) {
error.FileNotFound => null,
else => return err,
};
if (stat) |existing| {
if (existing.kind != .file) return error.NotRegularFile;
if (@import("builtin").os.tag == .windows and existing.permissions.toAttributes().READONLY)
return error.AccessDenied;
}
self.atomic_file = try cwd.createFileAtomic(self.io, self.path, .{
.permissions = if (@import("builtin").os.tag == .windows) .default_file else .fromMode(0o600),
.replace = true,
});
if (@import("builtin").os.tag != .windows) if (stat) |existing| {
try self.atomic_file.?.file.setPermissions(
self.io,
.fromMode(existing.permissions.toMode() & 0o777),
);
};
try statusError(c.z_file_writer_open(pathSpan(self.path), &self.writer));
},
.info => unreachable,
}
self.started = true;
return .pending;
}
@ -98,9 +87,11 @@ pub fn step(self: *FileOperation) !Result {
var chunk: [chunk_size]u8 = undefined;
const remaining = self.limit -| self.contents.items.len;
const capacity = @min(chunk.len, remaining +| 1);
const count = try self.file.?.readPositional(self.io, &.{chunk[0..capacity]}, self.offset);
var count: usize = 0;
try statusError(c.z_file_reader_read(self.reader.?, self.offset, &chunk, capacity, &count));
if (count == 0) return .{ .bytes = self.contents.items };
if (count > remaining) return error.StreamTooLong;
try self.contents.appendSlice(self.gpa, chunk[0..count]);
self.offset += count;
return .pending;
@ -108,39 +99,74 @@ pub fn step(self: *FileOperation) !Result {
if (self.offset < self.input.len) {
const remaining = self.input[@intCast(self.offset)..];
const count = try self.atomic_file.?.file.writePositional(
self.io,
&.{remaining[0..@min(chunk_size, remaining.len)]},
self.offset,
);
var count: usize = 0;
const part = remaining[0..@min(chunk_size, remaining.len)];
try statusError(c.z_file_writer_write(self.writer.?, self.offset, part.ptr, part.len, &count));
if (count == 0) return error.WriteFailed;
self.offset += count;
return .pending;
}
try self.atomic_file.?.replace(self.io);
try statusError(c.z_file_writer_commit(self.writer.?));
self.writer = null;
return .written;
}
fn pathSpan(path: []const u8) c.uhdk_bytes {
return .{ .ptr = path.ptr, .len = path.len };
}
fn metadata(path: []const u8, follow: bool) !Info {
var value: c.z_file_metadata = undefined;
try statusError(c.z_file_metadata_read(pathSpan(path), @intFromBool(follow), &value));
return .{
.size = value.size,
.modified_ns = value.modified_ns,
.kind = switch (value.type) {
c.Z_FILE_TYPE_REGULAR => .file,
c.Z_FILE_TYPE_DIRECTORY => .directory,
else => .other,
},
};
}
fn statusError(status: u32) !void {
return switch (status) {
c.Z_FILE_OK => {},
c.Z_FILE_NOT_FOUND => error.FileNotFound,
c.Z_FILE_ACCESS_DENIED => error.AccessDenied,
c.Z_FILE_NOT_REGULAR => error.NotRegularFile,
c.Z_FILE_INVALID_PATH => error.InvalidPath,
c.Z_FILE_OUT_OF_MEMORY => error.OutOfMemory,
else => error.Unexpected,
};
}
test "chunked replacement, bounded read, and cancellation before commit" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var temporary = std.testing.tmpDir(.{});
defer temporary.cleanup();
const directory = try temporary.dir.realPathFileAlloc(io, ".", gpa);
defer gpa.free(directory);
const path = try std.fs.path.join(gpa, &.{ directory, "document" });
defer gpa.free(path);
const contents = try gpa.alloc(u8, 600_000);
defer gpa.free(contents);
@memset(contents, 0xab);
var write = FileOperation.init(gpa, io, .write, path, contents, 0);
var write = FileOperation.init(gpa, .write, path, contents, 0);
defer write.deinit();
var passes: usize = 0;
while (try write.step() == .pending) : (passes += 1) {}
try std.testing.expect(passes >= 4);
var read = FileOperation.init(gpa, io, .read, path, &.{}, contents.len);
var read = FileOperation.init(gpa, .read, path, &.{}, contents.len);
defer read.deinit();
while (true) {
switch (try read.step()) {
@ -152,14 +178,16 @@ test "chunked replacement, bounded read, and cancellation before commit" {
else => unreachable,
}
}
var limited = FileOperation.init(gpa, io, .read, path, &.{}, 10);
var limited = FileOperation.init(gpa, .read, path, &.{}, 10);
defer limited.deinit();
try std.testing.expectError(error.StreamTooLong, limited.step());
var cancelled = FileOperation.init(gpa, io, .write, path, "changed", 0);
var cancelled = FileOperation.init(gpa, .write, path, "changed", 0);
try std.testing.expect(try cancelled.step() == .pending);
try std.testing.expect(try cancelled.step() == .pending);
cancelled.deinit();
const preserved = try temporary.dir.readFileAlloc(io, "document", gpa, .limited(contents.len + 1));
defer gpa.free(preserved);
try std.testing.expectEqualSlices(u8, contents, preserved);

61
src/MinimalIo.zig Normal file
View File

@ -0,0 +1,61 @@
//! UHDK's small blocking `std.Io` implementation.
//!
//! UHDK schedules file work on its own worker. This interface exists only for
//! clocks and the futex operations used by `std.Io.Mutex` and `std.Io.Event`.
const std = @import("std");
const c = @import("native");
const Io = std.Io;
pub const instance: Io = .{
.userdata = null,
.vtable = &vtable,
};
const vtable: Io.VTable = blk: {
var result = Io.failing.vtable.*;
result.futexWait = futexWait;
result.futexWaitUncancelable = futexWaitUncancelable;
result.futexWake = futexWake;
result.now = now;
break :blk result;
};
fn futexWait(_: ?*anyopaque, ptr: *const u32, expected: u32, timeout: Io.Timeout) Io.Cancelable!void {
const duration = timeout.toDurationFromNow(instance);
const timeout_ns: u64 = if (duration) |value|
std.math.lossyCast(u64, @max(0, value.raw.toNanoseconds()))
else
0;
c.z_io_wait(ptr, expected, timeout_ns, @intFromBool(duration != null));
}
fn futexWaitUncancelable(_: ?*anyopaque, ptr: *const u32, expected: u32) void {
c.z_io_wait(ptr, expected, 0, 0);
}
fn futexWake(_: ?*anyopaque, ptr: *const u32, max_waiters: u32) void {
c.z_io_wake(ptr, max_waiters);
}
fn now(_: ?*anyopaque, clock: Io.Clock) Io.Timestamp {
return .{ .nanoseconds = c.z_io_now(@intFromEnum(clock)) };
}
test "clock and event wake" {
var event: Io.Event = .unset;
const worker = try std.Thread.spawn(.{}, struct {
fn run(target: *Io.Event) void {
const start = c.z_io_now(@intFromEnum(Io.Clock.awake));
while (c.z_io_now(@intFromEnum(Io.Clock.awake)) - start < std.time.ns_per_ms)
std.atomic.spinLoopHint();
target.set(instance);
}
}.run, .{&event});
defer worker.join();
try event.waitTimeout(instance, .{ .duration = .{
.raw = .fromSeconds(5),
.clock = .awake,
} });
try std.testing.expect(c.z_io_now(@intFromEnum(Io.Clock.awake)) > 0);
}

View File

@ -2,7 +2,7 @@
const std = @import("std");
const builtin = @import("builtin");
pub const enabled = @import("profile_options").enabled;
const verify_stack_order = builtin.mode == .Debug or builtin.mode == .ReleaseSafe;
const verify_stack_order = builtin.mode == .debug or builtin.mode == .safe;
// Tracy 0.14.1 C ABI with TRACY_ON_DEMAND; the consumer supplies the client.
// No C header translation or references to Tracy symbols in disabled builds.
@ -13,11 +13,13 @@ const SourceLocation = extern struct {
line: u32,
color: u32 = 0,
};
const Token = extern struct {
id: u32 = 0,
active: i32 = 0,
connection: u64 = 0,
};
extern fn ___tracy_emit_zone_begin(source: *const SourceLocation, active: i32) Token;
extern fn ___tracy_emit_zone_end(zone: Token) void;
extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void;
@ -36,6 +38,7 @@ pub const Zone = if (enabled) struct {
std.debug.assert(self.depth == stack_depth);
stack_depth -= 1;
}
if (self.token.active != 0) ___tracy_emit_zone_end(self.token);
}
} else struct {
@ -58,6 +61,7 @@ fn StaticSource(comptime source: std.builtin.SourceLocation, comptime name: [:0]
pub inline fn begin(comptime source: std.builtin.SourceLocation, comptime name: [:0]const u8) Zone {
if (!enabled) return .{};
const Statics = StaticSource(source, name);
const token = ___tracy_emit_zone_begin(&Statics.location, 1);
if (verify_stack_order) stack_depth += 1;
@ -102,6 +106,7 @@ pub fn TrackingAllocator(comptime pool: [:0]const u8) type {
.vtable = &.{
.alloc = allocate,
.resize = resize,
// Let Allocator.realloc use alloc/copy/free. A moving rawRemap
// releases the old address before we can report its free, so
// another thread could reuse it and emit an out-of-order alloc.
@ -110,19 +115,23 @@ pub fn TrackingAllocator(comptime pool: [:0]const u8) type {
},
};
}
fn allocate(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ret: usize) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
const ptr = self.child.rawAlloc(len, alignment, ret) orelse return null;
alloc(ptr, len, pool);
return ptr;
}
fn resize(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ret: usize) bool {
const self: *Self = @ptrCast(@alignCast(ctx));
if (!self.child.rawResize(memory, alignment, len, ret)) return false;
free(memory.ptr, pool);
alloc(memory.ptr, len, pool);
return true;
}
fn release(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ret: usize) void {
const self: *Self = @ptrCast(@alignCast(ctx));
free(memory.ptr, pool);

View File

@ -7,15 +7,23 @@ const Resource = @import("Resource.zig");
const FileOperation = @import("FileOperation.zig");
const Request = @This();
pub const Completion = enum { request, resource, discard };
next: ?*Request = null,
queued_next: ?*Request = null,
arena: abi.Arena,
gpa: std.mem.Allocator,
data: c.z_command = std.mem.zeroes(c.z_command),
node: *Event,
id: u64 = 0,
kind: u32 = c.UHDK_REQUEST_COMMAND,
id: u64 = 0, // Private monotonically increasing native identity.
tag: u64 = 0,
kind: u32 = 0,
cancelled: bool = false,
native_deferred: bool = false,
completion: Completion = .request,
pins: std.ArrayList(*Resource) = .empty,
file_operation: ?FileOperation = null,
io_status: abi.Status = abi.OK,
io_result: c.z_request_result = std.mem.zeroes(c.z_request_result),
io_prepared: ?*anyopaque = null,

View File

@ -10,34 +10,35 @@ gpa: std.mem.Allocator,
arena: std.heap.ArenaAllocator,
next: ?*Resource = null,
alive: bool = true,
ready: bool,
creation_status: u32 = 0,
refs: usize = 1,
native: ?*anyopaque = null,
payload: Payload,
pub const Kind = enum(u32) {
window = c.Z_KIND_WINDOW,
gl = c.Z_KIND_GL,
file = c.Z_KIND_FILE,
menu = c.Z_KIND_MENU,
watch = c.Z_KIND_WATCH,
tray = c.Z_KIND_TRAY,
};
pub const Payload = union(Kind) {
window: Window,
gl: Gl,
file: File,
menu: Menu,
watch: Watch,
tray: Tray,
};
pub const Window = struct {
context: ?*Resource = null,
cycles: @import("Cycles.zig") = .{},
parent: ?*Resource = null,
metrics: c.uhdk_window_metrics = std.mem.zeroes(c.uhdk_window_metrics),
};
pub const Gl = struct {
owner: ?*Resource = null,
gl_requested: bool = false,
gl_ready: bool = false,
gl_status: u32 = 0,
bracket: bool = false,
frame_cpu_start: u64 = 0,
swap_cpu_time: u64 = 0,
@ -60,17 +61,32 @@ pub const Watch = struct {
owner: ?*Resource = null,
};
pub const TraySnapshot = struct {
arena: std.heap.ArenaAllocator,
desc: c.uhdk_tray_desc,
};
pub const Tray = struct {
snapshot: ?*TraySnapshot = null,
state: c.uhdk_tray_state = .{
.struct_size = @sizeOf(c.uhdk_tray_state),
.status = c.UHDK_STATUS_UNAVAILABLE,
.available = 0,
},
};
pub fn init(application: *Application, resource_kind: Kind) Resource {
return .{
.app = application,
.gpa = application.gpa,
.arena = .init(application.gpa),
.ready = resource_kind != .window,
.payload = switch (resource_kind) {
.window => .{ .window = .{} },
.gl => .{ .gl = .{} },
.file => .{ .file = .{} },
.menu => .{ .menu = .{} },
.watch => .{ .watch = .{} },
.tray => .{ .tray = .{} },
},
};
}

View File

@ -27,7 +27,9 @@ pub fn textBytes(text: c.uhdk_text) []const u8 {
}
pub fn validText(t: c.uhdk_text, no_nul: bool) bool {
return validSpan(t.ptr, t.len) and std.unicode.utf8ValidateSlice(textBytes(t)) and (!no_nul or std.mem.findScalar(u8, textBytes(t), 0) == null);
return validSpan(t.ptr, t.len) and
std.unicode.utf8ValidateSlice(textBytes(t)) and
(!no_nul or std.mem.findScalar(u8, textBytes(t), 0) == null);
}
pub fn textSpan(s: []const u8) c.uhdk_text {
@ -49,15 +51,37 @@ pub fn validDescriptor(comptime T: type, handle: [*c]const T) bool {
pub fn writeOutput(comptime T: type, dest: [*c]T, value: T) Status {
if (dest == null or dest.*.struct_size < @sizeOf(T)) return INVALID;
dest.* = value;
dest.*.struct_size = @sizeOf(T);
return OK;
}
pub fn finiteSize(s: c.uhdk_size) bool {
return std.math.isFinite(s.width) and std.math.isFinite(s.height) and s.width >= 0 and s.height >= 0 and s.width <= 65536 and s.height <= 65536;
return std.math.isFinite(s.width) and
std.math.isFinite(s.height) and
s.width >= 0 and s.height >= 0 and
s.width <= 65536 and s.height <= 65536;
}
pub fn boundary(s: []const u8, offset: u64) bool {
return offset <= s.len and (offset == s.len or (s[@intCast(offset)] & 0xC0) != 0x80);
}
pub fn statusMessage(status: Status) c.uhdk_text {
return textSpan(switch (status) {
c.UHDK_STATUS_OK => "Success",
c.UHDK_STATUS_CANCELLED => "Operation cancelled",
c.UHDK_STATUS_UNSUPPORTED => "Operation not supported",
c.UHDK_STATUS_INVALID_ARGUMENT => "Invalid argument",
c.UHDK_STATUS_OUT_OF_MEMORY => "Out of memory",
c.UHDK_STATUS_PERMISSION_DENIED => "Permission denied",
c.UHDK_STATUS_UNAVAILABLE => "Resource unavailable",
c.UHDK_STATUS_NOT_FOUND => "Not found",
c.UHDK_STATUS_BUSY => "Resource or request tag is busy",
c.UHDK_STATUS_WRONG_THREAD => "Called from the wrong thread",
c.UHDK_STATUS_OS_ERROR => "Operating system error",
c.UHDK_STATUS_BUFFER_TOO_SMALL => "Buffer or requested size limit is too small",
else => "Unknown UHDK status",
});
}

View File

@ -6,120 +6,149 @@ const backend_kind = switch (@import("builtin").os.tag) {
.linux => c.UHDK_BACKEND_WAYLAND,
else => c.UHDK_BACKEND_MACOS,
};
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Application = @import("../Application.zig");
const MinimalIo = @import("../MinimalIo.zig");
pub var singleton: bool = false; // OS-main-thread lifecycle gate.
pub export fn uhdk_get_abi_version() u32 {
return c.UHDK_ABI_VERSION;
}
pub export fn uhdk_app_create(desc: [*c]const c.uhdk_app_desc, out: [*c]?*c.uhdk_app) abi.Status {
pub fn create(desc: *const c.uhdk_options, out: *?*c.uhdk_session) abi.Status {
out.* = null;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
if (!abi.validDescriptor(c.uhdk_app_desc, desc) or
out == null or
desc.*.abi_version != c.UHDK_ABI_VERSION or
desc.*.reserved != 0 or
!abi.validText(desc.*.display_name, true) or
!abi.validText(desc.*.application_id, true)) return abi.INVALID;
if (desc.*.preferred_backend != c.UHDK_BACKEND_AUTO and desc.*.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED;
if (!abi.validText(desc.title, true) or !abi.validText(desc.application_id, true)) return abi.INVALID;
if (desc.preferred_backend != c.UHDK_BACKEND_AUTO and desc.preferred_backend != backend_kind) return c.UHDK_STATUS_UNSUPPORTED;
if (singleton) return c.UHDK_STATUS_BUSY;
const gpa = profile.allocator();
const backend = gpa.create(std.Io.Threaded) catch return abi.OOM;
backend.* = .init(gpa, .{ .async_limit = .nothing, .concurrent_limit = .nothing });
const application = Application.create(gpa, backend.io(), abi.textBytes(desc.*.display_name)) catch {
backend.deinit();
gpa.destroy(backend);
return abi.OOM;
};
application.application_id = gpa.dupe(u8, abi.textBytes(desc.*.application_id)) catch {
const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.title)) catch return abi.OOM;
application.application_id = gpa.dupe(u8, abi.textBytes(desc.application_id)) catch {
application.scratch.deinit();
gpa.free(application.name);
gpa.destroy(application);
backend.deinit();
gpa.destroy(backend);
return abi.OOM;
};
application.io_backend = backend;
singleton = true;
const status = initialize(application);
if (status != abi.OK) {
releaseStorage(application);
return status;
}
out.* = runtime.toAppHandle(application);
return abi.OK;
}
pub export fn uhdk_app_run(
handle: ?*c.uhdk_app,
entry: c.uhdk_app_main_fn,
user: ?*anyopaque,
) abi.Status {
if (handle == null or entry == null) return abi.INVALID;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
const application = runtime.fromAppHandle(handle);
if (application.has_run) return abi.UNAVAILABLE;
fn initialize(application: *Application) abi.Status {
const handle = runtime.toAppHandle(application);
profile.thread("UHDK platform");
const ready = runtime.prepareReady(application) catch return abi.OOM;
const status = c.z_native_start(handle, abi.textSpan(application.name));
if (status != abi.OK) {
runtime.destroyEvent(ready);
return status;
}
runtime.publishReady(application, ready);
application.entry = entry;
application.user = user;
application.running = true;
application.has_run = true;
const worker = std.Thread.spawn(.{}, runtime.applicationMain, .{application}) catch {
application.running = false;
application.io_worker = std.Thread.spawn(.{}, runtime.ioMain, .{application}) catch {
c.z_native_finish();
return abi.OOM;
};
c.z_native_run();
worker.join();
application.running = false;
application.native_started = true;
application.running = true;
application.main_thread = std.Thread.getCurrentId();
return abi.OK;
}
fn shutdown(application: *Application) void {
const handle = runtime.toAppHandle(application);
std.debug.assert(!runtime.hasFrame(application));
_ = c.z_native_gl(null, 4, null);
application.lock();
application.stopping = true;
application.unlock();
// Keep native services alive while cancellation, completion, and destruction drain.
while (true) {
runtime.dispatch(handle);
application.lock();
const drained = application.requests == null and application.queue_head == null;
application.unlock();
if (drained) break;
c.z_native_pump(10 * std.time.ns_per_ms);
}
application.lock();
application.io_exit = true;
application.io_available.set(application.io);
application.unlock();
if (application.io_worker) |worker| worker.join();
application.io_worker = null;
// Native sources stop before any of their Zig records can be released.
var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.payload == .tray) {
object.alive = false;
if (object.native) |native| c.z_native_destroy(c.Z_KIND_TRAY, native);
object.native = null;
@import("tray.zig").clear(object);
}
if (object.kind() == c.Z_KIND_WATCH and object.native != null) {
c.z_native_destroy(object.kind(), object.native);
object.native = null;
}
}
cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.kind() == c.Z_KIND_GL and object.native != null) {
c.z_native_destroy(object.kind(), object.native);
object.native = null;
}
}
cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.kind() == c.Z_KIND_WINDOW and object.native != null) {
if (object.payload.window.gl_ready and object.payload.window.gl_status == abi.OK) {
c.z_native_destroy(c.Z_KIND_GL, object.native);
object.payload.window.gl_ready = false;
}
c.z_native_destroy(object.kind(), object.native);
object.native = null;
}
}
c.z_native_finish();
return abi.OK;
application.native_started = false;
application.running = false;
application.main_thread = null;
}
pub export fn uhdk_app_poll_events(
handle: ?*c.uhdk_app,
pub fn poll(
handle: ?*c.uhdk_session,
timeout: u64,
out: [*c]c.uhdk_event_list,
) abi.Status {
if (handle == null or out == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.hasFrame(application)) return c.UHDK_STATUS_BUSY;
const poll_zone = profile.begin(@src(), "UHDK poll events (includes wait)");
defer poll_zone.end();
runtime.destroyEvents(application.published);
application.published = null;
application.scratch.reset();
out.* = .{ .ptr = null, .len = 0 };
const start = runtime.now(application.io);
const end = start +| timeout;
runtime.dispatch(handle);
if (application.native_started) c.z_native_pump(0);
runtime.dispatch(handle);
application.lock();
defer application.unlock();
if (application.native_error != abi.OK) return application.native_error;
if (application.stopped_seen) return abi.UNAVAILABLE;
if (application.deadline != 0 and runtime.now(application.io) - application.epoch >= application.deadline) {
application.deadline = 0;
@ -127,9 +156,8 @@ pub export fn uhdk_app_poll_events(
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
application.lock();
}
const start = runtime.now(application.io);
const end = start +| timeout;
while (application.pending_head == null and application.event_error == abi.OK) {
while (application.pending_head == null and application.event_error == abi.OK and application.native_error == abi.OK) {
const current = runtime.now(application.io);
if (application.deadline != 0 and current - application.epoch >= application.deadline) {
application.deadline = 0;
@ -138,48 +166,56 @@ pub export fn uhdk_app_poll_events(
application.lock();
break;
}
if (current >= end) return abi.OK;
const wake_time = if (application.deadline == 0) end else @min(end, application.epoch +| application.deadline);
const ns = wake_time -| current;
application.available.reset();
application.unlock();
const wait_zone = profile.begin(@src(), "UHDK wait for events");
defer wait_zone.end();
application.available.waitTimeout(application.io, .{ .duration = .{
.raw = .fromNanoseconds(ns),
.clock = .awake,
} }) catch |err| switch (err) {
error.Timeout => {},
error.Canceled => {
application.lock();
return abi.CANCELLED;
},
};
if (application.native_started) c.z_native_pump(ns);
runtime.dispatch(handle);
application.lock();
}
if (application.native_error != abi.OK) return application.native_error;
if (application.event_error != abi.OK) {
const err = application.event_error;
application.event_error = abi.OK;
return err;
}
var cursor = application.pending_head;
var count: usize = 0;
while (cursor) |node| : (cursor = node.next) {
count += 1;
}
const allocator = application.scratch.allocator();
const events = allocator.alloc(c.uhdk_event, count) catch return abi.OOM;
var len: usize = 0;
cursor = application.pending_head;
// Do not consume nodes until the entire batch has been converted. On OOM,
// the queue (and all terminal request completions) remains retryable.
while (cursor) |node| : (cursor = node.next) {
const event = node.event;
if (event.window != null and !runtime.fromObjectHandle(event.window).alive) continue;
if (event.type == c.UHDK_EVENT_WATCH and !runtime.fromObjectHandle(event.data.watch.watch).alive) continue;
const tray = switch (event.type) {
c.UHDK_EVENT_TRAY_ACTIVATE => event.data.tray.tray,
c.UHDK_EVENT_TRAY_STATE => event.data.tray_state.tray,
c.UHDK_EVENT_MENU_COMMAND => event.data.menu.tray,
else => null,
};
if (tray != null and !runtime.fromObjectHandle(tray).alive) continue;
events[len] = @import("../EventPayload.zig").pack(allocator, event) catch return abi.OOM;
len += 1;
}
application.published = application.pending_head;
application.pending_head = null;
application.pending_tail = null;
@ -190,40 +226,23 @@ pub export fn uhdk_app_poll_events(
_ = node.arena.reset(.free_all);
if (node.event.type == c.UHDK_EVENT_STOPPED) application.stopped_seen = true;
}
out.* = .{ .ptr = if (len == 0) null else events.ptr, .len = len };
application.stats.event_count +|= out.*.len;
return abi.OK;
}
pub export fn uhdk_app_begin_tick(handle: ?*c.uhdk_app) abi.Status {
pub export fn uhdk_get_stats(handle: ?*c.uhdk_session, out: [*c]c.uhdk_stats) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (application.tick_start != null) return c.UHDK_STATUS_BUSY;
application.tick_start = runtime.threadCpuTime(application.io);
return abi.OK;
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return abi.writeOutput(c.uhdk_stats, out, application.stats);
}
pub export fn uhdk_app_end_tick(handle: ?*c.uhdk_app) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const start = application.tick_start orelse return abi.INVALID;
application.stats.tick_time_ns = runtime.threadCpuTime(application.io) -| start;
application.stats.tick_count +|= 1;
application.tick_start = null;
return abi.OK;
}
pub export fn uhdk_app_get_stats(handle: ?*c.uhdk_app, out: [*c]c.uhdk_app_stats) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return abi.writeOutput(c.uhdk_app_stats, out, application.stats);
}
pub export fn uhdk_app_quit(handle: ?*c.uhdk_app) void {
pub export fn uhdk_quit(handle: ?*c.uhdk_session) void {
if (handle == null) return;
const application = runtime.fromAppHandle(handle);
application.lock();
application.stopping = true;
@ -231,19 +250,24 @@ pub export fn uhdk_app_quit(handle: ?*c.uhdk_app) void {
c.z_native_wake();
}
pub export fn uhdk_app_wake(handle: ?*c.uhdk_app) void {
if (handle != null) runtime.simpleEvent(runtime.fromAppHandle(handle), c.UHDK_EVENT_WAKE);
pub export fn uhdk_wake(handle: ?*c.uhdk_session) void {
if (handle != null) {
runtime.simpleEvent(runtime.fromAppHandle(handle), c.UHDK_EVENT_WAKE);
c.z_native_wake();
}
}
pub export fn uhdk_app_get_time_ns(handle: ?*c.uhdk_app) u64 {
pub export fn uhdk_get_time_ns(handle: ?*c.uhdk_session) u64 {
const application = runtime.fromAppHandle(handle);
return runtime.now(application.io) - application.epoch;
}
pub export fn uhdk_app_set_wake_deadline(handle: ?*c.uhdk_app, deadline: u64) abi.Status {
pub export fn uhdk_set_wake_deadline(handle: ?*c.uhdk_session, deadline: u64) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
application.deadline = deadline;
application.notify();
@ -251,44 +275,55 @@ pub export fn uhdk_app_set_wake_deadline(handle: ?*c.uhdk_app, deadline: u64) ab
return abi.OK;
}
pub export fn uhdk_app_get_backend(handle: ?*c.uhdk_app) c.uhdk_backend {
pub export fn uhdk_get_backend(handle: ?*c.uhdk_session) c.uhdk_backend {
if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").backend(handle);
return backend_kind;
}
pub export fn uhdk_app_has_capability(handle: ?*c.uhdk_app, cap: c.uhdk_capability) c.uhdk_bool {
pub export fn uhdk_has_capability(handle: ?*c.uhdk_session, cap: c.uhdk_capability) c.uhdk_bool {
if (@import("builtin").os.tag == .linux) return @import("../linux/native.zig").capability(handle, cap);
return switch (cap) {
c.UHDK_CAP_FILE_DIALOGS, c.UHDK_CAP_CLIPBOARD, c.UHDK_CAP_DROP_FILES, c.UHDK_CAP_APP_MENU, c.UHDK_CAP_CONTEXT_MENU, c.UHDK_CAP_APP_ICON, c.UHDK_CAP_POINTER_CAPTURE, c.UHDK_CAP_TEXT_INPUT, c.UHDK_CAP_OPENGL => 1,
c.UHDK_CAP_POINTER_CONFINEMENT => @intFromBool(@import("builtin").os.tag == .windows),
c.UHDK_CAP_FILE_DIALOGS, c.UHDK_CAP_CLIPBOARD, c.UHDK_CAP_DROP_FILES, c.UHDK_CAP_APP_MENU, c.UHDK_CAP_CONTEXT_MENU, c.UHDK_CAP_APP_ICON, c.UHDK_CAP_POINTER_CAPTURE, c.UHDK_CAP_TEXT_INPUT, c.UHDK_CAP_OPENGL, c.UHDK_CAP_TRAY => 1,
else => 0,
};
}
pub export fn uhdk_request_cancel(handle: ?*c.uhdk_app, id: u64) abi.Status {
if (handle == null or id == 0) return abi.INVALID;
pub export fn uhdk_request_cancel(handle: ?*c.uhdk_session, tag: u64) abi.Status {
if (handle == null or tag == 0) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) {
if (command.id == id) {
if (command.completion == .request and command.tag == tag) {
command.cancelled = true;
application.unlock();
c.z_native_wake();
return abi.OK;
}
}
application.unlock();
return c.UHDK_STATUS_NOT_FOUND;
}
pub export fn uhdk_app_destroy(handle: ?*c.uhdk_app) void {
pub fn destroy(handle: ?*c.uhdk_session) void {
if (handle == null) return;
const application = runtime.fromAppHandle(handle);
std.debug.assert(c.z_native_is_main_thread() != 0 and !application.running);
std.debug.assert(c.z_native_is_main_thread() != 0);
shutdown(application);
releaseStorage(application);
}
fn releaseStorage(application: *Application) void {
runtime.destroyEvents(application.published);
runtime.destroyEvents(application.pending_head);
application.scratch.deinit();
var cursor = application.objects;
while (cursor) |object| {
cursor = object.next;
@ -296,13 +331,14 @@ pub export fn uhdk_app_destroy(handle: ?*c.uhdk_app) void {
object.arena.deinit();
application.gpa.destroy(object);
}
const gpa = application.gpa;
gpa.free(application.name);
gpa.free(application.application_id);
if (application.io_backend) |backend| {
backend.deinit();
gpa.destroy(backend);
}
gpa.destroy(application);
singleton = false;
}
pub export fn uhdk_status_message(status: abi.Status) c.uhdk_text {
return abi.statusMessage(status);
}

View File

@ -1,64 +1,62 @@
//! C ABI entry points for desktop.
const std = @import("std");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_clipboard_write_text_async(
handle: ?*c.uhdk_app,
pub export fn uhdk_clipboard_write_text(
handle: ?*c.uhdk_session,
text: c.uhdk_text,
out: [*c]u64,
) abi.Status {
if (!abi.validText(text, false)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_CLIP_WRITE) catch |err| return runtime.applicationError(err);
command.data.text = abi.copyText(command.arena.allocator(), text) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submitCommand(runtime.fromAppHandle(handle), command);
}
pub export fn uhdk_clipboard_read_text_async(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
limit: u64,
out: [*c]u64,
tag: u64,
) abi.Status {
const command = runtime.createAppCommand(handle, c.Z_CLIP_READ) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
command.data.limit = limit;
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_shell_open_url_async(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
text: c.uhdk_text,
out: [*c]u64,
tag: u64,
) abi.Status {
if (!abi.validText(text, true) or text.len == 0) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_URL) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_SHELL;
command.data.text = abi.copyText(command.arena.allocator(), text) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_app_set_icon_async(
handle: ?*c.uhdk_app,
pub export fn uhdk_set_icon(
handle: ?*c.uhdk_session,
image: [*c]const c.uhdk_image,
out: [*c]u64,
) abi.Status {
if (!abi.validDescriptor(c.uhdk_image, image)) return abi.INVALID;
const i = image.*;
if (i.reserved != 0 or
i.width == 0 or
i.height == 0 or
i.width > 4096 or
i.height > 4096 or
i.stride_bytes < @as(u64, i.width) * 4 or
i.stride_bytes > std.math.maxInt(u64) / @as(u64, i.height) or
i.pixels.len < i.stride_bytes * i.height or
i.pixels.len < @as(u64, i.width) * i.height * 4 or
!abi.validSpan(i.pixels.ptr, i.pixels.len)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_ICON) catch |err| return runtime.applicationError(err);
command.data.image = i;
@ -66,16 +64,18 @@ pub export fn uhdk_app_set_icon_async(
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submitCommand(runtime.fromAppHandle(handle), command);
}
pub export fn uhdk_app_get_preferences(
handle: ?*c.uhdk_app,
pub export fn uhdk_get_preferences(
handle: ?*c.uhdk_session,
out: [*c]c.uhdk_preferences,
) abi.Status {
if (handle == null) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
application.lock();
defer application.unlock();
return abi.writeOutput(c.uhdk_preferences, out, application.preferences);

View File

@ -5,11 +5,12 @@ const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_file_dialog_show_async(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
desc: [*c]const c.uhdk_file_dialog_desc,
out: [*c]u64,
tag: u64,
) abi.Status {
if (handle == null or !abi.validDescriptor(c.uhdk_file_dialog_desc, desc)) return abi.INVALID;
const d = desc.*;
if (d.kind > c.UHDK_DIALOG_SAVE_FILE or
!abi.validText(d.title, true) or
@ -20,6 +21,7 @@ pub export fn uhdk_file_dialog_show_async(
if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or
!runtime.fromObjectHandle(d.parent).alive)) return abi.INVALID;
if (d.initial_directory != null and runtime.fromObjectHandle(d.initial_directory).app != runtime.fromAppHandle(handle)) return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_DIALOG) catch |err| return runtime.applicationError(err);
command.kind = c.UHDK_REQUEST_FILE_DIALOG;
command.data.dialog = d;
@ -27,11 +29,11 @@ pub export fn uhdk_file_dialog_show_async(
runtime.abandon(command);
return if (err == error.OutOfMemory) abi.OOM else abi.INVALID;
};
return runtime.submit(runtime.fromAppHandle(handle), command, out);
return runtime.submit(runtime.fromAppHandle(handle), command, tag);
}
pub export fn uhdk_file_create_from_native_path(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
path: c.uhdk_bytes,
out: [*c]?*c.uhdk_file,
) abi.Status {
@ -41,30 +43,34 @@ pub export fn uhdk_file_create_from_native_path(
path.len == 0) return abi.INVALID;
if (@import("builtin").os.tag != .windows and
(abi.bytes(path)[0] != '/' or std.mem.findScalar(u8, abi.bytes(path), 0) != null)) return abi.INVALID;
if (runtime.checkThread(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), path, .{ .ptr = null, .len = 0 }, null);
if (status != abi.OK) {
runtime.release(object);
return status;
}
out.* = runtime.castHandle(*c.uhdk_file, object);
return abi.OK;
}
pub export fn uhdk_file_create_from_uri(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
uri: c.uhdk_text,
out: [*c]?*c.uhdk_file,
) abi.Status {
if (handle == null or out == null or !abi.validText(uri, true)) return abi.INVALID;
if (runtime.checkThread(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_FILE) catch return abi.OOM;
const status = c.z_native_file_init(runtime.castHandle(*c.uhdk_file, object), .{ .ptr = null, .len = 0 }, uri, null);
if (status != abi.OK) {
runtime.release(object);
return status;
}
out.* = runtime.castHandle(*c.uhdk_file, object);
return abi.OK;
}
@ -85,15 +91,18 @@ pub export fn uhdk_file_copy_representation(
out: [*c]u64,
) abi.Status {
if (handle == null or out == null or !abi.validSpan(buffer, capacity)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_FILE);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_FILE);
if (status != abi.OK) return status;
const data = switch (form) {
c.UHDK_FILE_DISPLAY_NAME => object.payload.file.display,
c.UHDK_FILE_URI => object.payload.file.uri,
c.UHDK_FILE_NATIVE_PATH => object.payload.file.native_path,
else => return abi.INVALID,
};
if (@import("builtin").os.tag == .windows and form == c.UHDK_FILE_URI and data.len == 0)
return c.UHDK_STATUS_UNSUPPORTED;
out.* = data.len;
@ -103,46 +112,48 @@ pub export fn uhdk_file_copy_representation(
return abi.OK;
}
pub export fn uhdk_file_read_all_async(handle: ?*c.uhdk_file, limit: u64, out: [*c]u64) abi.Status {
pub export fn uhdk_file_read_all_async(handle: ?*c.uhdk_file, limit: u64, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_READ) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_READ;
command.data.limit = limit;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_file_write_all_async(
handle: ?*c.uhdk_file,
data: c.uhdk_bytes,
out: [*c]u64,
tag: u64,
) abi.Status {
if (!abi.validSpan(data.ptr, data.len)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_WRITE) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_WRITE;
command.data.bytes = abi.copyBytes(command.arena.allocator(), data) catch {
runtime.abandon(command);
return abi.OOM;
};
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_file_get_info_async(handle: ?*c.uhdk_file, out: [*c]u64) abi.Status {
pub export fn uhdk_file_get_info_async(handle: ?*c.uhdk_file, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, abi.IO_INFO) catch |err| return runtime.objectError(err);
command.kind = c.UHDK_REQUEST_FILE_INFO;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}
pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, out: [*c]u64) abi.Status {
pub export fn uhdk_watch_create_async(handle: ?*c.uhdk_file, tag: u64) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_FILE, c.Z_WATCH) catch |err| return runtime.objectError(err);
const f = runtime.fromObjectHandle(handle);
const object = runtime.createObject(f.app, c.Z_KIND_WATCH) catch {
runtime.abandon(command);
return abi.OOM;
};
object.payload.watch.owner = f;
runtime.retain(f);
command.data.other = object;
command.kind = c.UHDK_REQUEST_WATCH;
return runtime.submit(f.app, command, out);
return runtime.submit(f.app, command, tag);
}
pub export fn uhdk_watch_destroy(handle: ?*c.uhdk_watch) void {

View File

@ -1,136 +1,104 @@
//! C ABI entry points for graphics.
//! Private GL ownership and presentation for session boundaries.
const std = @import("std");
const profile = @import("profile");
const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_gl_context_create_async(handle: ?*c.uhdk_window, out: [*c]u64) abi.Status {
pub fn create(handle: ?*c.uhdk_window) abi.Status {
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_GL) catch |err| return runtime.objectError(err);
const w = runtime.fromObjectHandle(handle);
if (w.payload.window.context != null) {
if (w.payload.window.gl_requested) {
runtime.abandon(command);
return c.UHDK_STATUS_BUSY;
}
const object = runtime.createObject(w.app, c.Z_KIND_GL) catch {
runtime.abandon(command);
return abi.OOM;
};
object.payload.gl.owner = w;
w.payload.window.context = object;
command.data.other = object;
command.kind = c.UHDK_REQUEST_GL_CONTEXT;
return runtime.submit(w.app, command, out);
w.payload.window.gl_requested = true;
return runtime.submitResource(w.app, command);
}
pub export fn uhdk_gl_context_destroy(handle: ?*c.uhdk_gl_context) void {
if (handle == null) return;
const object = runtime.fromObjectHandle(handle);
if (object.payload.gl.owner) |w| w.payload.window.context = null;
runtime.destroyObject(object);
}
pub export fn uhdk_gl_context_begin_frame(handle: ?*c.uhdk_gl_context) abi.Status {
pub fn acquire(handle: ?*c.uhdk_window) abi.Status {
const zone = profile.begin(@src(), "UHDK acquire GL context");
defer zone.end();
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
if (object.payload.gl.bracket) return c.UHDK_STATUS_BUSY;
if (object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
const status = runtime.glCall(handle, 1, null);
if (status == abi.OK) {
object.payload.gl.bracket = true;
object.payload.gl.frame_cpu_start = runtime.threadCpuTime(object.app.io);
object.payload.gl.swap_cpu_time = 0;
object.payload.gl.presented = false;
object.payload.window.bracket = true;
object.payload.window.frame_cpu_start = runtime.threadCpuTime(object.app.io);
object.payload.window.swap_cpu_time = 0;
object.payload.window.presented = false;
}
return status;
}
pub export fn uhdk_gl_context_end_frame(handle: ?*c.uhdk_gl_context) abi.Status {
pub fn release(handle: ?*c.uhdk_window) abi.Status {
const status = runtime.glCall(handle, 2, null);
if (status == abi.OK) {
const object = runtime.fromObjectHandle(handle);
object.payload.gl.bracket = false;
if (object.payload.gl.presented) {
object.payload.window.bracket = false;
if (object.payload.window.presented) {
const stats = &object.app.stats;
const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.gl.frame_cpu_start;
stats.render_time_ns = elapsed -| object.payload.gl.swap_cpu_time;
stats.frame_time_ns = stats.tick_time_ns +| stats.render_time_ns;
const elapsed = runtime.threadCpuTime(object.app.io) -| object.payload.window.frame_cpu_start;
stats.render_time_ns = elapsed -| object.payload.window.swap_cpu_time;
stats.frame_count +|= 1;
const now = runtime.now(object.app.io);
if (object.app.last_frame_time) |previous| {
const interval = now -| previous;
stats.frames_per_second = if (interval == 0) 0 else @as(f32, std.time.ns_per_s) / @as(f32, @floatFromInt(interval));
}
object.app.last_frame_time = now;
}
}
return status;
}
pub export fn uhdk_gl_context_make_current(handle: ?*c.uhdk_gl_context) abi.Status {
return runtime.glCall(handle, 3, null);
}
pub export fn uhdk_gl_clear_current(handle: ?*c.uhdk_app) abi.Status {
if (handle == null) return abi.INVALID;
if (runtime.checkThread(runtime.fromAppHandle(handle)) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return c.z_native_gl(null, 4, null);
}
pub export fn uhdk_gl_context_get_version(
handle: ?*c.uhdk_gl_context,
major: [*c]u32,
minor: [*c]u32,
) abi.Status {
if (major == null or minor == null) return abi.INVALID;
var version: [2]u32 = undefined;
const status = runtime.glCall(handle, 5, &version);
if (status == abi.OK) {
major.* = version[0];
minor.* = version[1];
}
return status;
}
pub export fn uhdk_gl_context_swap_buffers(handle: ?*c.uhdk_gl_context) abi.Status {
pub fn present(handle: ?*c.uhdk_window) abi.Status {
const zone = profile.begin(@src(), "UHDK present (includes vsync)");
defer zone.end();
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const valid = runtime.checkObject(object, c.Z_KIND_GL);
const valid = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (valid != abi.OK) return valid;
if (!object.payload.gl.bracket) return c.UHDK_STATUS_BUSY;
if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
// Exclude even driver CPU work/spinning inside presentation, not just sleep.
const start = runtime.threadCpuTime(object.app.io);
const status = runtime.glCall(handle, 6, null);
object.payload.gl.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start;
if (status == abi.OK) object.payload.gl.presented = true;
object.payload.window.swap_cpu_time +|= runtime.threadCpuTime(object.app.io) -| start;
if (status == abi.OK) object.payload.window.presented = true;
return status;
}
pub export fn uhdk_gl_context_set_swap_interval(
handle: ?*c.uhdk_gl_context,
pub fn setSwapInterval(
handle: ?*c.uhdk_window,
interval: i32,
) abi.Status {
if (interval != 0 and interval != 1) return abi.INVALID;
var value = interval;
return runtime.glCall(handle, 7, &value);
}
pub export fn uhdk_gl_context_get_proc(
handle: ?*c.uhdk_gl_context,
pub fn getProc(
handle: ?*c.uhdk_window,
name: c.uhdk_text,
out: [*c]c.uhdk_gl_proc,
) abi.Status {
if (handle == null or
out == null or
!abi.validText(name, true) or
name.len == 0 or
name.len > 255) return abi.INVALID;
if (handle == null or out == null or !abi.validText(name, true) or name.len == 0 or name.len > 255)
return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_GL);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
if (!object.payload.gl.bracket) return c.UHDK_STATUS_BUSY;
if (!object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
return c.z_native_gl_proc(object.native, name, out);
}

View File

@ -4,38 +4,46 @@ const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_window_set_cursor_shape_async(
handle: ?*c.uhdk_window,
shape: u32,
out: [*c]u64,
) abi.Status {
pub export fn uhdk_window_set_function_key_policy(handle: ?*c.uhdk_window, policy: u32) abi.Status {
if (policy > c.UHDK_FUNCTION_KEYS_APPLICATION) return abi.INVALID;
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_FUNCTION_KEYS, policy);
}
pub export fn uhdk_window_set_cursor_shape(handle: ?*c.uhdk_window, shape: u32) abi.Status {
if (shape > c.UHDK_CURSOR_HIDDEN) return abi.INVALID;
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_CURSOR, shape, out);
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_CURSOR, shape);
}
pub export fn uhdk_window_set_pointer_mode_async(
handle: ?*c.uhdk_window,
mode: u32,
out: [*c]u64,
) abi.Status {
if (mode > 1) return abi.INVALID;
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_POINTER, mode, out);
pub export fn uhdk_window_set_pointer_mode(handle: ?*c.uhdk_window, mode: u32) abi.Status {
if (mode > c.UHDK_POINTER_CONFINED) return abi.INVALID;
const command = runtime.createObjectCommand(
handle,
c.Z_KIND_WINDOW,
c.Z_POINTER,
) catch |err| return runtime.objectError(err);
const application = runtime.fromObjectHandle(handle).app;
if (mode == c.UHDK_POINTER_CONFINED) {
const supported = @import("app.zig").uhdk_has_capability(
runtime.toAppHandle(application),
c.UHDK_CAP_POINTER_CONFINEMENT,
);
if (supported == 0) {
runtime.abandon(command);
return c.UHDK_STATUS_UNSUPPORTED;
}
}
command.data.number = mode;
return runtime.submitCommand(application, command);
}
pub export fn uhdk_window_set_text_input_async(
handle: ?*c.uhdk_window,
enabled: c.uhdk_bool,
out: [*c]u64,
) abi.Status {
pub export fn uhdk_window_set_text_input(handle: ?*c.uhdk_window, enabled: c.uhdk_bool) abi.Status {
if (enabled != 0 and enabled != 1) return abi.INVALID;
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_TEXT_ENABLE, @intCast(enabled), out);
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TEXT_ENABLE, @intCast(enabled));
}
pub export fn uhdk_window_cancel_composition_async(
handle: ?*c.uhdk_window,
out: [*c]u64,
) abi.Status {
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_TEXT_CANCEL, 0, out);
pub export fn uhdk_window_cancel_composition(handle: ?*c.uhdk_window) abi.Status {
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TEXT_CANCEL, 0);
}
pub export fn uhdk_window_set_text_state(
@ -61,6 +69,7 @@ pub export fn uhdk_window_set_text_state(
runtime.abandon(command);
return abi.OOM;
};
const application = runtime.fromObjectHandle(handle).app;
application.lock();
if (application.queue_tail) |tail| tail.queued_next = command else application.queue_head = command;
@ -70,11 +79,7 @@ pub export fn uhdk_window_set_text_state(
return abi.OK;
}
pub export fn uhdk_window_set_drop_enabled_async(
handle: ?*c.uhdk_window,
enabled: c.uhdk_bool,
out: [*c]u64,
) abi.Status {
pub export fn uhdk_window_set_drop_enabled(handle: ?*c.uhdk_window, enabled: c.uhdk_bool) abi.Status {
if (enabled != 0 and enabled != 1) return abi.INVALID;
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_DROP, @intCast(enabled), out);
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_DROP, @intCast(enabled));
}

View File

@ -5,19 +5,22 @@ const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_menu_create(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
items: [*c]const c.uhdk_menu_item,
len: u64,
out: [*c]?*c.uhdk_menu,
) abi.Status {
if (handle == null or out == null or !abi.validSpan(items, len) or len > 4096) return abi.INVALID;
const application = runtime.fromAppHandle(handle);
if (runtime.checkThread(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (runtime.validateMainThreadSessionReady(application) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
const object = runtime.createObject(application, c.Z_KIND_MENU) catch return abi.OOM;
object.payload.menu.items = object.arena.allocator().alloc(c.uhdk_menu_item, @intCast(len)) catch {
runtime.release(object);
return abi.OOM;
};
for (object.payload.menu.items, 0..) |*item, i| {
item.* = items[i];
if (!abi.validText(item.label, true) or
@ -28,26 +31,31 @@ pub export fn uhdk_menu_create(
runtime.release(object);
return abi.INVALID;
}
if (item.submenu != null and (runtime.fromObjectHandle(item.submenu).app != application or
!runtime.fromObjectHandle(item.submenu).alive))
{
runtime.release(object);
return abi.INVALID;
}
item.label = abi.copyText(object.arena.allocator(), item.label) catch {
runtime.release(object);
return abi.OOM;
};
}
var ids: std.AutoHashMap(u64, void) = .init(application.gpa);
defer ids.deinit();
runtime.validateMenu(object, &ids, 0) catch |err| {
runtime.release(object);
return if (err == error.OutOfMemory) abi.OOM else abi.INVALID;
};
for (object.payload.menu.items) |item| if (item.submenu) |sub| {
runtime.retain(runtime.fromObjectHandle(sub));
};
object.payload.menu.owns_submenus = true;
out.* = runtime.castHandle(*c.uhdk_menu, object);
return abi.OK;
@ -61,41 +69,39 @@ pub export fn uhdk_menu_release(handle: ?*c.uhdk_menu) void {
if (handle != null) runtime.release(runtime.fromObjectHandle(handle));
}
pub export fn uhdk_app_set_menu_async(
handle: ?*c.uhdk_app,
pub export fn uhdk_set_menu(
handle: ?*c.uhdk_session,
menu: ?*c.uhdk_menu,
out: [*c]u64,
) abi.Status {
return runtime.attachMenu(handle, null, menu, out);
return runtime.attachMenu(handle, null, menu);
}
pub export fn uhdk_window_set_menu_async(
pub export fn uhdk_window_set_menu(
handle: ?*c.uhdk_window,
menu: ?*c.uhdk_menu,
out: [*c]u64,
) abi.Status {
if (handle == null) return abi.INVALID;
return runtime.attachMenu(runtime.toAppHandle(runtime.fromObjectHandle(handle).app), handle, menu, out);
return runtime.attachMenu(runtime.toAppHandle(runtime.fromObjectHandle(handle).app), handle, menu);
}
pub export fn uhdk_menu_set_item_flags_async(
pub export fn uhdk_menu_set_item_flags(
handle: ?*c.uhdk_menu,
id: u64,
flags: u32,
out: [*c]u64,
) abi.Status {
if (id == 0 or flags & ~@as(u32, 3) != 0) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_MENU, c.Z_MENU_FLAGS) catch |err| return runtime.objectError(err);
command.data.number = id;
command.data.limit = flags;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
}
pub export fn uhdk_menu_popup_async(
handle: ?*c.uhdk_menu,
window: ?*c.uhdk_window,
point: c.uhdk_point,
out: [*c]u64,
tag: u64,
) abi.Status {
if (handle == null or
window == null or
@ -109,7 +115,8 @@ pub export fn uhdk_menu_popup_async(
runtime.abandon(command);
return abi.OOM;
};
command.data.point = point;
command.kind = c.UHDK_REQUEST_MENU_POPUP;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submit(runtime.fromObjectHandle(handle).app, command, tag);
}

263
src/api/session.zig Normal file
View File

@ -0,0 +1,263 @@
//! Main-thread application iterations. Native work runs only outside GL ownership.
const std = @import("std");
const c = @import("native");
const abi = @import("../abi.zig");
const runtime = @import("../runtime.zig");
const Application = @import("../Application.zig");
const app = @import("app.zig");
const windows = @import("windows.zig");
const graphics = @import("graphics.zig");
fn state(session: *c.uhdk_session) *Application {
return @ptrCast(@alignCast(session));
}
fn handle(a: *Application) *c.uhdk_session {
return runtime.toAppHandle(a);
}
pub fn acquire(a: *Application) abi.Status {
if (!a.session_has_gl) return abi.OK;
const window = runtime.fromObjectHandle(a.session_window);
if (window.payload.window.bracket) return abi.OK;
return graphics.acquire(a.session_window);
}
pub fn release(a: *Application) abi.Status {
if (!a.session_has_gl) return abi.OK;
const window = runtime.fromObjectHandle(a.session_window);
if (!window.payload.window.bracket) return abi.OK;
return graphics.release(a.session_window);
}
pub fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status {
const object = runtime.fromObjectHandle(resource);
while (!object.ready) {
if (!object.alive) return if (object.creation_status == abi.OK) abi.UNAVAILABLE else object.creation_status;
if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
}
return abi.OK;
}
fn readyGl(a: *Application, deadline: u64) abi.Status {
const window = runtime.fromObjectHandle(a.session_window);
while (!window.payload.window.gl_ready) {
if (!window.alive) return abi.UNAVAILABLE;
if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
}
return window.payload.window.gl_status;
}
pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_session) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
var opts = std.mem.zeroes(c.uhdk_options);
if (options != null) {
if (!abi.validDescriptor(c.uhdk_options, options)) return abi.INVALID;
opts = options.*;
}
if (opts.render_mode > c.UHDK_RENDER_ON_DEMAND) return abi.INVALID;
if (opts.undecorated != 0 and opts.undecorated != 1) return abi.INVALID;
if (opts.fixed_size != 0 and opts.fixed_size != 1) return abi.INVALID;
if (opts.disable_vsync != 0 and opts.disable_vsync != 1) return abi.INVALID;
if (opts.request_focus != 0 and opts.request_focus != 1) return abi.INVALID;
if (opts.no_opengl != 0 and opts.no_opengl != 1) return abi.INVALID;
if (opts.title.len == 0) opts.title = abi.textSpan("UHDK");
var application: ?*c.uhdk_session = null;
var status = app.create(&opts, &application);
if (status != abi.OK) return status;
const a = runtime.fromAppHandle(application);
var success = false;
defer if (!success) {
_ = release(a);
app.destroy(application);
};
a.session_on_demand = opts.render_mode == c.UHDK_RENDER_ON_DEMAND;
var window = std.mem.zeroes(c.z_window_desc);
window.struct_size = @sizeOf(c.z_window_desc);
window.title = opts.title;
window.flags = if (opts.no_opengl == 0) c.Z_WINDOW_OPENGL else 0;
window.style = .{
.struct_size = @sizeOf(c.uhdk_window_style),
.decorated = 1 - opts.undecorated,
.resizable = 1 - opts.fixed_size,
.reserved = 0,
};
window.content_size = opts.content_size;
if (window.content_size.width == 0) window.content_size.width = 800;
if (window.content_size.height == 0) window.content_size.height = 600;
window.min_size = opts.min_size;
window.max_size = opts.max_size;
if (opts.startup_timeout_ns != 0) a.startup_timeout_ns = opts.startup_timeout_ns;
const deadline = runtime.now(a.io) +| a.startup_timeout_ns;
status = windows.queueCreate(application, &window, &a.session_window);
if (status != abi.OK) return status;
status = ready(a, a.session_window, deadline);
if (status != abi.OK) return status;
if (opts.no_opengl == 0) {
status = graphics.create(a.session_window);
if (status != abi.OK) return status;
status = readyGl(a, deadline);
if (status != abi.OK) return status;
a.session_has_gl = true;
}
status = windows.uhdk_window_set_visible(a.session_window, 1);
if (status != abi.OK) return status;
if (opts.request_focus != 0) {
status = windows.uhdk_window_request_focus(a.session_window);
if (status != abi.OK) return status;
}
runtime.dispatch(application);
c.z_native_pump(0);
if (a.native_error != abi.OK) return a.native_error;
status = acquire(a);
if (status != abi.OK) return status;
if (opts.no_opengl == 0) {
status = graphics.setSwapInterval(a.session_window, 1 - @as(i32, opts.disable_vsync));
if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status;
if (c.z_gl_load(runtime.fromObjectHandle(a.session_window).native, &a.session_gl) == 0) {
return c.UHDK_STATUS_UNSUPPORTED;
}
}
out.* = @ptrCast(a);
success = true;
return abi.OK;
}
pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) c.uhdk_bool {
const a = state(session orelse return 0);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return 0;
if (out == null or a.session_active) {
a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY;
return 0;
}
out.* = std.mem.zeroes(c.uhdk_frame);
if (a.session_status != abi.OK or a.stopped_seen) return 0;
var metrics = std.mem.zeroes(c.uhdk_window_metrics);
metrics.struct_size = @sizeOf(c.uhdk_window_metrics);
_ = windows.uhdk_window_get_metrics(a.session_window, &metrics);
const wait = !a.session_first and (a.session_on_demand or !drawable(metrics));
a.session_status = release(a);
if (a.session_status != abi.OK) return 0;
const poll_status = app.poll(handle(a), if (wait) std.math.maxInt(u64) else 0, &out.*.events);
// Restore GL ownership even after polling fails so cleanup can delete resources.
const acquire_status = acquire(a);
a.session_status = if (poll_status != abi.OK) poll_status else acquire_status;
if (a.session_status != abi.OK) return 0;
a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics);
if (a.session_status != abi.OK) return 0;
out.*.gl = if (a.session_has_gl) &a.session_gl else null;
out.*.metrics = metrics;
a.session_drawable = !a.stopping and drawable(metrics);
out.*.drawable = @intFromBool(a.session_drawable);
a.session_first = false;
a.session_active = true;
return 1;
}
fn drawable(metrics: c.uhdk_window_metrics) bool {
const minimized = if (metrics.observations & c.UHDK_WINDOW_OBSERVE_MINIMIZED != 0)
metrics.minimized != 0
else
metrics.state == c.UHDK_WINDOW_MINIMIZED;
const suspended = metrics.observations & c.UHDK_WINDOW_OBSERVE_SUSPENDED != 0 and metrics.suspended != 0;
return metrics.visible != 0 and metrics.framebuffer_width != 0 and metrics.framebuffer_height != 0 and !minimized and !suspended;
}
pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (!a.session_active) return c.UHDK_STATUS_BUSY;
a.session_active = false;
var status: abi.Status = abi.OK;
if (a.session_drawable and !a.stopping and a.session_has_gl) status = graphics.present(a.session_window);
const end_status = release(a);
const begin_status = if (end_status == abi.OK) acquire(a) else end_status;
a.session_status = if (status != abi.OK) status else begin_status;
return a.session_status;
}
pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return a.session_status;
}
pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions {
const a = state(session orelse return null);
return if (a.session_has_gl) &a.session_gl else null;
}
pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window {
return state(session orelse return null).session_window;
}
pub export fn uhdk_close(session: ?*c.uhdk_session) void {
const a = state(session orelse return);
_ = release(a);
app.destroy(handle(a));
}
pub export fn uhdk_get_gl_proc(session: ?*c.uhdk_session, name: c.uhdk_text, out: [*c]c.uhdk_gl_proc) abi.Status {
const a = state(session orelse return abi.INVALID);
if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.getProc(a.session_window, name, out);
}
pub export fn uhdk_set_vsync(session: ?*c.uhdk_session, enabled: c.uhdk_bool) abi.Status {
const a = state(session orelse return abi.INVALID);
if (enabled != 0 and enabled != 1) return abi.INVALID;
if (!a.session_has_gl) return c.UHDK_STATUS_UNSUPPORTED;
return graphics.setSwapInterval(a.session_window, enabled);
}

142
src/api/tray.zig Normal file
View File

@ -0,0 +1,142 @@
//! Session-owned tray snapshots. Native hosts never borrow application storage.
const std = @import("std");
const c = @import("native");
const abi = @import("../abi.zig");
const runtime = @import("../runtime.zig");
const Resource = @import("../Resource.zig");
const session = @import("session.zig");
fn validMenu(menu: *Resource) bool {
if (menu.payload != .menu or !menu.alive) return false;
for (menu.payload.menu.items) |item| {
if (item.role != c.UHDK_MENU_ROLE_NONE and item.role != c.UHDK_MENU_ROLE_QUIT) return false;
if (item.submenu) |sub| if (!validMenu(runtime.fromObjectHandle(sub))) return false;
}
return true;
}
fn snapshot(object: *Resource, desc: [*c]const c.uhdk_tray_desc) !*Resource.TraySnapshot {
if (!abi.validDescriptor(c.uhdk_tray_desc, desc)) return error.Invalid;
const d = desc.*;
const icon = d.icon;
if (d.reserved != 0 or d.hidden < 0 or d.hidden > 1) return error.Invalid;
if (d.menu_on_primary < 0 or d.menu_on_primary > 1) return error.Invalid;
if (d.template_image < 0 or d.template_image > 1) return error.Invalid;
if (!abi.validText(d.id, true) or d.id.len == 0 or d.id.len > 255) return error.Invalid;
if (!abi.validText(d.title, true) or d.title.len > 4096) return error.Invalid;
if (!abi.validText(d.tooltip, true) or d.tooltip.len > 4096) return error.Invalid;
if (d.menu_on_primary != 0 and d.menu == null) return error.Invalid;
if (!abi.validDescriptor(c.uhdk_image, &d.icon) or icon.reserved != 0) return error.Invalid;
if (icon.width == 0 or icon.height == 0 or icon.width > 512 or icon.height > 512) return error.Invalid;
if (icon.pixels.len != @as(u64, icon.width) * icon.height * 4) return error.Invalid;
if (!abi.validSpan(icon.pixels.ptr, icon.pixels.len)) return error.Invalid;
if (d.menu) |menu| {
const root = runtime.fromObjectHandle(menu);
if (root.app != object.app or !validMenu(root)) return error.Invalid;
}
if (object.payload.tray.snapshot) |old| {
if (!std.mem.eql(u8, abi.textBytes(old.desc.id), abi.textBytes(d.id))) return error.Invalid;
}
{
object.app.lock();
defer object.app.unlock();
var cursor = object.app.objects;
while (cursor) |other| : (cursor = other.next) {
if (other != object and other.alive and other.payload == .tray) {
if (other.payload.tray.snapshot) |s| {
if (std.mem.eql(u8, abi.textBytes(s.desc.id), abi.textBytes(d.id))) return error.Invalid;
}
}
}
}
const s = try object.gpa.create(Resource.TraySnapshot);
errdefer object.gpa.destroy(s);
s.* = .{ .arena = .init(object.gpa), .desc = d };
errdefer s.arena.deinit();
const a = s.arena.allocator();
s.desc.id = abi.textSpan(try a.dupeSentinel(u8, abi.textBytes(d.id), 0));
s.desc.title = abi.textSpan(try a.dupeSentinel(u8, abi.textBytes(d.title), 0));
s.desc.tooltip = abi.textSpan(try a.dupeSentinel(u8, abi.textBytes(d.tooltip), 0));
s.desc.icon.pixels = try abi.copyBytes(a, icon.pixels);
if (d.menu) |menu| runtime.retain(runtime.fromObjectHandle(menu));
return s;
}
pub fn freeSnapshot(object: *Resource, s: *Resource.TraySnapshot) void {
if (s.desc.menu) |menu| runtime.release(runtime.fromObjectHandle(menu));
s.arena.deinit();
object.gpa.destroy(s);
}
pub fn clear(object: *Resource) void {
if (object.payload.tray.snapshot) |s| freeSnapshot(object, s);
object.payload.tray.snapshot = null;
}
fn update(object: *Resource, desc: [*c]const c.uhdk_tray_desc) abi.Status {
if (object.app.session_active) return c.UHDK_STATUS_BUSY;
const next = snapshot(object, desc) catch |err| return runtime.objectError(err);
const released = session.release(object.app);
if (released != abi.OK) {
freeSnapshot(object, next);
return released;
}
const old = object.payload.tray.snapshot;
object.payload.tray.snapshot = next;
const status = c.z_native_tray_update(@ptrCast(object), &next.desc);
if (status != abi.OK) {
object.payload.tray.snapshot = old;
freeSnapshot(object, next);
} else if (old) |s| freeSnapshot(object, s);
const restored = session.acquire(object.app);
if (restored != abi.OK) {
object.app.session_status = restored;
return restored;
}
return status;
}
pub export fn uhdk_tray_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_tray_desc, out: [*c]?*c.uhdk_tray) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (handle == null) return abi.INVALID;
const app = runtime.fromAppHandle(handle);
const ready = runtime.validateMainThreadSessionReady(app);
if (ready != abi.OK) return ready;
if (app.session_active) return c.UHDK_STATUS_BUSY;
const object = runtime.createObject(app, c.Z_KIND_TRAY) catch return abi.OOM;
const status = update(object, desc);
if (status != abi.OK) {
runtime.destroyObject(object);
return status;
}
out.* = @ptrCast(object);
return abi.OK;
}
pub export fn uhdk_tray_update(handle: ?*c.uhdk_tray, desc: [*c]const c.uhdk_tray_desc) abi.Status {
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
if (ready != abi.OK) return ready;
return update(object, desc);
}
pub export fn uhdk_tray_destroy(handle: ?*c.uhdk_tray) abi.Status {
if (handle == null) return abi.OK;
const object = runtime.fromObjectHandle(handle);
const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
if (ready != abi.OK) return ready;
runtime.destroyObject(object);
return abi.OK;
}
pub export fn uhdk_tray_get_state(handle: ?*c.uhdk_tray, out: [*c]c.uhdk_tray_state) abi.Status {
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const ready = runtime.validateMainThreadObjectReady(object, c.Z_KIND_TRAY);
if (ready != abi.OK) return ready;
return abi.writeOutput(c.uhdk_tray_state, out, object.payload.tray.state);
}

View File

@ -4,86 +4,94 @@ const c = @import("native");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
pub export fn uhdk_window_create_async(
handle: ?*c.uhdk_app,
desc: [*c]const c.uhdk_window_desc,
out: [*c]u64,
pub fn queueCreate(
handle: ?*c.uhdk_session,
desc: [*c]const c.z_window_desc,
out: [*c]?*c.uhdk_window,
) abi.Status {
if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc)) return abi.INVALID;
if (handle == null or !abi.validDescriptor(c.z_window_desc, desc)) return abi.INVALID;
if (out == null) return abi.INVALID;
const d = desc.*;
if (!abi.validText(d.title, true) or
!abi.finiteSize(d.content_size) or
d.content_size.width == 0 or
d.content_size.height == 0 or
!abi.finiteSize(d.min_size) or
!abi.finiteSize(d.max_size) or
d.flags & ~@as(u32, 11) != 0) return abi.INVALID;
if ((d.max_size.width != 0 and d.max_size.width < d.min_size.width) or
(d.max_size.height != 0 and d.max_size.height < d.min_size.height)) return abi.INVALID;
if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or
!runtime.fromObjectHandle(d.parent).alive)) return abi.INVALID;
if (d.content_size.width == 0 or d.content_size.height == 0)
return abi.INVALID;
if (!abi.finiteSize(d.content_size) or !abi.finiteSize(d.content_size) or !abi.finiteSize(d.min_size) or !abi.finiteSize(d.max_size))
return abi.INVALID;
if (!validStyle(&d.style) or d.content_size.width == 0 or d.content_size.height == 0 or d.flags & ~@as(u32, c.Z_WINDOW_OPENGL) != 0)
return abi.INVALID;
if ((d.max_size.width != 0 and d.max_size.width < d.min_size.width) or (d.max_size.height != 0 and d.max_size.height < d.min_size.height))
return abi.INVALID;
if (d.parent != null and (runtime.fromObjectHandle(d.parent).app != runtime.fromAppHandle(handle) or !runtime.fromObjectHandle(d.parent).alive))
return abi.INVALID;
const command = runtime.createAppCommand(handle, c.Z_WINDOW) catch |err| return runtime.applicationError(err);
const object = runtime.createObject(runtime.fromAppHandle(handle), c.Z_KIND_WINDOW) catch {
runtime.abandon(command);
return abi.OOM;
};
object.payload.window.parent = if (d.parent) |parent| runtime.fromObjectHandle(parent) else null;
command.data.target = object;
command.data.window = d;
command.kind = c.UHDK_REQUEST_WINDOW;
command.data.window.title = abi.copyText(command.arena.allocator(), d.title) catch {
runtime.abandon(command);
object.alive = false;
return abi.OOM;
};
const status = runtime.submit(runtime.fromAppHandle(handle), command, out);
const status = runtime.submitResource(runtime.fromAppHandle(handle), command);
if (status != abi.OK) object.alive = false;
if (status == abi.OK) out.* = runtime.castHandle(*c.uhdk_window, object);
return status;
}
pub export fn uhdk_window_destroy(handle: ?*c.uhdk_window) void {
if (handle) |_| runtime.destroyObject(runtime.fromObjectHandle(handle));
fn validStyle(style: [*c]const c.uhdk_window_style) bool {
return abi.validDescriptor(c.uhdk_window_style, style) and
(style.*.decorated == 0 or style.*.decorated == 1) and
(style.*.resizable == 0 or style.*.resizable == 1) and
style.*.reserved == 0;
}
pub export fn uhdk_window_set_title_async(
handle: ?*c.uhdk_window,
title: c.uhdk_text,
out: [*c]u64,
) abi.Status {
return runtime.textCommand(handle, c.Z_KIND_WINDOW, c.Z_TITLE, title, out);
pub export fn uhdk_window_set_title(handle: ?*c.uhdk_window, title: c.uhdk_text) abi.Status {
return runtime.textCommandValue(handle, c.Z_KIND_WINDOW, c.Z_TITLE, title);
}
pub export fn uhdk_window_set_size_async(
handle: ?*c.uhdk_window,
size: c.uhdk_size,
out: [*c]u64,
) abi.Status {
pub export fn uhdk_window_set_size(handle: ?*c.uhdk_window, size: c.uhdk_size) abi.Status {
if (!abi.finiteSize(size) or size.width == 0 or size.height == 0) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_SIZE) catch |err| return runtime.objectError(err);
command.data.size = size;
return runtime.submit(runtime.fromObjectHandle(handle).app, command, out);
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
}
pub export fn uhdk_window_set_state_async(
handle: ?*c.uhdk_window,
state: c.uhdk_window_state,
out: [*c]u64,
) abi.Status {
pub export fn uhdk_window_set_state(handle: ?*c.uhdk_window, state: c.uhdk_window_state) abi.Status {
if (state > c.UHDK_WINDOW_FULLSCREEN) return abi.INVALID;
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_STATE, state, out);
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_STATE, state);
}
pub export fn uhdk_window_set_visible_async(
handle: ?*c.uhdk_window,
visible: c.uhdk_bool,
out: [*c]u64,
) abi.Status {
pub export fn uhdk_window_set_visible(handle: ?*c.uhdk_window, visible: c.uhdk_bool) abi.Status {
if (visible != 0 and visible != 1) return abi.INVALID;
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_VISIBLE, @intCast(visible), out);
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_VISIBLE, @intCast(visible));
}
pub export fn uhdk_window_request_focus_async(handle: ?*c.uhdk_window, out: [*c]u64) abi.Status {
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_FOCUS, 0, out);
pub export fn uhdk_window_set_style(
handle: ?*c.uhdk_window,
style: [*c]const c.uhdk_window_style,
) abi.Status {
if (!validStyle(style)) return abi.INVALID;
const command = runtime.createObjectCommand(handle, c.Z_KIND_WINDOW, c.Z_STYLE) catch |err| return runtime.objectError(err);
command.data.style = style.*;
return runtime.submitCommand(runtime.fromObjectHandle(handle).app, command);
}
pub export fn uhdk_window_request_focus(handle: ?*c.uhdk_window) abi.Status {
return runtime.scalarCommandValue(handle, c.Z_KIND_WINDOW, c.Z_FOCUS, 0);
}
pub export fn uhdk_window_get_metrics(
@ -91,9 +99,11 @@ pub export fn uhdk_window_get_metrics(
out: [*c]c.uhdk_window_metrics,
) abi.Status {
if (handle == null) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_WINDOW);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
object.app.lock();
defer object.app.unlock();
return abi.writeOutput(c.uhdk_window_metrics, out, object.payload.window.metrics);
@ -108,9 +118,64 @@ pub export fn uhdk_window_get_native(
out: [*c]c.uhdk_native_window,
) abi.Status {
if (handle == null or out == null or out.*.struct_size < @sizeOf(c.uhdk_native_window)) return abi.INVALID;
const object = runtime.fromObjectHandle(handle);
const status = runtime.checkObject(object, c.Z_KIND_WINDOW);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
c.z_native_handles(object.native, out);
return abi.OK;
}
pub export fn uhdk_window_create(handle: ?*c.uhdk_session, desc: [*c]const c.uhdk_window_desc, out: [*c]?*c.uhdk_window) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc) or desc.*.reserved != 0) return abi.INVALID;
const a = runtime.fromAppHandle(handle);
if (runtime.validateMainThreadSessionReady(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (a.session_active) return c.UHDK_STATUS_BUSY;
const session = @import("session.zig");
const d: c.z_window_desc = .{
.struct_size = @sizeOf(c.z_window_desc),
.flags = 0,
.style = desc.*.style,
.title = desc.*.title,
.content_size = desc.*.content_size,
.min_size = desc.*.min_size,
.max_size = desc.*.max_size,
.parent = desc.*.parent,
};
var status = session.release(a);
if (status != abi.OK) return status;
var window: ?*c.uhdk_window = null;
status = queueCreate(handle, &d, &window);
if (status == abi.OK) status = session.ready(a, window, runtime.now(a.io) +| a.startup_timeout_ns);
if (status != abi.OK and window != null) runtime.destroyObject(runtime.fromObjectHandle(window));
const restored = session.acquire(a);
if (restored != abi.OK) {
a.session_status = restored;
if (status == abi.OK) runtime.destroyObject(runtime.fromObjectHandle(window));
return restored;
}
if (status == abi.OK) out.* = window;
return status;
}
pub export fn uhdk_window_destroy(window: ?*c.uhdk_window) abi.Status {
if (window == null) return abi.OK;
const object = runtime.fromObjectHandle(window);
const status = runtime.validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
if (object.app.session_window == window) return abi.INVALID;
runtime.destroyObject(object);
return abi.OK;
}

View File

@ -89,10 +89,12 @@ pub const BumpArena = struct {
self.pageIndex += 1;
offset = 0;
}
const memory = self.small.getMutable(self.pageIndex)[offset .. offset + len];
self.smallBumpOffset = offset + len;
break :result memory.ptr;
};
self.allocatedBytes += len;
self.allocCount += 1;
return result;
@ -138,24 +140,6 @@ pub const BumpArena = struct {
}
};
test "bump arena initialization" {
var arena = try BumpArena.init(std.testing.allocator, std.testing.io);
defer arena.deinit();
}
test "reset clears usage" {
var arena = try BumpArena.init(std.testing.allocator, std.testing.io);
defer arena.deinit();
const allocator = arena.allocator();
const mem = allocator.alloc(u8, 128) catch unreachable;
defer _ = mem;
try std.testing.expect(arena.usage() >= 128);
arena.reset();
try std.testing.expectEqual(@as(usize, 0), arena.usage());
}
// it's like an normal vector/ arraylist except it never invalidates old pointers.
// and never causes re-allocations. (excepting in the control block, which is just a vector of things)
//
@ -251,6 +235,7 @@ pub fn PagedVectorAdvanced(comptime T: type, comptime growth: usize) type {
pub fn append(self: *@This(), allocator: std.mem.Allocator, value: T) !void {
if (self.currentPage().len == growth) try self.maybeExpand(allocator);
const page = self.currentPage();
self.head = &page.data[page.len];
self.head.* = value;
@ -303,197 +288,60 @@ pub fn PagedVectorAdvanced(comptime T: type, comptime growth: usize) type {
};
}
pub fn PagedVectorUnmanaged(comptime T: type) type {
return PagedVectorAdvanced(T, 1024);
}
test "paged storage preserves values and pointers across growth, removal and reset" {
const gpa = std.testing.allocator;
var vector = try PagedVectorAdvanced(u32, 4).init(gpa);
defer vector.deinit(gpa);
pub fn PagedVector(comptime T: type) type {
return struct {
const VectorType = PagedVectorAdvanced(T, 1024);
try vector.append(gpa, 0);
const first = vector.get(0);
for (1..13) |i| try vector.append(gpa, @intCast(i));
try std.testing.expect(first == vector.get(0));
for (0..13) |i| try std.testing.expectEqual(@as(u32, @intCast(i)), vector.get(i).*);
vector: VectorType,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) !@This() {
return .{
.vector = try VectorType.init(allocator),
.allocator = allocator,
};
}
pub fn deinit(self: *@This()) void {
self.vector.deinit(self.allocator);
}
pub fn appendSlice(self: *@This(), slice: []const T) !void {
try self.vector.appendSlice(self.allocator, slice);
}
pub fn append(self: *@This(), value: T) !void {
try self.vector.append(self.allocator, value);
}
pub fn appendAndGet(self: *@This(), value: T) !*T {
const index = self.len();
try self.append(value);
return self.getMutable(index);
}
pub fn get(self: *const @This(), index: usize) *const T {
return self.vector.get(index);
}
pub fn getMutable(self: *@This(), index: usize) *T {
return self.vector.getMutable(index);
}
pub fn len(self: @This()) usize {
return self.vector.len();
}
pub fn capacity(self: @This()) usize {
return self.vector.capacity();
}
pub fn getStatistics(self: *const @This()) PoolStatistics {
return self.vector.getStatistics();
}
pub fn swapRemove(self: *@This(), index: usize) void {
self.vector.swapRemove(index);
}
pub fn reset(self: *@This()) void {
self.vector.reset(self.allocator);
}
// // retrieves a value, shrinking length by 1
pub fn pop(self: *@This()) !T {
return try self.vector.pop();
}
};
}
test "simple loading multiple pages." {
const TestStruct = struct {
lmao: usize,
};
const allocator = std.testing.allocator;
var vector = try PagedVectorAdvanced(TestStruct, 1024).init(std.testing.allocator);
defer vector.deinit(allocator);
for (0..128) |j| {
try vector.append(allocator, .{ .lmao = j });
}
const ptr = vector.get(0);
const mutable = vector.getMutable(127);
for (0..4096) |i| {
try vector.append(allocator, .{ .lmao = i });
}
// testing that pointers are not invalidated
std.debug.assert(ptr == vector.get(0));
std.debug.assert(mutable == vector.getMutable(127));
std.debug.assert(vector.getMutable(4092) == vector.getMutable(4092));
// 4096 + 128 = 4224 = 4 pages + 128 extra entries
std.debug.assert(vector.pages.items.len == 5);
std.debug.assert(vector.capacity() == 1024 * 5);
std.debug.assert(vector.len() == 128 + 1024 * 4);
// 4092 - 3072 = offset of 1020 in the third page.
const ptr4092 = vector.getMutable(4092);
std.debug.assert(vector.getMutable(4092) == &vector.pages.items[3].data[1020]);
// lets try adding 1024 elements and see if pointers are still preserved.
for (0..1024) |_| {
try vector.append(allocator, .{ .lmao = 0 });
}
std.debug.assert(vector.getMutable(4092) == ptr4092);
std.debug.assert(vector.get(0).lmao == 0);
std.debug.assert(vector.get(1).lmao == 1);
std.debug.assert(vector.get(2).lmao == 2);
// testing the pop() function
std.debug.assert(vector.len() == 128 + 1024 * 5);
_ = try vector.pop();
_ = try vector.pop();
_ = try vector.pop();
// testing the swapRemove Functionality
std.debug.assert(vector.len() == 128 + 1024 * 5 - 3);
// Remove across a page boundary, checking values rather than page layout.
try std.testing.expectEqual(@as(u32, 12), try vector.pop());
vector.swapRemove(1);
std.debug.assert(vector.len() == 128 + 1024 * 5 - 4);
try std.testing.expectEqual(@as(u32, 11), vector.get(1).*);
try std.testing.expectEqual(@as(usize, 11), vector.len());
try std.testing.expectEqual(@as(u32, 0), first.*);
for (0..1024) |_| {
vector.swapRemove(0);
}
std.debug.assert(vector.len() == 128 + 1024 * 5 - 4 - 1024);
}
test "managed version" {
const allocator = std.testing.allocator;
var vec = try PagedVector(struct { lmao: u64 }).init(allocator);
defer vec.deinit();
for (0..8192) |i| {
try vec.append(.{ .lmao = i });
}
std.debug.assert(vec.vector.pages.items.len == 8);
}
test "reset retains pages and clears length" {
const allocator = std.testing.allocator;
var vec = try PagedVectorAdvanced(u32, 4).init(allocator);
defer vec.deinit(allocator);
for (0..10) |i| {
try vec.append(allocator, @intCast(i));
}
try std.testing.expect(vec.pages.items.len > 1);
vec.reset(allocator);
try std.testing.expectEqual(@as(usize, 3), vec.pages.items.len);
try std.testing.expectEqual(@as(usize, 0), vec.len());
try vec.append(allocator, 42);
try std.testing.expectEqual(@as(u32, 42), vec.get(0).*);
vector.reset(gpa);
try std.testing.expectEqual(@as(usize, 0), vector.len());
for (0..13) |_| try vector.append(gpa, 42);
for (0..13) |i| try std.testing.expectEqual(@as(u32, 42), vector.get(i).*);
}
fn exercise(gpa: std.mem.Allocator) !void {
var arena = try BumpArena.init(gpa, std.testing.io);
defer arena.deinit();
const a = arena.allocator();
const first = try a.alloc(u8, 4096);
@memset(first, 17);
_ = try a.alloc(u8, 4096);
_ = try a.alloc(u8, 4096);
_ = try a.alloc(u8, 4093);
// Alignment rounding takes this allocation across the first page boundary.
const aligned = try a.create(u64);
aligned.* = 0x12345678;
try std.testing.expectEqual(@as(usize, 0), @intFromPtr(aligned) % @alignOf(u64));
const OverAligned = struct { value: u8 align(256) };
const over = try a.create(OverAligned);
over.* = .{ .value = 42 };
try std.testing.expectEqual(@as(usize, 0), @intFromPtr(over) % 256);
const large = try a.alloc(u8, 20000);
@memset(large, 29);
for (first) |v| try std.testing.expectEqual(@as(u8, 17), v);
try std.testing.expectEqual(@as(u64, 0x12345678), aligned.*);
arena.reset();
try std.testing.expectEqual(@as(usize, 0), arena.usage());
const reused = try a.alloc(u8, 4096);
try std.testing.expectEqual(@intFromPtr(first.ptr), @intFromPtr(reused.ptr));
@memset(reused, 31);
for (0..12) |_| _ = try a.alloc(u8, 4096);
arena.reset();
for (0..12) |_| _ = try a.alloc(u8, 4096);
@ -507,13 +355,16 @@ test "bump arena failed page allocation can be retried" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
var arena = try BumpArena.init(failing.allocator(), std.testing.io);
defer arena.deinit();
const a = arena.allocator();
for (0..4) |_| _ = try a.alloc(u8, 4096);
const before = arena.usage();
failing.fail_index = failing.alloc_index;
try std.testing.expectError(error.OutOfMemory, a.alloc(u8, 4096));
try std.testing.expectEqual(before, arena.usage());
failing.fail_index = std.math.maxInt(usize);
const memory = try a.alloc(u8, 4096);
@memset(memory, 7);
try std.testing.expectEqual(before + 4096, arena.usage());

View File

@ -4,12 +4,47 @@ const c = @import("native");
const abi = @import("abi.zig");
const runtime = @import("runtime.zig");
export fn z_emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void {
export fn z_tray_desc(handle: ?*c.uhdk_tray) [*c]const c.uhdk_tray_desc {
return &runtime.fromObjectHandle(handle).payload.tray.snapshot.?.desc;
}
export fn z_tray_state(handle: ?*c.uhdk_tray, available: c.uhdk_bool, status: c.uhdk_status) void {
const object = runtime.fromObjectHandle(handle);
if (!object.alive) return;
const state = &object.payload.tray.state;
if (state.available == available and state.status == status) return;
state.available = available;
state.status = status;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_TRAY_STATE;
event.data.tray_state = .{ .tray = handle, .state = state.* };
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_tray_activate(handle: ?*c.uhdk_tray, activation: c.uhdk_tray_activation) void {
const object = runtime.fromObjectHandle(handle);
if (!object.alive) return;
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_TRAY_ACTIVATE;
event.data.tray = .{ .tray = handle, .activation = activation };
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_tray_command(handle: ?*c.uhdk_tray, item: [*c]const c.uhdk_menu_item) void {
const object = runtime.fromObjectHandle(handle);
if (!object.alive or item == null or item.*.flags & (c.UHDK_MENU_DISABLED | c.UHDK_MENU_SEPARATOR) != 0 or item.*.submenu != null) return;
var event = std.mem.zeroes(c.z_event);
event.type = if (item.*.role == c.UHDK_MENU_ROLE_QUIT) c.UHDK_EVENT_QUIT_REQUESTED else c.UHDK_EVENT_MENU_COMMAND;
event.data.menu = .{ .command_id = item.*.command_id, .tray = handle };
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
runtime.emit(handle, event);
}
export fn z_complete(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
id: u64,
status: abi.Status,
result: [*c]const c.z_request_result,
@ -29,7 +64,7 @@ export fn z_object_kind(handle: ?*anyopaque) u32 {
return runtime.fromObjectHandle(handle).kind();
}
export fn z_object_app(handle: ?*anyopaque) ?*c.uhdk_app {
export fn z_object_app(handle: ?*anyopaque) ?*c.uhdk_session {
return runtime.toAppHandle(runtime.fromObjectHandle(handle).app);
}
@ -38,6 +73,7 @@ export fn z_metrics(handle: ?*c.uhdk_window, value: [*c]const c.uhdk_window_metr
object.app.lock();
object.payload.window.metrics = value.*;
object.app.unlock();
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_WINDOW_METRICS;
event.window = handle;
@ -45,11 +81,12 @@ export fn z_metrics(handle: ?*c.uhdk_window, value: [*c]const c.uhdk_window_metr
c.z_emit(runtime.toAppHandle(object.app), &event);
}
export fn z_preferences(handle: ?*c.uhdk_app, value: [*c]const c.uhdk_preferences) void {
export fn z_preferences(handle: ?*c.uhdk_session, value: [*c]const c.uhdk_preferences) void {
const application = runtime.fromAppHandle(handle);
application.lock();
application.preferences = value.*;
application.unlock();
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_PREFERENCES_CHANGED;
event.data.preferences = value.*;
@ -68,12 +105,14 @@ export fn z_file_init(
object.payload.file.native_path = arena.dupe(u8, abi.bytes(path)) catch return abi.OOM;
if (@import("builtin").os.tag == .windows) {
if (path.len % 2 != 0) return abi.INVALID;
const wide = arena.alloc(u16, @intCast(path.len / 2)) catch return abi.OOM;
@memcpy(std.mem.sliceAsBytes(wide), abi.bytes(path));
object.payload.file.path = std.unicode.wtf16LeToWtf8AllocZ(arena, wide) catch return abi.OOM;
} else {
object.payload.file.path = arena.dupeZ(u8, abi.bytes(path)) catch return abi.OOM;
object.payload.file.path = arena.dupeSentinel(u8, abi.bytes(path), 0) catch return abi.OOM;
}
object.payload.file.uri = arena.dupe(u8, abi.textBytes(uri)) catch return abi.OOM;
object.payload.file.display = arena.dupe(u8, abi.textBytes(display)) catch return abi.OOM;
object.native = grant;
@ -81,7 +120,7 @@ export fn z_file_init(
}
export fn z_file_from_url(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
path: c.uhdk_bytes,
grant: ?*anyopaque,
) ?*c.uhdk_file {
@ -90,6 +129,7 @@ export fn z_file_from_url(
object.alive = false;
return null;
}
return runtime.castHandle(*c.uhdk_file, object);
}
@ -104,6 +144,15 @@ export fn z_menu_items(handle: ?*c.uhdk_menu, len: [*c]u64) [*c]const c.uhdk_men
return object.payload.menu.items.ptr;
}
export fn z_tick(handle: ?*c.uhdk_app) void {
runtime.tick(handle);
export fn z_dispatch(handle: ?*c.uhdk_session) void {
runtime.dispatch(handle);
}
export fn z_native_failed(handle: ?*c.uhdk_session, status: abi.Status) void {
const app = runtime.fromAppHandle(handle);
app.lock();
app.native_error = status;
app.stopping = true;
app.notify();
app.unlock();
}

View File

@ -4,10 +4,34 @@ const Application = @import("Application.zig");
const runtime = @import("runtime.zig");
const abi = @import("abi.zig");
test "function key policy holds through repeats and release in both directions" {
const suppress = c.z_function_key_suppress;
const native = c.UHDK_FUNCTION_KEYS_NATIVE;
const application = c.UHDK_FUNCTION_KEYS_APPLICATION;
var state = std.mem.zeroes(c.z_function_keys);
var key: u32 = c.UHDK_KEY_F1;
while (key <= c.UHDK_KEY_F24) : (key += 1) {
// Switching to native while an application-owned press is held must
// not leak its repeats or release into native menu handling.
try std.testing.expect(suppress(&state, application, key, 0, 1) != 0);
try std.testing.expect(suppress(&state, native, key, 0, 1) != 0);
try std.testing.expect(suppress(&state, native, key, 0, 0) != 0);
// Conversely, a native key-down must retain native key-up handling so
// DefWindowProc can complete its F10 menu state, despite a policy change.
try std.testing.expect(suppress(&state, native, key, 0, 1) == 0);
try std.testing.expect(suppress(&state, application, key, 0, 1) == 0);
try std.testing.expect(suppress(&state, application, key, 0, 0) == 0);
}
try std.testing.expectEqual(@as(u32, 0), state.down);
try std.testing.expectEqual(@as(u32, 0), state.suppress);
}
fn destroyApplication(application: *Application) void {
runtime.destroyEvents(application.pending_head);
runtime.destroyEvents(application.published);
application.scratch.deinit();
const gpa = application.gpa;
gpa.free(application.name);
application.* = undefined;
@ -17,8 +41,10 @@ fn destroyApplication(application: *Application) void {
fn allocationLifecycle(gpa: std.mem.Allocator) !void {
const application = try Application.create(gpa, std.testing.io, "test");
defer destroyApplication(application);
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
const command = try runtime.createCommand(application, c.Z_CLIP_WRITE, file);
defer runtime.abandon(command);
command.data.text = try abi.copyText(command.arena.allocator(), .{
@ -33,46 +59,6 @@ test "all request construction failures release partial ownership" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationLifecycle, .{});
}
test "publication copies text and preserves batches across ordinary calls" {
const application = try Application.create(std.testing.allocator, std.testing.io, "events");
defer destroyApplication(application);
var source = [_]u8{ 'h', 'i' };
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_TEXT_COMMIT;
event.data.text.text = .{ .ptr = &source, .len = source.len };
runtime.emit(runtime.toAppHandle(application), &event);
@memset(&source, '?');
const published = application.pending_head.?;
try std.testing.expectEqualStrings("hi", abi.textBytes(published.event.data.text.text));
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
try std.testing.expect(published.next != null);
try std.testing.expect(published.next.?.next == null);
try std.testing.expectEqualStrings("hi", abi.textBytes(published.event.data.text.text));
}
test "accepted request gets one terminal result when cancellation wins" {
const application = try Application.create(std.testing.allocator, std.testing.io, "requests");
defer destroyApplication(application);
application.running = true;
application.worker_id = std.Thread.getCurrentId();
const command = try runtime.createCommand(application, c.Z_CLIP_READ, null);
var request_id: u64 = 0;
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OK), runtime.submit(application, command, &request_id));
try std.testing.expect(request_id != 0);
application.lock();
command.cancelled = true;
application.unlock();
runtime.tick(runtime.toAppHandle(application));
try std.testing.expect(application.requests == null);
try std.testing.expect(application.queue_head == null);
const event = application.pending_head.?;
try std.testing.expect(event.next == null);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_REQUEST_DONE), event.event.type);
try std.testing.expectEqual(request_id, event.event.data.request.id);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_CANCELLED), event.event.data.request.status);
}
test "invalid UTF-8 spans and partial scalar ranges are rejected" {
try std.testing.expect(!abi.validText(.{ .ptr = null, .len = 1 }, false));
try std.testing.expect(!abi.validText(.{ .ptr = "\xff", .len = 1 }, false));
@ -81,54 +67,39 @@ test "invalid UTF-8 spans and partial scalar ranges are rejected" {
try std.testing.expect(abi.boundary("a😀b", 5));
}
test "tick statistics exclude blocked time" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "stats");
defer destroyApplication(application);
application.running = true;
application.worker_id = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
const wall_start = runtime.now(application.io);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_begin_tick(handle));
try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(40), .clock = .awake }).sleep(application.io);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_end_tick(handle));
const wall_time = runtime.now(application.io) - wall_start;
var stats = std.mem.zeroes(c.uhdk_app_stats);
stats.struct_size = @sizeOf(c.uhdk_app_stats);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_get_stats(handle, &stats));
try std.testing.expectEqual(@as(u64, 1), stats.tick_count);
try std.testing.expect(stats.tick_time_ns < wall_time / 2);
}
test "public payload scratch lifetime empty polls and resource pins" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "payloads");
defer destroyApplication(application);
application.running = true;
application.worker_id = std.Thread.getCurrentId();
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
var handles = [_]?*c.uhdk_file{@ptrCast(file)};
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_OPEN_FILES;
event.data.files = .{ .ptr = &handles, .len = 1 };
runtime.emit(handle, &event);
try std.testing.expectEqual(@as(usize, 2), file.refs);
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch));
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 1), batch.len);
try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_file_list)), batch.ptr[0].data_size);
const payload: *const c.uhdk_file_list = @ptrCast(@alignCast(batch.ptr[0].data.?));
try std.testing.expectEqual(@intFromPtr(file), @intFromPtr(payload.ptr[0].?));
try std.testing.expectEqual(@as(usize, 2), file.refs);
// Invalid calls must not reset a borrow. Valid empty polls must release it.
try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.uhdk_app_poll_events(handle, 0, null));
try std.testing.expectEqual(@as(abi.Status, abi.INVALID), app_api.poll(handle, 0, null));
try std.testing.expectEqual(@as(u64, 1), payload.len);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch));
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
try std.testing.expectEqual(@as(usize, 1), file.refs);
try std.testing.expectEqual(@as(usize, 0), application.scratch.usage());
}
test "poll allocation failure keeps queued terminal completion retryable" {
@ -137,85 +108,218 @@ test "poll allocation failure keeps queued terminal completion retryable" {
const application = try Application.create(failing.allocator(), std.testing.io, "retry");
defer destroyApplication(application);
application.running = true;
application.worker_id = std.Thread.getCurrentId();
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
var bytes = [_]u8{42} ** 20000;
var bytes: [20000]u8 = @splat(42);
var event = std.mem.zeroes(c.z_event);
event.type = c.UHDK_EVENT_REQUEST_DONE;
event.data.request = .{ .id = 123, .kind = c.UHDK_REQUEST_FILE_READ, .status = abi.OK, .diagnostic = .{ .ptr = null, .len = 0 }, .value = .{ .bytes = .{ .ptr = &bytes, .len = bytes.len } } };
event.data.request = .{ .tag = 123, .kind = c.UHDK_REQUEST_FILE_READ, .status = abi.OK, .diagnostic = .{ .ptr = null, .len = 0 }, .value = .{ .bytes = .{ .ptr = &bytes, .len = bytes.len } } };
runtime.emit(handle, &event);
@memset(&bytes, 0);
failing.fail_index = failing.alloc_index;
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.uhdk_app_poll_events(handle, 0, &batch));
try std.testing.expectEqual(@as(abi.Status, abi.OOM), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
try std.testing.expect(application.pending_head != null);
failing.fail_index = std.math.maxInt(usize);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch));
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, 123));
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 1), batch.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(batch.ptr[0].data.?));
try std.testing.expectEqual(@as(u64, 123), result.id);
try std.testing.expectEqual(@as(u64, 123), result.tag);
const data: *const c.uhdk_bytes = @ptrCast(@alignCast(result.data.?));
try std.testing.expectEqual(@as(u64, bytes.len), data.len);
for (data.ptr[0..@intCast(data.len)]) |b| try std.testing.expectEqual(@as(u8, 42), b);
try std.testing.expect(application.pending_head == null);
// Producer payload storage has been freed; the public copy is in scratch.
try std.testing.expectEqual(@as(usize, 0), application.published.?.arena.queryCapacity());
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.uhdk_app_poll_events(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
}
test "READY precedes native startup events without being published on failed startup" {
const application = try Application.create(std.testing.allocator, std.testing.io, "startup");
defer destroyApplication(application);
const failed = try runtime.prepareReady(application);
try std.testing.expect(application.pending_head == null);
runtime.destroyEvent(failed);
const ready = try runtime.prepareReady(application);
runtime.simpleEvent(application, c.UHDK_EVENT_PREFERENCES_CHANGED);
const preferences = application.pending_head.?;
runtime.publishReady(application, ready);
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_READY), application.pending_head.?.event.type);
try std.testing.expect(ready.next == preferences);
try std.testing.expect(ready.event.time_ns <= preferences.event.time_ns);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), preferences.next.?.event.type);
try std.testing.expect(application.pending_tail == preferences.next);
try std.testing.expectEqual(@as(abi.Status, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 0), batch.len);
}
test {
_ = @import("linux/WindowState.zig");
}
test "desktop edit defaults preserve modifiers and selection intent" {
const ctrl = c.UHDK_MOD_CONTROL;
const shift = c.UHDK_MOD_SHIFT;
const cases = [_][3]u32{
.{ c.UHDK_KEY_BACKSPACE, ctrl, c.UHDK_EDIT_DELETE_WORD_BACKWARD },
.{ c.UHDK_KEY_DELETE, ctrl, c.UHDK_EDIT_DELETE_WORD_FORWARD },
.{ c.UHDK_KEY_DELETE, shift, c.UHDK_EDIT_CUT },
.{ c.UHDK_KEY_INSERT, ctrl, c.UHDK_EDIT_COPY },
.{ c.UHDK_KEY_INSERT, shift, c.UHDK_EDIT_PASTE },
.{ 'v', ctrl, c.UHDK_EDIT_PASTE },
.{ 'z', ctrl | shift, c.UHDK_EDIT_REDO },
.{ c.UHDK_KEY_UP, ctrl | shift, c.UHDK_EDIT_PARAGRAPH_START },
.{ c.UHDK_KEY_DOWN, ctrl, c.UHDK_EDIT_PARAGRAPH_END },
.{ c.UHDK_KEY_PAGE_UP, shift, c.UHDK_EDIT_PAGE_UP },
.{ c.UHDK_KEY_PAGE_DOWN, 0, c.UHDK_EDIT_PAGE_DOWN },
.{ c.UHDK_KEY_TAB, shift, c.UHDK_EDIT_BACKTAB },
.{ c.UHDK_KEY_ENTER, shift, c.UHDK_EDIT_LINE_BREAK },
.{ c.UHDK_KEY_ESCAPE, 0, c.UHDK_EDIT_CANCEL },
.{ c.UHDK_KEY_TAB, ctrl, 0 },
.{ c.UHDK_KEY_PAGE_DOWN, ctrl, 0 },
.{ 'v', ctrl | shift, 0 },
};
for (cases) |item| {
try std.testing.expectEqual(item[2], c.z_edit_key(item[0], item[1]));
try std.testing.expectEqual(@as(u32, 0), c.z_edit_key(item[0], item[1] | c.UHDK_MOD_ALT));
try std.testing.expectEqual(@as(u32, 0), c.z_edit_key(item[0], item[1] | c.UHDK_MOD_SUPER));
const IoGate = struct {
io: std.Io,
entered: std.Io.Event = .unset,
release: std.Io.Event = .unset,
fn block(context: *anyopaque) void {
const self: *IoGate = @ptrCast(@alignCast(context));
self.entered.set(self.io);
self.release.waitUncancelable(self.io);
}
};
test "blocked file execution leaves event polling live and cancellation drains once" {
const app_api = @import("api/app.zig");
{
const application = try Application.create(std.testing.allocator, std.testing.io, "io gate");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
var gate: IoGate = .{ .io = application.io };
application.io_test_hook = .{ .context = &gate, .before = IoGate.block };
const file = try runtime.createObject(application, c.Z_KIND_FILE);
defer runtime.release(file);
const worker = try std.Thread.spawn(.{}, runtime.ioMain, .{application});
defer {
gate.release.set(application.io);
application.lock();
application.io_exit = true;
application.io_available.set(application.io);
application.unlock();
worker.join();
}
const command = try runtime.createCommand(application, abi.IO_INFO, file);
command.kind = c.UHDK_REQUEST_FILE_INFO;
const id: u64 = 42;
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, command, id));
runtime.dispatch(handle);
try gate.entered.waitTimeout(application.io, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } });
runtime.simpleEvent(application, c.UHDK_EVENT_WAKE);
var events: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_WAKE), events.ptr[0].type);
// Shutdown is requested while the OS operation is still blocked.
app_api.uhdk_quit(handle);
runtime.dispatch(handle);
try std.testing.expect(!application.stopped_sent);
gate.release.set(application.io);
const deadline = runtime.now(application.io) + 5 * std.time.ns_per_s;
while (true) {
runtime.dispatch(handle);
application.lock();
const done = application.requests == null;
application.unlock();
if (done) break;
try std.testing.expect(runtime.now(application.io) < deadline);
try (std.Io.Clock.Duration{ .raw = .fromMilliseconds(1), .clock = .awake }).sleep(application.io);
}
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 2), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(id, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_STOPPED), events.ptr[1].type);
try std.testing.expectEqual(@as(u32, abi.UNAVAILABLE), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(usize, 0), application.io_pending);
}
try std.testing.expect(c.z_edit_extends_selection(c.UHDK_EDIT_WORD_LEFT, shift) != 0);
try std.testing.expect(c.z_edit_extends_selection(c.UHDK_EDIT_PAGE_DOWN, shift) != 0);
for ([_]u32{ c.UHDK_EDIT_BACKTAB, c.UHDK_EDIT_LINE_BREAK, c.UHDK_EDIT_CUT, c.UHDK_EDIT_DELETE_WORD_FORWARD, c.UHDK_EDIT_REDO }) |command|
try std.testing.expectEqual(@as(c_int, 0), c.z_edit_extends_selection(command, shift));
}
test "fatal native failure persists and wakes subsequent polls" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "native failure");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
c.z_native_failed(handle, c.UHDK_STATUS_OS_ERROR);
var events: c.uhdk_event_list = undefined;
for (0..2) |_| try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_OS_ERROR), app_api.poll(handle, std.math.maxInt(u64), &events));
}
test "caller tags remain reserved until delivery and isolate late native completions" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "tags");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const handle = runtime.toAppHandle(application);
const tag = std.math.maxInt(u64); // The full nonzero caller range is available.
const zero = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, abi.INVALID), runtime.submit(application, zero, 0));
try std.testing.expect(application.requests == null);
const first = try runtime.createCommand(application, c.Z_CLIP_READ, null);
first.kind = c.UHDK_REQUEST_CLIPBOARD_TEXT;
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, first, tag));
const old_native_id = first.id;
const duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, duplicate, tag));
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle);
const queued_duplicate = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_BUSY), runtime.submit(application, queued_duplicate, tag));
try std.testing.expectEqual(@as(u32, c.UHDK_STATUS_NOT_FOUND), app_api.uhdk_request_cancel(handle, tag));
var events: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
const result: *const c.uhdk_request_result = @ptrCast(@alignCast(events.ptr[0].data.?));
try std.testing.expectEqual(tag, result.tag);
try std.testing.expectEqual(@as(u32, abi.CANCELLED), result.status);
const second = try runtime.createCommand(application, c.Z_CLIP_READ, null);
try std.testing.expectEqual(@as(u32, abi.OK), runtime.submit(application, second, tag));
try std.testing.expect(second.id != old_native_id);
runtime.complete(handle, old_native_id, abi.OK, null);
try std.testing.expect(application.requests == second);
try std.testing.expect(application.pending_head == null);
try std.testing.expectEqual(@as(u32, abi.OK), app_api.uhdk_request_cancel(handle, tag));
runtime.dispatch(handle);
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &events));
try std.testing.expectEqual(@as(u64, 1), events.len);
}
test "cycle end markers survive public event batching" {
const app_api = @import("api/app.zig");
const application = try Application.create(std.testing.allocator, std.testing.io, "cycles");
defer destroyApplication(application);
application.running = true;
application.main_thread = std.Thread.getCurrentId();
const window = try runtime.createObject(application, c.Z_KIND_WINDOW);
defer {
window.arena.deinit();
application.gpa.destroy(window);
}
const handle = runtime.toAppHandle(application);
var event = std.mem.zeroes(c.z_event);
event.window = runtime.castHandle(*c.uhdk_window, window);
event.type = c.UHDK_EVENT_POINTER_BUTTON;
event.data.pointer.button = c.UHDK_BUTTON_PRIMARY;
event.data.pointer.pressed = 1;
runtime.emit(handle, &event);
event.data.pointer.pressed = 0;
runtime.emit(handle, &event);
var batch: c.uhdk_event_list = undefined;
try std.testing.expectEqual(@as(u32, abi.OK), app_api.poll(handle, 0, &batch));
try std.testing.expectEqual(@as(u64, 3), batch.len);
try std.testing.expect(batch.ptr[0].cycle_id != 0);
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[1].cycle_id);
try std.testing.expectEqual(batch.ptr[0].cycle_id, batch.ptr[2].cycle_id);
try std.testing.expectEqual(@as(u32, c.UHDK_EVENT_CYCLE_END), batch.ptr[2].type);
try std.testing.expectEqual(@as(u64, @sizeOf(c.uhdk_cycle_end_event)), batch.ptr[2].data_size);
const ending: *const c.uhdk_cycle_end_event = @ptrCast(@alignCast(batch.ptr[2].data.?));
try std.testing.expectEqual(@as(u32, c.UHDK_CYCLE_COMPLETED), ending.reason);
}

45
src/function_keys.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef UHDK_PRIVATE_FUNCTION_KEYS_H
#define UHDK_PRIVATE_FUNCTION_KEYS_H
#include "uhdk.h"
/* Windows fallback must see a consistent down/up pair. In particular, changing
* policy between F10 down and up must not leave DefWindowProc's menu flag armed.
* Keep this state independent of the OS so the transition rules can be tested
* without a desktop. Zero initialization and focus loss clear held state. */
typedef struct z_function_keys {
uint32_t down;
uint32_t suppress;
} z_function_keys;
static inline int z_function_key_suppress(
z_function_keys *state,
uhdk_function_key_policy policy,
uhdk_key key,
uhdk_modifier_flags modifiers,
int pressed
) {
if (key < UHDK_KEY_F1 || key > UHDK_KEY_F24)
return 0;
uint32_t bit = 1u << (key - UHDK_KEY_F1);
int suppress;
if (state->down & bit) {
suppress = (state->suppress & bit) != 0;
} else {
suppress =
policy == UHDK_FUNCTION_KEYS_APPLICATION &&
!(modifiers & (UHDK_MOD_SHIFT | UHDK_MOD_CONTROL | UHDK_MOD_ALT | UHDK_MOD_SUPER));
if (pressed) {
state->down |= bit;
if (suppress)
state->suppress |= bit;
else
state->suppress &= ~bit;
}
}
if (!pressed) {
state->down &= ~bit;
state->suppress &= ~bit;
}
return suppress;
}
#endif

21
src/gl_loader.c Normal file
View File

@ -0,0 +1,21 @@
/* Private GLAD implementation: never collide with a consumer's own loader. */
#define gladLoadGLContextUserPtr z_gladLoadGLContextUserPtr
#define gladLoadGLContext z_gladLoadGLContext
#define UHDK_ENABLE_OPENGL
#define GLAD_GL_IMPLEMENTATION
#include "glad/gl.h"
#undef GLAD_GL_IMPLEMENTATION
#include "native.h"
#include <string.h>
static GLADapiproc resolve(void *user, const char *name) {
uhdk_gl_proc proc = NULL;
uhdk_text symbol = {name, strlen(name)};
if (z_native_gl_proc(user, symbol, &proc) != UHDK_STATUS_OK)
return NULL;
return (GLADapiproc)proc;
}
int32_t z_gl_load(void *context, uhdk_gl_functions *functions) {
return gladLoadGLContextUserPtr(functions, resolve, context) && functions->VERSION_3_3;
}

View File

@ -1,3 +0,0 @@
/* Implementation for the vendored GLAD 3.3 core header. */
#define GLAD_GL_IMPLEMENTATION
#include "glad/gl.h"

View File

@ -1,23 +1,52 @@
//! Fixed 16px menu font and a clipped, opaque software canvas. No runtime font
//! parsing, allocation, GPU work, or dependency on an application's renderer.
//! Fixed 16px menu font and a clipped, opaque software canvas. The packed glyphs
//! decode directly from embedded data without allocation, GPU work, or a parser.
const std = @import("std");
const data = @embedFile("font/roboto-16.bin");
fn word(offset: usize) u32 {
return std.mem.readInt(u32, data[offset..][0..4], .little);
const data = @embedFile("font/roboto-16.fontatlas");
fn word(offset: usize) u16 {
return std.mem.readInt(u16, data[offset..][0..2], .little);
}
const count = word(4);
const Glyph = struct { offset: usize, width: u8, height: u8, x: i8, y: i8, advance: u8 };
const fallback = word(6);
const Glyph = struct {
offset: usize,
packed_size: usize,
width: u8,
height: u8,
x: i8,
y: i8,
advance: u8,
};
fn record(index: usize) Glyph {
const offset = 8 + index * 12;
return .{
.offset = word(offset + 2),
.packed_size = word(offset + 4),
.width = data[offset + 6],
.height = data[offset + 7],
.x = @bitCast(data[offset + 8]),
.y = @bitCast(data[offset + 9]),
.advance = data[offset + 10],
};
}
fn glyph(codepoint: u21) Glyph {
var lo: usize = 0;
var hi: usize = count;
while (lo < hi) {
const mid = (lo + hi) / 2;
const key = word(8 + mid * 16);
if (key < codepoint) lo = mid + 1 else hi = mid;
if (codepoint <= std.math.maxInt(u16)) {
while (lo < hi) {
const mid = (lo + hi) / 2;
const key = word(8 + mid * 12);
if (key < codepoint) lo = mid + 1 else hi = mid;
}
if (lo < count and word(8 + lo * 12) == codepoint) return record(lo);
}
const record = 8 + (if (lo < count and word(8 + lo * 16) == codepoint) lo else count - 1) * 16;
return .{ .offset = word(record + 4), .width = data[record + 8], .height = data[record + 9], .x = @bitCast(data[record + 10]), .y = @bitCast(data[record + 11]), .advance = data[record + 12] };
return record(fallback);
}
pub fn width(text: []const u8) i32 {
var it = std.unicode.Utf8View.initUnchecked(text).iterator();
var result: i32 = 0;
@ -25,8 +54,10 @@ pub fn width(text: []const u8) i32 {
result += glyph(cp).advance;
if (result >= 1024) break; // Menus constrain/ellipsize long labels.
}
return result;
}
pub const Canvas = struct {
pixels: []u32,
width: i32,
@ -38,27 +69,60 @@ pub const Canvas = struct {
const x1 = std.math.clamp(x + w, 0, self.width) * self.scale;
const y1 = std.math.clamp(y + h, 0, self.height) * self.scale;
if (x1 <= x0 or y1 <= y0) return;
var row = y0;
while (row < y1) : (row += 1) {
const offset: usize = @intCast(row * self.width * self.scale);
@memset(self.pixels[offset + @as(usize, @intCast(x0)) .. offset + @as(usize, @intCast(x1))], color | 0xff000000);
}
}
fn pixel(self: Canvas, x: i32, y: i32, color: u32, alpha: u32) void {
if (x < 0 or y < 0 or x >= self.width or y >= self.height or alpha == 0) return;
const index: usize = @intCast((y * self.width * self.scale + x) * self.scale);
const background = self.pixels[index];
var blended: u32 = 0xff000000;
inline for (.{ 0, 8, 16 }) |shift| {
blended |= ((((color >> shift) & 255) * alpha + ((background >> shift) & 255) * (255 - alpha) + 127) / 255) << shift;
}
self.rect(x, y, 1, 1, blended);
}
fn drawGlyph(self: Canvas, value: Glyph, x: i32, baseline: i32, color: u32) void {
for (0..value.height) |row| for (0..value.width) |column| {
self.pixel(x + value.x + @as(i32, @intCast(column)), baseline + value.y + @as(i32, @intCast(row)), color, data[value.offset + row * value.width + column]);
};
if (value.width == 0) return;
const encoded = data[value.offset..][0..value.packed_size];
const pixel_count: usize = @as(usize, value.width) * value.height;
var byte_index: usize = 0;
var pixel_index: usize = 0;
while (byte_index < encoded.len and pixel_index < pixel_count) {
const control = encoded[byte_index];
byte_index += 1;
const run: usize = @as(usize, control & 0x7f) + 1;
if (control & 0x80 != 0) {
pixel_index += run * 2;
continue;
}
for (encoded[byte_index..][0..run]) |pair| {
inline for (.{ pair & 0x0f, pair >> 4 }) |coverage| {
if (pixel_index < pixel_count and coverage != 0) {
const column = pixel_index % value.width;
const row = pixel_index / value.width;
self.pixel(x + value.x + @as(i32, @intCast(column)), baseline + value.y + @as(i32, @intCast(row)), color, @as(u32, coverage) * 17);
}
pixel_index += 1;
}
}
byte_index += run;
}
}
pub fn text(self: Canvas, value: []const u8, x: i32, baseline: i32, limit: i32, color: u32) void {
var it = std.unicode.Utf8View.initUnchecked(value).iterator();
var cursor = x;
@ -70,23 +134,44 @@ pub const Canvas = struct {
if (limit >= ellipsis.advance) self.drawGlyph(ellipsis, cursor, baseline, color);
return;
}
self.drawGlyph(g, cursor, baseline, color);
cursor += g.advance;
}
}
};
test "bitmap bounds, coverage and clipping" {
try std.testing.expectEqualStrings("UF16", data[0..4]);
var previous: u32 = 0;
try std.testing.expectEqualStrings("FAP1", data[0..4]);
try std.testing.expect(fallback < count);
var previous: u16 = 0;
for (0..count) |i| {
const cp = word(8 + i * 16);
const cp = word(8 + i * 12);
try std.testing.expect(cp > previous);
previous = cp;
const g = glyph(@intCast(cp));
try std.testing.expect(g.offset + @as(usize, g.width) * g.height <= data.len);
try std.testing.expect(g.offset + g.packed_size <= data.len);
var input: usize = 0;
var decoded_bytes: usize = 0;
while (input < g.packed_size) {
const control = data[g.offset + input];
input += 1;
const run: usize = @as(usize, control & 0x7f) + 1;
decoded_bytes += run;
if (control & 0x80 == 0) input += run;
try std.testing.expect(input <= g.packed_size);
}
try std.testing.expectEqual((@as(usize, g.width) * g.height + 1) / 2, decoded_bytes);
}
try std.testing.expectEqual(@as(u32, 0xfffd), previous);
try std.testing.expectEqual(width("<EFBFBD>"), width("漢"));
try std.testing.expectEqual(@as(u16, '~'), previous);
try std.testing.expectEqual(width("?"), width("漢"));
var pixels: [64 * 32]u32 = @splat(0xff000000);
const canvas: Canvas = .{ .pixels = &pixels, .width = 64, .height = 32, .scale = 1 };
canvas.text("Roboto café", -2, 17, 60, 0xffffff);

View File

@ -1,5 +1,6 @@
//! Small typed D-Bus message builder/parser. No GLib, process spawning, or
//! synchronous method calls. libdbus owns message storage and the transport.
const std = @import("std");
const c = @import("linux_c");
pub const Error = error{OutOfMemory};
@ -8,69 +9,87 @@ pub const Message = c.DBusMessage;
pub fn method(destination: [*:0]const u8, path: [*:0]const u8, interface: [*:0]const u8, member: [*:0]const u8) Error!*Message {
return c.z_dbus_message_new_method_call.?(destination, path, interface, member) orelse error.OutOfMemory;
}
pub fn append(message: *Message) Iter {
var i: Iter = undefined;
c.z_dbus_message_iter_init_append.?(message, &i);
return i;
}
pub fn parse(message: *Message) Iter {
var i: Iter = std.mem.zeroes(Iter);
_ = c.z_dbus_message_iter_init.?(message, &i);
return i;
}
pub fn basic(i: *Iter, type_: c_int, value: anytype) Error!void {
var v = value;
if (c.z_dbus_message_iter_append_basic.?(i, type_, @ptrCast(&v)) == 0) return error.OutOfMemory;
}
pub fn string(i: *Iter, value: [*:0]const u8) Error!void {
try basic(i, c.DBUS_TYPE_STRING, value);
}
pub fn open(i: *Iter, type_: c_int, signature: ?[*:0]const u8) Error!Iter {
var nested: Iter = std.mem.zeroes(Iter);
if (c.z_dbus_message_iter_open_container.?(i, type_, signature, &nested) == 0) return error.OutOfMemory;
return nested;
}
pub fn close(i: *Iter, nested: *Iter) Error!void {
if (c.z_dbus_message_iter_close_container.?(i, nested) == 0) return error.OutOfMemory;
}
pub fn option(i: *Iter, key: [*:0]const u8, comptime signature: [:0]const u8, value: anytype) Error!void {
var pair = try open(i, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &pair);
try string(&pair, key);
var payload = try open(&pair, c.DBUS_TYPE_VARIANT, signature);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &payload);
try basic(&payload, signature[0], value);
try close(&pair, &payload);
try close(i, &pair);
}
pub fn kind(i: *Iter) c_int {
return c.z_dbus_message_iter_get_arg_type.?(i);
}
pub fn next(i: *Iter) bool {
return c.z_dbus_message_iter_next.?(i) != 0;
}
pub fn child(i: *Iter) Iter {
var result: Iter = std.mem.zeroes(Iter);
c.z_dbus_message_iter_recurse.?(i, &result);
return result;
}
pub fn str(i: *Iter) ?[]const u8 {
if (kind(i) != c.DBUS_TYPE_STRING and kind(i) != c.DBUS_TYPE_OBJECT_PATH) return null;
var value: [*c]const u8 = null;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return if (value == null) null else std.mem.span(value);
}
pub fn uint(i: *Iter) ?u32 {
if (kind(i) != c.DBUS_TYPE_UINT32) return null;
var value: u32 = 0;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return value;
}
pub fn variant(i: *Iter) ?Iter {
return if (kind(i) == c.DBUS_TYPE_VARIANT) child(i) else null;
}
pub fn entry(i: *Iter, key: []const u8) ?Iter {
if (kind(i) != c.DBUS_TYPE_ARRAY) return null;
var entries = child(i);
while (kind(&entries) == c.DBUS_TYPE_DICT_ENTRY) {
var pair = child(&entries);
@ -79,8 +98,10 @@ pub fn entry(i: *Iter, key: []const u8) ?Iter {
if (std.mem.eql(u8, name, key)) return pair;
if (!next(&entries)) break;
}
return null;
}
comptime {
std.debug.assert(@sizeOf(c.dbus_uint32_t) == 4);
std.debug.assert(@sizeOf(c.dbus_uint64_t) == 8);
@ -89,6 +110,7 @@ comptime {
pub fn int(i: *Iter) ?i32 {
if (kind(i) != c.DBUS_TYPE_INT32) return null;
var value: i32 = 0;
c.z_dbus_message_iter_get_basic.?(i, @ptrCast(&value));
return value;

View File

@ -17,7 +17,14 @@ const Offer = struct {
actions: u32 = 0,
action: u32 = 0,
};
const Source = struct { next: ?*Source = null, proxy: ?*c.struct_wl_data_source, bytes: []u8, refs: usize = 1 };
const Source = struct {
next: ?*Source = null,
proxy: ?*c.struct_wl_data_source,
bytes: []u8,
refs: usize = 1,
};
const Transfer = struct {
next: ?*Transfer = null,
fd: c_int,
@ -31,6 +38,7 @@ const Transfer = struct {
limit: u64 = 0,
deadline: u64,
};
pub const State = struct {
manager: ?*c.struct_wl_data_device_manager = null,
device: ?*c.struct_wl_data_device = null,
@ -43,114 +51,141 @@ pub const State = struct {
position: n.uhdk_point = .{ .x = 0, .y = 0 },
transfers: ?*Transfer = null,
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
fn s() *State {
return &b().data;
fn dataState() *State {
return &backend().data;
}
fn data(comptime T: type, raw: ?*anyopaque) *T {
return @ptrCast(@alignCast(raw.?));
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (std.mem.eql(u8, interface, "wl_data_device_manager") and version >= 3)
s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_data_device_manager_interface, 3));
dataState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_data_device_manager_interface, 3));
}
pub fn setup() void {
if (s().manager != null and Input.state().seat != null and s().device == null) {
s().device = c.wl_data_device_manager_get_data_device(s().manager, Input.state().seat);
if (s().device != null) _ = c.wl_data_device_add_listener(s().device, &device_listener, null);
if (dataState().manager != null and Input.state().seat != null and dataState().device == null) {
dataState().device = c.wl_data_device_manager_get_data_device(dataState().manager, Input.state().seat);
if (dataState().device != null) _ = c.wl_data_device_add_listener(dataState().device, &device_listener, null);
}
native.setCapability(n.UHDK_CAP_CLIPBOARD, s().device != null);
native.setCapability(n.UHDK_CAP_DROP_FILES, s().device != null);
native.setCapability(n.UHDK_CAP_CLIPBOARD, dataState().device != null);
native.setCapability(n.UHDK_CAP_DROP_FILES, dataState().device != null);
}
fn unref(o: *Offer) void {
o.refs -= 1;
if (o.refs != 0) return;
var link = &s().offers;
var link = &dataState().offers;
while (link.* != o) link = &link.*.?.next;
link.* = o.next;
c.wl_data_offer_destroy(o.proxy);
b().app.gpa.destroy(o);
backend().app.gpa.destroy(o);
}
fn offer(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
const o = b().app.gpa.create(Offer) catch {
const o = backend().app.gpa.create(Offer) catch {
c.wl_data_offer_destroy(proxy);
return;
};
o.* = .{ .next = s().offers, .proxy = proxy };
s().offers = o;
o.* = .{ .next = dataState().offers, .proxy = proxy };
dataState().offers = o;
_ = c.wl_data_offer_add_listener(proxy, &offer_listener, o);
}
fn mime(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, name: [*c]const u8) callconv(.c) void {
const o = data(Offer, raw);
const str = std.mem.span(name);
if (std.mem.eql(u8, str, "text/plain;charset=utf-8")) o.text = "text/plain;charset=utf-8" else if (std.mem.eql(u8, str, "text/plain") and o.text == null) o.text = "text/plain";
if (std.mem.eql(u8, str, "text/uri-list")) o.uris = true;
}
fn actions(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void {
data(Offer, raw).actions = value;
}
fn action(raw: ?*anyopaque, _: ?*c.struct_wl_data_offer, value: u32) callconv(.c) void {
data(Offer, raw).action = value;
}
const offer_listener: c.struct_wl_data_offer_listener = .{ .offer = mime, .source_actions = actions, .action = action };
fn lookup(proxy: ?*c.struct_wl_data_offer) ?*Offer {
var o = s().offers;
var o = dataState().offers;
while (o) |item| : (o = item.next) if (item.proxy == proxy) return item;
return null;
}
fn selection(_: ?*anyopaque, _: ?*c.struct_wl_data_device, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
if (s().selection) |old| unref(old);
s().selection = lookup(proxy); // Takes the initial offer reference.
if (dataState().selection) |old| unref(old);
dataState().selection = lookup(proxy); // Takes the initial offer reference.
}
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_data_device, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32, proxy: ?*c.struct_wl_data_offer) callconv(.c) void {
leave(null, null);
s().drag = lookup(proxy);
s().drag_window = Input.find(surface);
s().drag_serial = serial;
s().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
dataState().drag = lookup(proxy);
dataState().drag_window = Input.find(surface);
dataState().drag_serial = serial;
dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
negotiate();
}
fn negotiate() void {
const o = s().drag orelse return;
const accepted = o.uris and s().drag_window != null and s().drag_window.?.drop_enabled;
c.wl_data_offer_accept(o.proxy, s().drag_serial, if (accepted) "text/uri-list" else null);
const o = dataState().drag orelse return;
const accepted = o.uris and dataState().drag_window != null and dataState().drag_window.?.drop_enabled;
c.wl_data_offer_accept(o.proxy, dataState().drag_serial, if (accepted) "text/uri-list" else null);
c.wl_data_offer_set_actions(o.proxy, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0, if (accepted) c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY else 0);
}
fn leave(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
if (s().drag) |o| unref(o);
s().drag = null;
s().drag_window = null;
if (dataState().drag) |o| unref(o);
dataState().drag = null;
dataState().drag_window = null;
}
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_data_device, _: u32, x: i32, y: i32) callconv(.c) void {
s().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
dataState().position = .{ .x = @as(f32, @floatFromInt(x)) / 256, .y = @as(f32, @floatFromInt(y)) / 256 };
}
fn drop(_: ?*anyopaque, _: ?*c.struct_wl_data_device) callconv(.c) void {
const o = s().drag orelse return;
const w = s().drag_window orelse return;
const o = dataState().drag orelse return;
const w = dataState().drag_window orelse return;
if (!w.drop_enabled or !o.uris or o.action != c.WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) return;
_ = receive(o, "text/uri-list", 0, 16 * 1024 * 1024, w);
// drop ends the drag session; no leave is required after a successful drop.
leave(null, null);
}
const device_listener: c.struct_wl_data_device_listener = .{ .data_offer = offer, .enter = enter, .leave = leave, .motion = motion, .drop = drop, .selection = selection };
pub fn enable(w: *native.Window, enabled: bool) u32 {
if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
w.drop_enabled = enabled;
if (s().drag_window == w) negotiate();
if (dataState().drag_window == w) negotiate();
return abi.OK;
}
fn sourceUnref(source: *Source) void {
source.refs -= 1;
if (source.refs != 0) return;
var link = &s().sources;
var link = &dataState().sources;
while (link.* != source) link = &link.*.?.next;
link.* = source.next;
b().app.gpa.free(source.bytes);
b().app.gpa.destroy(source);
backend().app.gpa.free(source.bytes);
backend().app.gpa.destroy(source);
}
fn target(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: [*c]const u8) callconv(.c) void {}
fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd: i32) callconv(.c) void {
const source = data(Source, raw);
const str = std.mem.span(name);
@ -158,87 +193,105 @@ fn send(raw: ?*anyopaque, _: ?*c.struct_wl_data_source, name: [*c]const u8, fd:
_ = c.close(fd);
return;
}
const transfer = b().app.gpa.create(Transfer) catch {
const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fd);
return;
};
source.refs += 1;
transfer.* = .{ .next = s().transfers, .fd = fd, .source = source, .deadline = runtime.now(b().app.io) + 10 * std.time.ns_per_s };
s().transfers = transfer;
transfer.* = .{ .next = dataState().transfers, .fd = fd, .source = source, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
dataState().transfers = transfer;
}
fn cancelled(raw: ?*anyopaque, proxy: ?*c.struct_wl_data_source) callconv(.c) void {
const source = data(Source, raw);
c.wl_data_source_destroy(proxy);
source.proxy = null;
sourceUnref(source);
}
fn unused(_: ?*anyopaque, _: ?*c.struct_wl_data_source) callconv(.c) void {}
fn unusedAction(_: ?*anyopaque, _: ?*c.struct_wl_data_source, _: u32) callconv(.c) void {}
const source_listener: c.struct_wl_data_source_listener = .{ .target = target, .send = send, .cancelled = cancelled, .dnd_drop_performed = unused, .dnd_finished = unused, .action = unusedAction };
pub fn write(text: n.uhdk_text) u32 {
if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
const input = Input.state();
// Selection changes require an actual input serial. Never queue a write to
// hijack an unrelated future keystroke when the app has no input focus.
if (input.key_focus == null or input.serial == 0) return abi.UNAVAILABLE;
const source = b().app.gpa.create(Source) catch return abi.OOM;
const bytes = b().app.gpa.dupe(u8, abi.textBytes(text)) catch {
b().app.gpa.destroy(source);
const source = backend().app.gpa.create(Source) catch return abi.OOM;
const bytes = backend().app.gpa.dupe(u8, abi.textBytes(text)) catch {
backend().app.gpa.destroy(source);
return abi.OOM;
};
const proxy = c.wl_data_device_manager_create_data_source(s().manager) orelse {
b().app.gpa.free(bytes);
b().app.gpa.destroy(source);
const proxy = c.wl_data_device_manager_create_data_source(dataState().manager) orelse {
backend().app.gpa.free(bytes);
backend().app.gpa.destroy(source);
return abi.OOM;
};
source.* = .{ .next = s().sources, .proxy = proxy, .bytes = bytes };
s().sources = source;
source.* = .{ .next = dataState().sources, .proxy = proxy, .bytes = bytes };
dataState().sources = source;
_ = c.wl_data_source_add_listener(proxy, &source_listener, source);
c.wl_data_source_offer(proxy, "text/plain;charset=utf-8");
c.wl_data_source_offer(proxy, "text/plain");
c.wl_data_device_set_selection(s().device, proxy, input.serial);
c.wl_data_device_set_selection(dataState().device, proxy, input.serial);
return abi.OK;
}
pub fn read(id: u64, limit: u64) u32 {
if (s().device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (dataState().device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (Input.state().key_focus == null) return abi.UNAVAILABLE;
const o = s().selection orelse return n.UHDK_STATUS_NOT_FOUND;
const o = dataState().selection orelse return n.UHDK_STATUS_NOT_FOUND;
const format = o.text orelse return n.UHDK_STATUS_NOT_FOUND;
return receive(o, format, id, limit, null);
}
fn receive(o: *Offer, format: [*:0]const u8, id: u64, limit: u64, w: ?*native.Window) u32 {
var fds: [2]c_int = undefined;
if (c.z_linux_pipe(&fds) != 0) return n.UHDK_STATUS_OS_ERROR;
const transfer = b().app.gpa.create(Transfer) catch {
const transfer = backend().app.gpa.create(Transfer) catch {
_ = c.close(fds[0]);
_ = c.close(fds[1]);
return abi.OOM;
};
o.refs += 1;
transfer.* = .{ .next = s().transfers, .fd = fds[0], .request = id, .offer = o, .window = w, .position = s().position, .limit = limit, .deadline = runtime.now(b().app.io) + 10 * std.time.ns_per_s };
s().transfers = transfer;
transfer.* = .{ .next = dataState().transfers, .fd = fds[0], .request = id, .offer = o, .window = w, .position = dataState().position, .limit = limit, .deadline = runtime.now(backend().app.io) + 10 * std.time.ns_per_s };
dataState().transfers = transfer;
c.wl_data_offer_receive(o.proxy, format, fds[1]);
_ = c.close(fds[1]);
return n.Z_DEFERRED;
}
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var t = s().transfers;
while (t) |item| : (t = item.next) try fds.append(b().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 });
var t = dataState().transfers;
while (t) |item| : (t = item.next) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = if (item.source != null) c.POLLOUT else c.POLLIN, .revents = 0 });
}
pub fn tick() i32 {
var t = s().transfers;
var t = dataState().transfers;
while (t) |item| {
t = item.next;
if (runtime.now(b().app.io) >= item.deadline) {
if (runtime.now(backend().app.io) >= item.deadline) {
finish(item, abi.UNAVAILABLE);
continue;
}
if (item.source) |source| {
const bytes = source.bytes[item.offset..];
if (bytes.len == 0) {
finish(item, abi.OK);
continue;
}
const amount = c.z_linux_pipe_write(item.fd, bytes.ptr, @min(bytes.len, 65536));
if (amount > 0) item.offset += @intCast(amount) else if (amount < 0 and c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
} else {
@ -250,71 +303,84 @@ pub fn tick() i32 {
finish(item, n.UHDK_STATUS_BUFFER_TOO_SMALL);
continue;
}
item.bytes.appendSlice(b().app.gpa, buffer[0..length]) catch {
item.bytes.appendSlice(backend().app.gpa, buffer[0..length]) catch {
finish(item, abi.OOM);
continue;
};
} else if (c.z_linux_errno() != c.EAGAIN and c.z_linux_errno() != c.EINTR) finish(item, abi.UNAVAILABLE);
}
}
return if (s().transfers != null) 100 else -1;
return if (dataState().transfers != null) 100 else -1;
}
fn finish(t: *Transfer, status: u32) void {
if (t.request != 0) {
var result = std.mem.zeroes(n.z_request_result);
result.value.text = abi.textSpan(t.bytes.items);
n.z_complete(runtime.toAppHandle(b().app), t.request, if (status == abi.OK and !std.unicode.utf8ValidateSlice(t.bytes.items)) abi.INVALID else status, &result);
n.z_complete(runtime.toAppHandle(backend().app), t.request, if (status == abi.OK and !std.unicode.utf8ValidateSlice(t.bytes.items)) abi.INVALID else status, &result);
} else if (t.window) |w| {
if (status == abi.OK and w.drop_enabled and emitDrop(w, t.bytes.items, t.position)) c.wl_data_offer_finish(t.offer.?.proxy);
}
var link = &s().transfers;
var link = &dataState().transfers;
while (link.* != t) link = &link.*.?.next;
link.* = t.next;
_ = c.close(t.fd);
if (t.offer) |o| unref(o);
if (t.source) |source| sourceUnref(source);
t.bytes.deinit(b().app.gpa);
b().app.gpa.destroy(t);
t.bytes.deinit(backend().app.gpa);
backend().app.gpa.destroy(t);
}
fn emitDrop(w: *native.Window, bytes: []const u8, position: n.uhdk_point) bool {
var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer {
for (files.items) |file| n.uhdk_file_release(file);
files.deinit(b().app.gpa);
files.deinit(backend().app.gpa);
}
var lines = std.mem.splitScalar(u8, bytes, '\n');
while (lines.next()) |line| {
const uri = std.mem.trim(u8, line, "\r");
if (uri.len == 0 or uri[0] == '#') continue;
const path = Files.decode(b().app.gpa, uri) catch return false;
defer b().app.gpa.free(path);
const file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false;
files.append(b().app.gpa, file) catch {
const path = Files.decode(backend().app.gpa, uri) catch return false;
defer backend().app.gpa.free(path);
const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = path.ptr, .len = path.len }, null) orelse return false;
files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file);
return false;
};
}
if (files.items.len == 0) return false;
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_DROP_FILES;
event.data.drop_files = .{ .files = .{ .ptr = files.items.ptr, .len = files.items.len }, .position = position };
Input.send(w, &event);
return true;
}
pub fn cancel(id: u64) bool {
var t = s().transfers;
var t = dataState().transfers;
while (t) |item| : (t = item.next) if (item.request == id) {
finish(item, abi.CANCELLED);
return true;
};
return false;
}
pub fn forget(w: *native.Window) void {
if (s().drag_window == w) {
s().drag_window = null;
if (dataState().drag_window == w) {
dataState().drag_window = null;
negotiate();
}
var t = s().transfers;
var t = dataState().transfers;
while (t) |item| {
t = item.next;
if (item.window == w) {
@ -323,23 +389,26 @@ pub fn forget(w: *native.Window) void {
}
}
}
pub fn releaseSeat() void {
while (s().transfers) |t| finish(t, abi.CANCELLED);
s().selection = null;
s().drag = null;
s().drag_window = null;
while (s().offers) |o| unref(o);
while (s().sources) |source| {
while (dataState().transfers) |t| finish(t, abi.CANCELLED);
dataState().selection = null;
dataState().drag = null;
dataState().drag_window = null;
while (dataState().offers) |o| unref(o);
while (dataState().sources) |source| {
if (source.proxy != null) c.wl_data_source_destroy(source.proxy);
sourceUnref(source);
}
if (s().device != null) c.wl_data_device_release(s().device);
s().device = null;
if (dataState().device != null) c.wl_data_device_release(dataState().device);
dataState().device = null;
native.setCapability(n.UHDK_CAP_CLIPBOARD, false);
native.setCapability(n.UHDK_CAP_DROP_FILES, false);
}
pub fn deinit() void {
releaseSeat();
if (s().manager != null) c.wl_data_device_manager_destroy(s().manager);
s().manager = null;
if (dataState().manager != null) c.wl_data_device_manager_destroy(dataState().manager);
dataState().manager = null;
}

View File

@ -7,8 +7,21 @@ const native = @import("native.zig");
const Input = @import("Input.zig");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Activation = struct { next: ?*Activation = null, id: u64, window: *native.Window, token: ?*c.struct_xdg_activation_token_v1, deadline: u64 };
const Icon = struct { proxy: ?*c.struct_xdg_toplevel_icon_v1, buffer: ?*c.struct_wl_buffer, mapping: *anyopaque, size: usize };
const Activation = struct {
next: ?*Activation = null,
id: u64,
window: *native.Window,
token: ?*c.struct_xdg_activation_token_v1,
deadline: u64,
};
const Icon = struct {
proxy: ?*c.struct_xdg_toplevel_icon_v1,
buffer: ?*c.struct_wl_buffer,
mapping: *anyopaque,
size: usize,
};
pub const State = struct {
activation: ?*c.struct_xdg_activation_v1 = null,
manager: ?*c.struct_xdg_toplevel_icon_manager_v1 = null,
@ -16,113 +29,168 @@ pub const State = struct {
icon: ?Icon = null,
pending: ?*Activation = null,
launch: ?[:0]u8 = null,
tray_token: ?[:0]u8 = null,
tray_token_deadline: u64 = 0,
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
fn s() *State {
return &b().desktop;
fn desktopState() *State {
return &backend().desktop;
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "xdg_activation_v1")) s().activation = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_activation_v1_interface, 1)) else if (std.mem.eql(u8, interface, "xdg_toplevel_icon_manager_v1")) {
s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1));
if (s().manager != null) _ = c.xdg_toplevel_icon_manager_v1_add_listener(s().manager, &icon_listener, null);
if (std.mem.eql(u8, interface, "xdg_activation_v1")) desktopState().activation = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_activation_v1_interface, 1)) else if (std.mem.eql(u8, interface, "xdg_toplevel_icon_manager_v1")) {
desktopState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_xdg_toplevel_icon_manager_v1_interface, 1));
if (desktopState().manager != null) _ = c.xdg_toplevel_icon_manager_v1_add_listener(desktopState().manager, &icon_listener, null);
} else if (std.mem.eql(u8, interface, "wl_shm")) {
s().shm = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_shm_interface, 1));
if (s().shm != null) _ = c.wl_shm_add_listener(s().shm, &shm_listener, null);
desktopState().shm = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wl_shm_interface, 1));
if (desktopState().shm != null) _ = c.wl_shm_add_listener(desktopState().shm, &shm_listener, null);
}
native.setCapability(n.UHDK_CAP_APP_ICON, s().manager != null and s().shm != null);
native.setCapability(n.UHDK_CAP_APP_ICON, desktopState().manager != null and desktopState().shm != null);
}
fn iconSize(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1, _: i32) callconv(.c) void {}
fn iconDone(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel_icon_manager_v1) callconv(.c) void {}
const icon_listener: c.struct_xdg_toplevel_icon_manager_v1_listener = .{ .icon_size = iconSize, .done = iconDone };
fn format(_: ?*anyopaque, _: ?*c.struct_wl_shm, _: u32) callconv(.c) void {}
const shm_listener: c.struct_wl_shm_listener = .{ .format = format };
var launch_token_read = false;
pub fn initialize() void {
if (launch_token_read) return;
launch_token_read = true;
const token = c.getenv("XDG_ACTIVATION_TOKEN");
if (token != null and token[0] != 0) {
s().launch = b().app.gpa.dupeZ(u8, std.mem.span(token)) catch null;
_ = c.unsetenv("XDG_ACTIVATION_TOKEN");
desktopState().launch = backend().app.gpa.dupeSentinel(
u8,
std.mem.span(token),
0,
) catch null;
}
}
// A tray host supplies provenance that a hidden application's own seat lacks.
// Consume it once, promptly, without modifying the process environment.
pub fn trayToken(token: []const u8) !void {
const copy = if (token.len != 0) try backend().app.gpa.dupeSentinel(u8, token, 0) else null;
if (desktopState().tray_token) |old| backend().app.gpa.free(old);
desktopState().tray_token = copy;
desktopState().tray_token_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
}
pub fn focus(w: *native.Window, id: u64) u32 {
if (s().activation == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s().launch) |token| {
c.xdg_activation_v1_activate(s().activation, token, w.surface);
b().app.gpa.free(token);
s().launch = null;
if (desktopState().activation == null) return n.UHDK_STATUS_UNSUPPORTED;
if (desktopState().tray_token) |token| {
const fresh = runtime.now(backend().app.io) < desktopState().tray_token_deadline;
if (fresh) c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
backend().app.gpa.free(token);
desktopState().tray_token = null;
if (fresh) return abi.OK;
}
if (desktopState().launch) |token| {
c.xdg_activation_v1_activate(desktopState().activation, token, w.surface);
backend().app.gpa.free(token);
desktopState().launch = null;
return abi.OK;
}
const input = Input.state();
if (input.serial == 0 or input.key_focus == null or runtime.now(b().app.io) -| input.serial_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE;
const p = b().app.gpa.create(Activation) catch return abi.OOM;
const token = c.xdg_activation_v1_get_activation_token(s().activation) orelse {
b().app.gpa.destroy(p);
if (input.serial == 0 or input.key_focus == null or
runtime.now(backend().app.io) -| input.serial_time > 5 * std.time.ns_per_s)
return abi.UNAVAILABLE;
const p = backend().app.gpa.create(Activation) catch return abi.OOM;
const token = c.xdg_activation_v1_get_activation_token(desktopState().activation) orelse {
backend().app.gpa.destroy(p);
return abi.OOM;
};
p.* = .{ .next = s().pending, .id = id, .window = w, .token = token, .deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s };
s().pending = p;
p.* = .{
.next = desktopState().pending,
.id = id,
.window = w,
.token = token,
.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s,
};
desktopState().pending = p;
_ = c.xdg_activation_token_v1_add_listener(token, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(token, input.serial, input.seat);
c.xdg_activation_token_v1_set_surface(token, input.key_focus.?.surface);
const app_id = b().app.gpa.dupeZ(u8, b().app.application_id) catch {
const app_id = backend().app.gpa.dupeSentinel(u8, backend().app.application_id, 0) catch {
finish(p, abi.OOM);
return n.Z_DEFERRED;
};
defer b().app.gpa.free(app_id);
defer backend().app.gpa.free(app_id);
c.xdg_activation_token_v1_set_app_id(token, app_id);
c.xdg_activation_token_v1_commit(token);
return n.Z_DEFERRED;
}
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Activation = @ptrCast(@alignCast(raw.?));
c.xdg_activation_v1_activate(s().activation, token, p.window.surface);
c.xdg_activation_v1_activate(desktopState().activation, token, p.window.surface);
finish(p, abi.OK);
}
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn finish(p: *Activation, status: u32) void {
var link = &s().pending;
var link = &desktopState().pending;
while (link.* != p) link = &link.*.?.next;
link.* = p.next;
c.xdg_activation_token_v1_destroy(p.token);
n.z_complete(runtime.toAppHandle(b().app), p.id, status, null);
b().app.gpa.destroy(p);
n.z_complete(runtime.toAppHandle(backend().app), p.id, status, null);
backend().app.gpa.destroy(p);
}
pub fn tick() i32 {
var cursor = s().pending;
var cursor = desktopState().pending;
while (cursor) |p| {
cursor = p.next;
if (runtime.now(b().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE);
if (runtime.now(backend().app.io) >= p.deadline) finish(p, abi.UNAVAILABLE);
}
return if (s().pending != null) 100 else -1;
return if (desktopState().pending != null) 100 else -1;
}
pub fn cancel(id: u64) bool {
var cursor = s().pending;
var cursor = desktopState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) {
finish(p, abi.CANCELLED);
return true;
};
return false;
}
pub fn forget(w: *native.Window) void {
var cursor = s().pending;
var cursor = desktopState().pending;
while (cursor) |p| {
cursor = p.next;
if (p.window == w) finish(p, abi.CANCELLED);
}
}
pub fn applyIcon(w: *native.Window) void {
if (s().icon) |icon| c.xdg_toplevel_icon_manager_v1_set_icon(s().manager, w.top, icon.proxy);
if (desktopState().icon) |icon|
c.xdg_toplevel_icon_manager_v1_set_icon(desktopState().manager, w.top, icon.proxy);
}
/// Public pixels are straight RGBA; wl_shm ARGB8888 uses native-endian,
/// premultiplied channels. Pad rectangular images to a transparent square.
pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void {
@memset(destination, 0);
const source = abi.bytes(image.pixels);
const x0 = (side - image.width) / 2;
const y0 = (side - image.height) / 2;
for (0..image.height) |y| for (0..image.width) |x| {
const offset = y * @as(usize, @intCast(image.stride_bytes)) + x * 4;
const offset = (y * image.width + x) * 4;
const a: u32 = source[offset + 3];
const r = (@as(u32, source[offset]) * a + 127) / 255;
const g = (@as(u32, source[offset + 1]) * a + 127) / 255;
@ -130,58 +198,79 @@ pub fn pixels(destination: []u32, side: usize, image: n.uhdk_image) void {
destination[(y + y0) * side + x + x0] = a << 24 | r << 16 | g << 8 | blue;
};
}
pub fn setIcon(image: n.uhdk_image) u32 {
if (s().manager == null or s().shm == null) return n.UHDK_STATUS_UNSUPPORTED;
if (desktopState().manager == null or desktopState().shm == null) return n.UHDK_STATUS_UNSUPPORTED;
const side = @max(image.width, image.height);
const size: usize = @as(usize, side) * side * 4;
const fd = c.memfd_create("uhdk-icon", c.MFD_CLOEXEC);
if (fd < 0) return n.UHDK_STATUS_OS_ERROR;
defer _ = c.close(fd);
if (c.ftruncate(fd, @intCast(size)) != 0) return n.UHDK_STATUS_OS_ERROR;
const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
if (mapping == c.MAP_FAILED) return n.UHDK_STATUS_OS_ERROR;
var retained = false;
defer if (!retained) {
_ = c.munmap(mapping, size);
};
const words: [*]u32 = @ptrCast(@alignCast(mapping.?));
pixels(words[0 .. size / 4], side, image);
const pool = c.wl_shm_create_pool(s().shm, fd, @intCast(size)) orelse return abi.OOM;
const pool = c.wl_shm_create_pool(desktopState().shm, fd, @intCast(size)) orelse return abi.OOM;
defer c.wl_shm_pool_destroy(pool);
const buffer = c.wl_shm_pool_create_buffer(pool, 0, @intCast(side), @intCast(side), @intCast(side * 4), c.WL_SHM_FORMAT_ARGB8888) orelse return abi.OOM;
const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(s().manager) orelse {
const buffer = c.wl_shm_pool_create_buffer(
pool,
0,
@intCast(side),
@intCast(side),
@intCast(side * 4),
c.WL_SHM_FORMAT_ARGB8888,
) orelse return abi.OOM;
const proxy = c.xdg_toplevel_icon_manager_v1_create_icon(desktopState().manager) orelse {
c.wl_buffer_destroy(buffer);
return abi.OOM;
};
c.xdg_toplevel_icon_v1_add_buffer(proxy, buffer, 1);
const old = s().icon;
s().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size };
const old = desktopState().icon;
desktopState().icon = .{ .proxy = proxy, .buffer = buffer, .mapping = mapping.?, .size = size };
retained = true;
var cursor = b().windows;
var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) applyIcon(w);
if (old) |icon| destroyIcon(icon);
return abi.OK;
}
fn destroyIcon(icon: Icon) void {
c.xdg_toplevel_icon_v1_destroy(icon.proxy);
c.wl_buffer_destroy(icon.buffer);
_ = c.munmap(icon.mapping, icon.size);
}
pub fn deinit() void {
while (s().pending) |p| finish(p, abi.CANCELLED);
if (s().icon) |icon| destroyIcon(icon);
if (s().launch) |token| b().app.gpa.free(token);
if (s().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(s().manager);
if (s().shm != null) c.wl_shm_destroy(s().shm);
if (s().activation != null) c.xdg_activation_v1_destroy(s().activation);
while (desktopState().pending) |p| finish(p, abi.CANCELLED);
if (desktopState().icon) |icon| destroyIcon(icon);
if (desktopState().launch) |token| backend().app.gpa.free(token);
if (desktopState().tray_token) |token| backend().app.gpa.free(token);
if (desktopState().manager != null) c.xdg_toplevel_icon_manager_v1_destroy(desktopState().manager);
if (desktopState().shm != null) c.wl_shm_destroy(desktopState().shm);
if (desktopState().activation != null) c.xdg_activation_v1_destroy(desktopState().activation);
}
test "icons premultiply RGBA and pad rectangular images" {
const rgba = [_]u8{ 255, 128, 0, 128, 0, 255, 0, 255 };
var image = std.mem.zeroes(n.uhdk_image);
image.width = 2;
image.height = 1;
image.stride_bytes = 8;
image.pixels = .{ .ptr = &rgba, .len = rgba.len };
var result: [4]u32 = undefined;
pixels(&result, 2, image);
try std.testing.expectEqualSlices(u32, &.{ 0x80804000, 0xff00ff00, 0, 0 }, &result);

View File

@ -12,12 +12,15 @@ pub const Context = struct {
surface: c.EGLSurface,
context: c.EGLContext,
};
threadlocal var frame: ?*Context = null;
pub fn initialize(b: *native.Backend) void {
if (c.z_linux_egl_available() == 0) return;
const display = c.z_eglGetPlatformDisplay.?(c.EGL_PLATFORM_WAYLAND_KHR, b.display, null);
if (display == null) return;
var major: c.EGLint = 0;
var minor: c.EGLint = 0;
if (c.z_eglInitialize.?(display, &major, &minor) == c.EGL_FALSE) return;
@ -25,6 +28,7 @@ pub fn initialize(b: *native.Backend) void {
_ = c.z_eglTerminate.?(display);
return;
}
const attributes = [_]c.EGLint{ c.EGL_SURFACE_TYPE, c.EGL_WINDOW_BIT, c.EGL_RENDERABLE_TYPE, c.EGL_OPENGL_BIT, c.EGL_RED_SIZE, 8, c.EGL_GREEN_SIZE, 8, c.EGL_BLUE_SIZE, 8, c.EGL_ALPHA_SIZE, 8, c.EGL_NONE };
var config: c.EGLConfig = null;
var count: c.EGLint = 0;
@ -32,9 +36,11 @@ pub fn initialize(b: *native.Backend) void {
_ = c.z_eglTerminate.?(display);
return;
}
b.egl_display = display;
b.egl_config = config;
}
pub fn finish(b: *native.Backend) void {
if (b.egl_display != null) {
_ = c.z_eglTerminate.?(b.egl_display);
@ -42,36 +48,41 @@ pub fn finish(b: *native.Backend) void {
b.egl_display = null;
}
}
pub fn create(b: *native.Backend, w: *native.Window, object: ?*anyopaque, result: [*c]n.z_request_result) u32 {
if (b.egl_display == null or w.flags & n.UHDK_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED;
pub fn create(b: *native.Backend, w: *native.Window) u32 {
if (b.egl_display == null or w.flags & n.Z_WINDOW_OPENGL == 0) return n.UHDK_STATUS_UNSUPPORTED;
if (w.egl != null) return n.UHDK_STATUS_BUSY;
if (c.z_eglBindAPI.?(c.EGL_OPENGL_API) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
const attrs = [_]c.EGLint{ c.EGL_CONTEXT_MAJOR_VERSION, 3, c.EGL_CONTEXT_MINOR_VERSION, 3, c.EGL_CONTEXT_OPENGL_PROFILE_MASK, c.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, c.EGL_NONE };
const context = c.z_eglCreateContext.?(b.egl_display, b.egl_config, null, &attrs);
if (context == null) return n.UHDK_STATUS_UNSUPPORTED;
const win = c.z_wl_egl_window_create.?(w.surface, @intCast(w.metrics.framebuffer_width), @intCast(w.metrics.framebuffer_height));
if (win == null) {
_ = c.z_eglDestroyContext.?(b.egl_display, context);
return abi.OOM;
}
const surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, @ptrCast(win), null);
if (surface == null) {
c.z_wl_egl_window_destroy.?(win);
_ = c.z_eglDestroyContext.?(b.egl_display, context);
return n.UHDK_STATUS_OS_ERROR;
}
const ctx = b.app.gpa.create(Context) catch {
_ = c.z_eglDestroySurface.?(b.egl_display, surface);
c.z_wl_egl_window_destroy.?(win);
_ = c.z_eglDestroyContext.?(b.egl_display, context);
return abi.OOM;
};
ctx.* = .{ .window = w, .native = win, .surface = surface, .context = context };
w.egl = ctx;
n.z_object_set_native(object, ctx);
result.*.value.gl_context = @ptrCast(object);
return abi.OK;
}
pub fn destroy(ctx: *Context) void {
const b = native.instance.?;
_ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface);
@ -80,18 +91,22 @@ pub fn destroy(ctx: *Context) void {
ctx.window.egl = null;
b.app.gpa.destroy(ctx);
}
pub fn resetSurface(ctx: *Context) void {
const b = native.instance.?;
// An unmapped surface may never receive the driver's outstanding frame
// callback. Drop its EGL surface before hiding so remapping cannot wait
// forever in the next swap; the GL context and application resources survive.
if (ctx.surface != null) _ = c.z_eglDestroySurface.?(b.egl_display, ctx.surface);
ctx.surface = c.z_eglCreateWindowSurface.?(b.egl_display, b.egl_config, ctx.native, null);
}
fn makeCurrent(b: *native.Backend, ctx: *Context) bool {
return ctx.surface != null and c.z_eglBindAPI.?(c.EGL_OPENGL_API) != c.EGL_FALSE and
c.z_eglMakeCurrent.?(b.egl_display, ctx.surface, ctx.surface, ctx.context) != c.EGL_FALSE;
}
pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
const b = native.instance orelse return abi.UNAVAILABLE;
if (b.egl_display == null) return n.UHDK_STATUS_UNSUPPORTED;
@ -99,40 +114,34 @@ pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
if (op == 8 and frame != null) return n.UHDK_STATUS_BUSY;
return if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) != c.EGL_FALSE) abi.OK else n.UHDK_STATUS_OS_ERROR;
}
const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
if (op == 1) {
if (frame != null) return n.UHDK_STATUS_BUSY;
if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
ctx.window.mutex.lockUncancelable(b.app.io);
if (!makeCurrent(b, ctx)) {
ctx.window.mutex.unlock(b.app.io);
return n.UHDK_STATUS_OS_ERROR;
}
frame = ctx;
return abi.OK;
}
if (frame != ctx) return n.UHDK_STATUS_BUSY;
switch (op) {
2 => {
// Keep ownership on failure so a caller cannot destroy a current context.
if (c.z_eglMakeCurrent.?(b.egl_display, null, null, null) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
frame = null;
ctx.window.mutex.unlock(b.app.io);
n.z_native_wake();
return abi.OK;
},
3 => return if (makeCurrent(b, ctx)) abi.OK else n.UHDK_STATUS_OS_ERROR,
5 => {
if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const address = c.z_eglGetProcAddress.?("glGetIntegerv") orelse return n.UHDK_STATUS_NOT_FOUND;
const get_integer: *const fn (c_uint, *c_int) callconv(.c) void = @ptrCast(address);
var major: c_int = 0;
var minor: c_int = 0;
get_integer(0x821B, &major); // GL_MAJOR_VERSION
get_integer(0x821C, &minor); // GL_MINOR_VERSION
const version: *[2]u32 = @ptrCast(@alignCast(out.?));
version.* = .{ @intCast(major), @intCast(minor) };
},
6 => {
if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
if (!ctx.window.visible or !ctx.window.configured) return abi.UNAVAILABLE;
@ -141,19 +150,24 @@ pub fn call(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
},
7 => {
if (c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const interval: *const i32 = @ptrCast(@alignCast(out.?));
if (c.z_eglSwapInterval.?(b.egl_display, interval.*) == c.EGL_FALSE) return n.UHDK_STATUS_OS_ERROR;
},
else => return abi.INVALID,
}
return abi.OK;
}
pub fn proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 {
const ctx: *Context = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
if (frame != ctx or c.z_eglGetCurrentContext.?() != ctx.context) return n.UHDK_STATUS_BUSY;
const allocator = ctx.window.owner.gpa;
const terminated = allocator.dupeZ(u8, abi.textBytes(name)) catch return abi.OOM;
const terminated = allocator.dupeSentinel(u8, abi.textBytes(name), 0) catch return abi.OOM;
defer allocator.free(terminated);
const address = c.z_eglGetProcAddress.?(terminated) orelse return n.UHDK_STATUS_NOT_FOUND;
out.* = @ptrCast(address);
return abi.OK;

View File

@ -8,20 +8,25 @@ pub fn decode(allocator: std.mem.Allocator, uri: []const u8) ![]u8 {
const encoded = if (std.mem.startsWith(u8, uri, "file:///")) uri[7..] else if (std.mem.startsWith(u8, uri, "file://localhost/")) uri[16..] else return error.Invalid;
var result: std.Io.Writer.Allocating = .init(allocator);
errdefer result.deinit();
var i: usize = 0;
while (i < encoded.len) : (i += 1) {
var byte = encoded[i];
if (byte == '%') {
if (encoded.len - i < 3) return error.Invalid;
if (!std.ascii.isHex(encoded[i + 1]) or !std.ascii.isHex(encoded[i + 2])) return error.Invalid;
byte = std.fmt.parseInt(u8, encoded[i + 1 ..][0..2], 16) catch return error.Invalid;
i += 2;
} else if (byte == '?' or byte == '#') return error.Invalid;
if (byte == 0) return error.Invalid;
try result.writer.writeByte(byte);
}
return result.toOwnedSlice();
}
fn encode(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
var result: std.Io.Writer.Allocating = .init(allocator);
errdefer result.deinit();
@ -31,18 +36,24 @@ fn encode(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
try result.writer.writeByte(byte);
} else try result.writer.print("%{X:0>2}", .{byte});
}
return result.toOwnedSlice();
}
pub fn init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 {
if (grant != null) return n.UHDK_STATUS_UNSUPPORTED;
const object = runtime.fromObjectHandle(file);
var arena: std.heap.ArenaAllocator = .init(object.app.gpa);
defer arena.deinit();
const allocator = arena.allocator();
const bytes = if (path.len != 0) abi.bytes(path) else decode(allocator, abi.textBytes(uri)) catch |err| return if (err == error.Invalid) abi.INVALID else abi.OOM;
if (bytes.len == 0 or bytes[0] != '/' or std.mem.findScalar(u8, bytes, 0) != null) return abi.INVALID;
const encoded = encode(allocator, bytes) catch return abi.OOM;
const basename = std.fs.path.basename(bytes);
// Display text is lossy only when the native byte name isn't UTF-8.
const display = if (std.unicode.utf8ValidateSlice(basename)) basename else "(non-UTF-8 filename)";
return n.z_file_init(file, .{ .ptr = bytes.ptr, .len = bytes.len }, abi.textSpan(encoded), abi.textSpan(display), null);
@ -54,12 +65,14 @@ test "file URI preserves POSIX bytes and rejects remote, NUL, malformed escapes"
const uri = try encode(allocator, original);
defer allocator.free(uri);
try std.testing.expectEqualStrings("file:///tmp/a%20b%25%23%FF", uri);
const path = try decode(allocator, uri);
defer allocator.free(path);
try std.testing.expectEqualStrings(original, path);
for ([_][]const u8{ "https://host/file", "file://host/path", "file:///a%", "file:///a%XX", "file:///a%00", "file:///a%+1", "file:///a#fragment" }) |bad| {
try std.testing.expectError(error.Invalid, decode(allocator, bad));
}
const local = try decode(allocator, "file://localhost/tmp/a");
defer allocator.free(local);
try std.testing.expectEqualStrings("/tmp/a", local);

View File

@ -20,17 +20,24 @@ const Key = struct {
text: [256]u8 = undefined,
len: usize = 0,
};
pub const State = struct {
seat: ?*c.struct_wl_seat = null,
seat_name: u32 = 0,
keyboard: ?*c.struct_wl_keyboard = null,
pointer: ?*c.struct_wl_pointer = null,
cursor_manager: ?*c.struct_wp_cursor_shape_manager_v1 = null,
cursor_device: ?*c.struct_wp_cursor_shape_device_v1 = null,
constraints: ?*c.struct_zwp_pointer_constraints_v1 = null,
constraints_name: u32 = 0,
confined: ?*c.struct_zwp_confined_pointer_v1 = null,
text_manager: ?*c.struct_zwp_text_input_manager_v3 = null,
text_input: ?*c.struct_zwp_text_input_v3 = null,
text_focus: ?*native.Window = null,
text_serial: u32 = 0,
key_focus: ?*native.Window = null,
pointer_focus: ?*native.Window = null,
context: ?*c.struct_xkb_context = null,
@ -42,6 +49,7 @@ pub const State = struct {
active: bool = false,
pending_key: ?Key = null,
key_sync: ?*c.struct_wl_callback = null,
serial: u32 = 0,
serial_time: u64 = 0,
popup_serial: u32 = 0,
@ -50,48 +58,60 @@ pub const State = struct {
popup_buttons: u32 = 0,
pointer_serial: u32 = 0,
next_id: u64 = 0,
position: n.uhdk_point = .{ .x = 0, .y = 0 },
buttons: u32 = 0,
captured: bool = false,
pointer_mode: u32 = n.UHDK_POINTER_NORMAL,
mode_window: ?*native.Window = null,
last_click_time: u64 = 0,
last_click_button: u32 = 0,
last_click_position: n.uhdk_point = .{ .x = 0, .y = 0 },
click_count: u32 = 0,
repeat_key: ?u32 = null,
repeat_rate: u32 = 0,
repeat_delay: u32 = 600,
repeat_at: u64 = 0,
held: [256]bool = @splat(false),
menu_keys: [256]bool = @splat(false),
axis: n.uhdk_point = .{ .x = 0, .y = 0 },
wheel: n.uhdk_point = .{ .x = 0, .y = 0 },
axis_source: u32 = c.WL_POINTER_AXIS_SOURCE_WHEEL,
axis_stop: bool = false,
scrolling: bool = false,
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
pub fn state() *State {
return &b().input;
return &backend().input;
}
pub fn find(surface: ?*c.struct_wl_surface) ?*native.Window {
var item = b().windows;
var item = backend().windows;
while (item) |w| : (item = w.next) if (w.surface == surface) return w;
return null;
}
pub fn send(w: *native.Window, event: *n.z_event) void {
event.window = w.handle;
n.z_emit(runtime.toAppHandle(w.owner), event);
}
pub fn id() u64 {
state().next_id += 1;
return state().next_id;
}
pub fn provenance(serial: u32) void {
state().serial = serial;
state().serial_time = runtime.now(b().app.io);
state().serial_time = runtime.now(backend().app.io);
}
pub fn initialize() void {
const s = state();
if (c.z_linux_xkb_available() != 0) {
@ -106,6 +126,7 @@ pub fn initialize() void {
}
}
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
const s = state();
if (std.mem.eql(u8, interface, "wl_seat") and s.seat == null and version >= 5) {
@ -114,10 +135,15 @@ pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8
if (s.seat != null) _ = c.wl_seat_add_listener(s.seat, &seat_listener, null);
} else if (std.mem.eql(u8, interface, "wp_cursor_shape_manager_v1")) {
s.cursor_manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wp_cursor_shape_manager_v1_interface, 1));
} else if (std.mem.eql(u8, interface, "zwp_pointer_constraints_v1") and s.constraints == null) {
s.constraints = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zwp_pointer_constraints_v1_interface, 1));
s.constraints_name = name;
native.setCapability(n.UHDK_CAP_POINTER_CONFINEMENT, s.pointer != null and s.constraints != null);
} else if (std.mem.eql(u8, interface, "zwp_text_input_manager_v3")) {
s.text_manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zwp_text_input_manager_v3_interface, 1));
}
}
pub fn setup() void {
const s = state();
if (s.pointer != null and s.cursor_manager != null and s.cursor_device == null)
@ -126,11 +152,14 @@ pub fn setup() void {
s.text_input = c.zwp_text_input_manager_v3_get_text_input(s.text_manager, s.seat);
if (s.text_input != null) Text.listen(s.text_input);
}
Data.setup();
Popup.capability();
native.setCapability(n.UHDK_CAP_POINTER_CAPTURE, s.pointer != null);
native.setCapability(n.UHDK_CAP_POINTER_CONFINEMENT, s.pointer != null and s.constraints != null);
native.setCapability(n.UHDK_CAP_TEXT_INPUT, s.context != null and s.keyboard != null);
}
fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callconv(.c) void {
const s = state();
if (caps & c.WL_SEAT_CAPABILITY_KEYBOARD != 0 and s.keyboard == null) {
@ -141,6 +170,7 @@ fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callcon
c.wl_keyboard_release(s.keyboard);
s.keyboard = null;
}
if (caps & c.WL_SEAT_CAPABILITY_POINTER != 0 and s.pointer == null) {
s.pointer = c.wl_seat_get_pointer(seat);
if (s.pointer != null) _ = c.wl_pointer_add_listener(s.pointer, &pointer_listener, null);
@ -151,13 +181,20 @@ fn seatCapabilities(_: ?*anyopaque, seat: ?*c.struct_wl_seat, caps: u32) callcon
c.wl_pointer_release(s.pointer);
s.pointer = null;
}
setup();
}
fn seatName(_: ?*anyopaque, _: ?*c.struct_wl_seat, _: [*c]const u8) callconv(.c) void {}
const seat_listener: c.struct_wl_seat_listener = .{ .capabilities = seatCapabilities, .name = seatName };
const seat_listener: c.struct_wl_seat_listener = .{
.capabilities = seatCapabilities,
.name = seatName,
};
fn keymap(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, format: u32, fd: i32, size: u32) callconv(.c) void {
flushKey();
defer _ = c.close(fd);
const s = state();
s.repeat_key = null;
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
@ -167,18 +204,23 @@ fn keymap(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, format: u32, fd: i32, size:
s.state = null;
s.keymap = null;
if (s.context == null or format != c.WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1 or size == 0 or size > 16 * 1024 * 1024) return;
const mapped = c.mmap(null, size, c.PROT_READ, c.MAP_PRIVATE, fd, 0);
if (mapped == c.MAP_FAILED) return;
defer _ = c.munmap(mapped, size);
const bytes: [*]const u8 = @ptrCast(mapped.?);
if (bytes[size - 1] != 0) return;
s.keymap = c.z_xkb_keymap_new_from_string.?(s.context, @ptrCast(mapped), c.XKB_KEYMAP_FORMAT_TEXT_V1, c.XKB_KEYMAP_COMPILE_NO_FLAGS);
if (s.keymap != null) s.state = c.z_xkb_state_new.?(s.keymap);
}
fn keyEnter(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, surface: ?*c.struct_wl_surface, keys: [*c]c.struct_wl_array) callconv(.c) void {
leaveKeyboard();
const s = state();
s.key_focus = Popup.owner(surface) orelse find(surface);
const suppressed = s.menu_keys;
s.menu_keys = @splat(false);
if (s.state != null and keys.*.size != 0) {
@ -191,24 +233,29 @@ fn keyEnter(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, surface: ?*c.stru
}
}
}
fn keyLeave(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void {
leaveKeyboard();
}
fn updateModifiers() void {
const s = state();
s.modifiers = 0;
if (s.state == null) return;
const names = [_][*:0]const u8{ "Shift", "Control", "Mod1", "Mod4", "Lock", "Mod2" };
for (names, 0..) |name, index| if (c.z_xkb_state_mod_name_is_active.?(s.state, name, c.XKB_STATE_MODS_EFFECTIVE) > 0) {
s.modifiers |= @as(u32, 1) << @intCast(index);
};
}
fn modifiers(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, _: u32, depressed: u32, latched: u32, locked: u32, group: u32) callconv(.c) void {
const s = state();
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, depressed, latched, locked, 0, 0, group);
updateModifiers();
flushKey();
}
fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void {
const s = state();
flushKey();
@ -216,72 +263,116 @@ fn key(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, serial: u32, _: u32, code: u32
provenance(serial);
if (pressed != 0 and !Popup.active()) popupTrigger(s.key_focus, serial);
if (code < s.held.len) s.held[code] = pressed != 0;
// The compositor supplies the authoritative modifier/group mask. Running
// XKB key actions locally as well would apply latch/lock actions twice.
s.pending_key = prepareKey(code, pressed != 0, false);
// wl_keyboard has no frame event. A sync boundary lets the following
// authoritative modifiers event supply the public post-event flags even
// when the key and modifier messages arrive in separate socket reads.
if (s.key_sync == null) {
s.key_sync = c.wl_display_sync(b().display);
s.key_sync = c.wl_display_sync(backend().display);
if (s.key_sync != null) _ = c.wl_callback_add_listener(s.key_sync, &key_sync_listener, null) else flushKey();
}
if (pressed != 0 and s.repeat_rate > 0 and s.keymap != null and c.z_xkb_keymap_key_repeats.?(s.keymap, code + 8) != 0) {
s.repeat_key = code;
s.repeat_at = runtime.now(b().app.io) + @as(u64, s.repeat_delay) * std.time.ns_per_ms;
s.repeat_at = runtime.now(backend().app.io) + @as(u64, s.repeat_delay) * std.time.ns_per_ms;
} else if (s.repeat_key == code) s.repeat_key = null;
}
fn prepareKey(code: u32, down: bool, repeated: bool) Key {
const s = state();
var value: Key = .{ .code = code, .down = down, .repeated = repeated, .sym = if (s.state != null) c.z_xkb_state_key_get_one_sym.?(s.state, code + 8) else 0, .modifiers = s.modifiers };
var value: Key = .{
.code = code,
.down = down,
.repeated = repeated,
.sym = if (s.state != null)
c.z_xkb_state_key_get_one_sym.?(s.state, code + 8)
else
0,
.modifiers = s.modifiers,
};
if (down and s.state != null) {
const length = c.z_xkb_state_key_get_utf8.?(s.state, code + 8, &value.text, value.text.len);
if (length > 0 and length < value.text.len) value.len = @intCast(length);
}
return value;
}
fn deliverKey(code: u32, down: bool, repeated: bool) void {
emitKey(prepareKey(code, down, repeated));
}
fn emitKey(value: Key) void {
const s = state();
const w = s.key_focus orelse return;
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_KEY;
event.input_id = id();
event.data.key = .{ .physical_key = Keyboard.physical(value.code), .logical_key = if (s.state != null) Keyboard.logical(value.sym) else 0, .modifiers = s.modifiers, .pressed = @intFromBool(value.down), .repeat = @intFromBool(value.repeated) };
event.data.key = .{
.physical_key = Keyboard.physical(value.code),
.logical_key = if (s.state != null) Keyboard.logical(value.sym) else 0,
.modifiers = s.modifiers,
.pressed = @intFromBool(value.down),
.repeat = @intFromBool(value.repeated),
};
if (value.code < s.menu_keys.len) {
if (s.menu_keys[value.code]) {
if (!value.down) s.menu_keys[value.code] = false else if (Popup.active()) Popup.key(event.data.key.logical_key, true, s.serial);
return; // Consume the release/repeats even after flags or focus change.
}
if (Popup.active()) {
s.menu_keys[value.code] = value.down;
Popup.key(event.data.key.logical_key, value.down, s.serial);
return;
}
if (value.down and !value.repeated and !w.text.composing and KdeAppMenu.shortcut(w, event.data.key.logical_key, value.modifiers, event.input_id)) {
if (value.down and
!value.repeated and
!w.text.composing and
KdeAppMenu.shortcut(w, event.data.key.logical_key, value.modifiers, event.input_id))
{
s.menu_keys[value.code] = true;
return;
}
}
if (Popup.active()) return;
send(w, &event);
// Resolve symbols/text before consuming a latched modifier, while reporting
// the compositor's post-event flags in the observational raw event.
if (value.down and w.text.enabled) Text.key(w, value.sym, event.data.key.logical_key, event.input_id, value.modifiers, value.text[0..value.len]);
if (value.down and w.text.enabled) {
Text.key(
w,
value.sym,
event.data.key.logical_key,
event.input_id,
value.modifiers,
value.text[0..value.len],
);
}
}
pub fn flushKey() void {
if (state().pending_key) |value| {
state().pending_key = null;
emitKey(value);
}
}
fn keySynced(_: ?*anyopaque, callback: ?*c.struct_wl_callback, _: u32) callconv(.c) void {
c.wl_callback_destroy(callback);
state().key_sync = null;
flushKey();
}
const key_sync_listener: c.struct_wl_callback_listener = .{ .done = keySynced };
fn repeatInfo(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, rate: i32, delay: i32) callconv(.c) void {
@ -289,30 +380,45 @@ fn repeatInfo(_: ?*anyopaque, _: ?*c.struct_wl_keyboard, rate: i32, delay: i32)
state().repeat_delay = @intCast(@max(0, delay));
if (rate <= 0) state().repeat_key = null;
}
const keyboard_listener: c.struct_wl_keyboard_listener = .{ .keymap = keymap, .enter = keyEnter, .leave = keyLeave, .key = key, .modifiers = modifiers, .repeat_info = repeatInfo };
const keyboard_listener: c.struct_wl_keyboard_listener = .{
.keymap = keymap,
.enter = keyEnter,
.leave = keyLeave,
.key = key,
.modifiers = modifiers,
.repeat_info = repeatInfo,
};
pub fn tick() i32 {
const s = state();
const active = s.key_focus != null;
if (active != s.active) {
s.active = active;
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_APP_ACTIVATION;
event.data.active = @intFromBool(active);
n.z_emit(runtime.toAppHandle(b().app), &event);
n.z_emit(runtime.toAppHandle(backend().app), &event);
}
if (s.pending_key != null) return -1;
if (s.repeat_key) |code| {
const now = runtime.now(b().app.io);
const now = runtime.now(backend().app.io);
if (now >= s.repeat_at) {
deliverKey(code, true, true);
s.repeat_at = now + std.time.ns_per_s / @max(1, s.repeat_rate);
}
return @intCast(@min(1000, (s.repeat_at -| now) / std.time.ns_per_ms + 1));
}
return -1;
}
fn leaveKeyboard() void {
flushKey();
const s = state();
s.modifiers = 0;
s.repeat_key = null;
@ -322,27 +428,41 @@ fn leaveKeyboard() void {
held.* = false;
if (!s.menu_keys[code]) deliverKey(@intCast(code), false, false);
};
Text.cancel(w);
}
s.key_focus = null;
// Preserve consumed held keys until the next enter supplies its held-key set.
s.modifiers = 0;
s.serial = 0;
if (s.state != null) _ = c.z_xkb_state_update_mask.?(s.state, 0, 0, 0, 0, 0, 0);
normal();
normal(n.UHDK_CYCLE_FOCUS_LOST);
}
fn pointerEvent(kind: u32, button_: u32, pressed: bool, delta: n.uhdk_point) void {
if (Popup.active()) return;
const s = state();
const w = s.pointer_focus orelse return;
var e = std.mem.zeroes(n.z_event);
e.type = kind;
e.input_id = id();
e.data.pointer = .{ .position = s.position, .delta = delta, .button = button_, .pressed = @intFromBool(pressed), .modifiers = s.modifiers, .click_count = if (pressed) s.click_count else 0 };
e.data.pointer = .{
.position = s.position,
.delta = delta,
.button = button_,
.pressed = @intFromBool(pressed),
.modifiers = s.modifiers,
.click_count = if (pressed) s.click_count else 0,
};
send(w, &e);
}
fn pointerEnter(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, surface: ?*c.struct_wl_surface, x: i32, y: i32) callconv(.c) void {
leavePointer();
const s = state();
s.pointer_focus = find(surface);
s.pointer_serial = serial;
@ -351,13 +471,16 @@ fn pointerEnter(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, surface:
pointerEvent(n.UHDK_EVENT_POINTER_ENTER, 0, false, .{ .x = 0, .y = 0 });
if (s.pointer_focus) |w| _ = cursor(w, w.cursor);
}
fn pointerLeave(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: ?*c.struct_wl_surface) callconv(.c) void {
leavePointer();
}
fn leavePointer() void {
Popup.pointerLeave();
const s = state();
normal();
normal(n.UHDK_CYCLE_CAPTURE_LOST);
pointerEvent(n.UHDK_EVENT_POINTER_LEAVE, 0, false, .{ .x = 0, .y = 0 });
s.pointer_focus = null;
s.buttons = 0;
@ -368,6 +491,7 @@ fn leavePointer() void {
s.axis_stop = false;
s.last_click_button = 0;
}
fn motion(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, x: i32, y: i32) callconv(.c) void {
const s = state();
const previous = s.position;
@ -376,11 +500,14 @@ fn motion(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, x: i32, y: i32) call
Popup.motion(s.position.x, s.position.y);
return;
}
pointerEvent(n.UHDK_EVENT_POINTER_MOVE, 0, false, .{ .x = s.position.x - previous.x, .y = s.position.y - previous.y });
}
fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u32, pressed: u32) callconv(.c) void {
const s = state();
provenance(serial);
const mapped: u32 = switch (code) {
0x110 => n.UHDK_BUTTON_PRIMARY,
0x111 => n.UHDK_BUTTON_SECONDARY,
@ -389,6 +516,7 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
0x114, 0x115 => n.UHDK_BUTTON_FORWARD,
else => 0,
};
if (mapped == 0) return;
const mask = @as(u32, 1) << @intCast(mapped);
if (Popup.active()) {
@ -396,42 +524,59 @@ fn button(_: ?*anyopaque, _: ?*c.struct_wl_pointer, serial: u32, _: u32, code: u
Popup.button(code, pressed != 0, serial);
return;
}
if (pressed == 0 and s.popup_buttons & mask != 0) {
s.popup_buttons &= ~mask;
return;
}
if (pressed != 0) popupTrigger(s.pointer_focus, serial);
if (pressed != 0) {
s.buttons |= mask;
const now = runtime.now(b().app.io);
const now = runtime.now(backend().app.io);
const dx = s.position.x - s.last_click_position.x;
const dy = s.position.y - s.last_click_position.y;
s.click_count = if (s.last_click_button == mapped and now -| s.last_click_time <= 500 * std.time.ns_per_ms and dx * dx + dy * dy <= 25) @min(3, s.click_count + 1) else 1;
const repeated_click = s.last_click_button == mapped and
now -| s.last_click_time <= 500 * std.time.ns_per_ms and
dx * dx + dy * dy <= 25;
s.click_count = if (repeated_click) @min(3, s.click_count + 1) else 1;
s.last_click_time = now;
s.last_click_button = mapped;
s.last_click_position = s.position;
} else s.buttons &= ~mask;
pointerEvent(n.UHDK_EVENT_POINTER_BUTTON, mapped, pressed != 0, .{ .x = 0, .y = 0 });
if (s.buttons == 0) normal();
if (s.buttons == 0 and s.pointer_mode == n.UHDK_POINTER_CAPTURE) normal(n.UHDK_CYCLE_COMPLETED);
}
fn axis(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, which: u32, value: i32) callconv(.c) void {
const v: f32 = @as(f32, @floatFromInt(value)) / 256;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().axis.y += v else state().axis.x += v;
}
fn axisSource(_: ?*anyopaque, _: ?*c.struct_wl_pointer, source: u32) callconv(.c) void {
state().axis_source = source;
}
fn axisStop(_: ?*anyopaque, _: ?*c.struct_wl_pointer, _: u32, _: u32) callconv(.c) void {
state().axis_stop = true;
}
fn axisDiscrete(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void {
if (c.wl_pointer_get_version(state().pointer) >= 8) return;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().wheel.y += @floatFromInt(value) else state().wheel.x += @floatFromInt(value);
}
fn axis120(_: ?*anyopaque, _: ?*c.struct_wl_pointer, which: u32, value: i32) callconv(.c) void {
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) state().wheel.y += @as(f32, @floatFromInt(value)) / 120 else state().wheel.x += @as(f32, @floatFromInt(value)) / 120;
const amount = @as(f32, @floatFromInt(value)) / 120;
if (which == c.WL_POINTER_AXIS_VERTICAL_SCROLL) {
state().wheel.y += amount;
} else {
state().wheel.x += amount;
}
}
fn frame(_: ?*anyopaque, _: ?*c.struct_wl_pointer) callconv(.c) void {
const s = state();
defer {
@ -439,25 +584,58 @@ fn frame(_: ?*anyopaque, _: ?*c.struct_wl_pointer) callconv(.c) void {
s.wheel = .{ .x = 0, .y = 0 };
s.axis_stop = false;
}
if (Popup.active()) {
const delta = if (s.wheel.y != 0) s.wheel.y * 26 else s.axis.y;
if (delta != 0) Popup.scroll(delta);
return;
}
const w = s.pointer_focus orelse return;
const discrete = s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL or s.axis_source == c.WL_POINTER_AXIS_SOURCE_WHEEL_TILT;
const has_wheel = s.wheel.x != 0 or s.wheel.y != 0;
if (s.axis.x == 0 and s.axis.y == 0 and !has_wheel and !s.axis_stop) return;
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_SCROLL;
e.input_id = id();
e.data.scroll = .{ .position = s.position, .delta = if (has_wheel) s.wheel else s.axis, .unit = if (has_wheel) n.UHDK_SCROLL_LINES else n.UHDK_SCROLL_LOGICAL_PIXELS, .phase = if (discrete) n.UHDK_SCROLL_DISCRETE else if (s.axis_stop) n.UHDK_SCROLL_END else if (!s.scrolling) n.UHDK_SCROLL_BEGIN else n.UHDK_SCROLL_UPDATE, .modifiers = s.modifiers, .momentum = 0 };
e.data.scroll = .{
.position = s.position,
.delta = if (has_wheel) s.wheel else s.axis,
.unit = if (has_wheel) n.UHDK_SCROLL_LINES else n.UHDK_SCROLL_LOGICAL_PIXELS,
.phase = if (discrete)
n.UHDK_SCROLL_DISCRETE
else if (s.axis_stop)
n.UHDK_SCROLL_END
else if (!s.scrolling)
n.UHDK_SCROLL_BEGIN
else
n.UHDK_SCROLL_UPDATE,
.modifiers = s.modifiers,
.momentum = 0,
};
s.scrolling = !discrete and !s.axis_stop;
send(w, &e);
}
const pointer_listener: c.struct_wl_pointer_listener = .{ .enter = pointerEnter, .leave = pointerLeave, .motion = motion, .button = button, .axis = axis, .frame = frame, .axis_source = axisSource, .axis_stop = axisStop, .axis_discrete = axisDiscrete, .axis_value120 = axis120, .axis_relative_direction = null };
const pointer_listener: c.struct_wl_pointer_listener = .{
.enter = pointerEnter,
.leave = pointerLeave,
.motion = motion,
.button = button,
.axis = axis,
.frame = frame,
.axis_source = axisSource,
.axis_stop = axisStop,
.axis_discrete = axisDiscrete,
.axis_value120 = axis120,
.axis_relative_direction = null,
};
pub fn cursor(w: *native.Window, shape: u32) u32 {
w.cursor = shape;
const s = state();
if (shape != n.UHDK_CURSOR_HIDDEN and s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s.pointer_focus != w) return abi.OK;
@ -465,67 +643,150 @@ pub fn cursor(w: *native.Window, shape: u32) u32 {
c.wl_pointer_set_cursor(s.pointer, s.pointer_serial, null, 0, 0);
return abi.OK;
}
if (s.cursor_device == null) return n.UHDK_STATUS_UNSUPPORTED;
const shapes = [_]u32{ c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT };
const shapes = [_]u32{
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED,
c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT,
};
c.wp_cursor_shape_device_v1_set_shape(s.cursor_device, s.pointer_serial, shapes[shape]);
return abi.OK;
}
pub fn capture(w: *native.Window, enabled: bool) u32 {
pub fn pointerMode(w: *native.Window, mode: u32) u32 {
const s = state();
if (enabled and (s.pointer_focus != w or s.buttons == 0)) return abi.UNAVAILABLE;
if (!enabled) {
normal();
if (mode == n.UHDK_POINTER_NORMAL) {
release(w, n.UHDK_CYCLE_CAPTURE_RELEASED);
return abi.OK;
}
s.captured = true;
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED;
e.data.pointer_mode = n.UHDK_POINTER_CAPTURE;
send(w, &e);
if (s.mode_window == w and (s.pointer_mode == mode or (mode == n.UHDK_POINTER_CONFINED and s.confined != null))) {
return abi.OK;
}
if (mode == n.UHDK_POINTER_CAPTURE and (s.pointer_focus != w or s.buttons == 0)) return abi.UNAVAILABLE;
if (mode == n.UHDK_POINTER_CONFINED) {
if (s.constraints == null or s.pointer == null) return n.UHDK_STATUS_UNSUPPORTED;
if (s.key_focus != w or s.pointer_focus != w or !w.want_visible or s.position.x < 0 or s.position.y < 0 or s.position.x >= @as(f32, @floatFromInt(w.width)) or s.position.y >= @as(f32, @floatFromInt(w.height))) {
return abi.UNAVAILABLE;
}
const constraint = c.zwp_pointer_constraints_v1_confine_pointer(
s.constraints,
w.surface,
s.pointer,
null, // The complete surface input region follows content resizes.
c.ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT,
) orelse return abi.OOM;
normal(n.UHDK_CYCLE_CAPTURE_RELEASED);
s.mode_window = w;
s.confined = constraint;
_ = c.zwp_confined_pointer_v1_add_listener(constraint, &confined_listener, null);
return abi.OK; // Only the compositor's confined event confirms activation.
}
normal(n.UHDK_CYCLE_CAPTURE_RELEASED);
s.mode_window = w;
s.pointer_mode = mode;
modeEvent(w, mode, n.UHDK_CYCLE_CAPTURE_RELEASED);
return abi.OK;
}
fn normal() void {
const s = state();
if (!s.captured) return;
s.captured = false;
if (s.pointer_focus) |w| {
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED;
e.data.pointer_mode = n.UHDK_POINTER_NORMAL;
send(w, &e);
}
fn modeEvent(w: *native.Window, mode: u32, reason: n.uhdk_cycle_end_reason) void {
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_POINTER_MODE_CHANGED;
e.data.pointer_mode = mode;
e.cycle_end_reason = reason;
send(w, &e);
}
fn normal(reason: n.uhdk_cycle_end_reason) void {
const s = state();
const w = s.mode_window orelse return;
if (s.confined != null) c.zwp_confined_pointer_v1_destroy(s.confined);
s.confined = null;
s.mode_window = null;
s.pointer_mode = n.UHDK_POINTER_NORMAL;
modeEvent(w, n.UHDK_POINTER_NORMAL, reason);
}
pub fn release(w: *native.Window, reason: n.uhdk_cycle_end_reason) void {
if (state().mode_window == w) normal(reason);
}
fn confined(_: ?*anyopaque, object: ?*c.struct_zwp_confined_pointer_v1) callconv(.c) void {
const s = state();
if (object != s.confined) return;
const w = s.mode_window orelse return;
if (s.pointer_mode == n.UHDK_POINTER_CONFINED) return;
s.pointer_mode = n.UHDK_POINTER_CONFINED;
modeEvent(w, n.UHDK_POINTER_CONFINED, n.UHDK_CYCLE_COMPLETED);
}
fn unconfined(_: ?*anyopaque, object: ?*c.struct_zwp_confined_pointer_v1) callconv(.c) void {
if (object == state().confined) normal(n.UHDK_CYCLE_CAPTURE_LOST);
}
const confined_listener: c.struct_zwp_confined_pointer_v1_listener = .{
.confined = confined,
.unconfined = unconfined,
};
fn popupTrigger(w: ?*native.Window, serial: u32) void {
const s = state();
s.popup_window = w;
s.popup_serial = serial;
s.popup_time = runtime.now(b().app.io);
s.popup_time = runtime.now(backend().app.io);
}
pub fn beginPopup() void {
normal();
normal(n.UHDK_CYCLE_CAPTURE_LOST);
state().buttons = 0;
state().scrolling = false;
}
pub fn clearPopupTrigger(w: *native.Window) void {
if (state().popup_window == w) {
state().popup_window = null;
state().popup_serial = 0;
}
}
pub fn forget(w: *native.Window) void {
release(w, n.UHDK_CYCLE_CANCELLED);
clearPopupTrigger(w);
if (state().key_focus == w) leaveKeyboard();
if (state().pointer_focus == w) leavePointer();
Text.forget(w);
}
pub fn remove(name: u32) void {
if (name == state().seat_name) releaseSeat();
if (state().constraints != null and name == state().constraints_name) {
if (state().confined != null) normal(n.UHDK_CYCLE_CAPTURE_LOST);
c.zwp_pointer_constraints_v1_destroy(state().constraints);
state().constraints = null;
state().constraints_name = 0;
setup();
}
}
fn releaseSeat() void {
Popup.deinit();
state().popup_serial = 0;
state().popup_window = null;
Data.releaseSeat();
const s = state();
if (s.key_sync != null) c.wl_callback_destroy(s.key_sync);
s.key_sync = null;
@ -544,11 +805,13 @@ fn releaseSeat() void {
s.seat = null;
setup();
}
pub fn deinit() void {
const s = state();
releaseSeat();
if (s.text_manager != null) c.zwp_text_input_manager_v3_destroy(s.text_manager);
if (s.cursor_manager != null) c.wp_cursor_shape_manager_v1_destroy(s.cursor_manager);
if (s.constraints != null) c.zwp_pointer_constraints_v1_destroy(s.constraints);
if (s.compose != null) c.z_xkb_compose_state_unref.?(s.compose);
if (s.compose_table != null) c.z_xkb_compose_table_unref.?(s.compose_table);
if (s.state != null) c.z_xkb_state_unref.?(s.state);

View File

@ -23,88 +23,116 @@ const Node = struct {
label: [:0]const u8 = "",
flags: u32 = 0,
};
pub const Export = struct {
next: ?*Export = null, // Temporary transaction list, never an object registry.
window: *native.Window,
window: ?*native.Window,
tray: ?*n.uhdk_tray = null,
registry_next: ?*Export = null,
connection: ?*c.DBusConnection = null,
root: *Resource,
arena: std.heap.ArenaAllocator,
nodes: std.ArrayList(Node) = .empty,
path: [:0]const u8,
proxy: ?*c.struct_org_kde_kwin_appmenu = null,
};
pub const State = struct {
manager: ?*c.struct_org_kde_kwin_appmenu_manager = null,
global_name: u32 = 0,
sequence: u64 = 0,
app_menu: ?*Resource = null,
exports: ?*Export = null,
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
fn s() *State {
return &b().menus;
fn menuState() *State {
return &backend().menus;
}
fn same(a: []const u8, z: []const u8) bool {
return std.mem.eql(u8, a, z);
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, version: u32) void {
if (!same(interface, "org_kde_kwin_appmenu_manager") or s().manager != null) return;
s().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2)));
s().global_name = name;
if (!same(interface, "org_kde_kwin_appmenu_manager") or menuState().manager != null) return;
menuState().manager = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_org_kde_kwin_appmenu_manager_interface, @min(version, 2)));
menuState().global_name = name;
ready();
}
pub fn remove(name: u32) void {
if (name != s().global_name) return;
if (name != menuState().global_name) return;
disconnected();
destroyManager();
}
fn destroyManager() void {
if (s().manager) |manager| {
if (menuState().manager) |manager| {
if (c.org_kde_kwin_appmenu_manager_get_version(manager) >= 2) c.org_kde_kwin_appmenu_manager_release(manager) else c.org_kde_kwin_appmenu_manager_destroy(manager);
}
s().manager = null;
s().global_name = 0;
menuState().manager = null;
menuState().global_name = 0;
}
pub fn ready() void {
native.setCapability(n.UHDK_CAP_APP_MENU, s().manager != null and b().portal.ready);
var cursor = b().windows;
native.setCapability(n.UHDK_CAP_APP_MENU, menuState().manager != null and backend().portal.ready);
var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| associate(e);
}
fn associate(e: *Export) void {
if (e.proxy != null or s().manager == null or !b().portal.ready) return;
const window = e.window orelse return;
if (e.proxy != null or menuState().manager == null or !backend().portal.ready) return;
// The export is already reachable by process() before advertising it.
e.proxy = c.org_kde_kwin_appmenu_manager_create(s().manager, e.window.surface) orelse return;
c.org_kde_kwin_appmenu_set_address(e.proxy, b().portal.unique.?.ptr, e.path.ptr);
e.proxy = c.org_kde_kwin_appmenu_manager_create(menuState().manager, window.surface) orelse return;
c.org_kde_kwin_appmenu_set_address(e.proxy, backend().portal.unique.?.ptr, e.path.ptr);
}
pub fn disconnected() void {
native.setCapability(n.UHDK_CAP_APP_MENU, false);
var cursor = b().windows;
var cursor = backend().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| unassociate(e);
}
fn unassociate(e: *Export) void {
if (e.proxy != null) c.org_kde_kwin_appmenu_release(e.proxy);
e.proxy = null;
}
fn destroy(e: *Export) void {
pub fn destroy(e: *Export) void {
var link = &menuState().exports;
while (link.* != e) link = &link.*.?.registry_next;
link.* = e.registry_next;
unassociate(e);
runtime.release(e.root);
e.arena.deinit();
b().app.gpa.destroy(e);
backend().app.gpa.destroy(e);
}
fn add(e: *Export, menu: *Resource, parent: usize) !void {
var previous: usize = 0;
for (menu.payload.menu.items) |*item| {
// Bound work and D-Bus message size even for repeatedly shared subtrees.
if (e.nodes.items.len >= 65536) return error.OutOfMemory;
const index = e.nodes.items.len;
const allocator = e.arena.allocator();
// D-BusMenu uses '_' as a mnemonic marker; UHDK labels are literal text.
var label: std.ArrayList(u8) = .empty;
for (abi.textBytes(item.label)) |byte| {
try label.append(allocator, byte);
if (byte == '_') try label.append(allocator, '_');
}
try label.append(allocator, 0);
try e.nodes.append(allocator, .{ .item = item, .parent = parent, .label = label.items[0 .. label.items.len - 1 :0], .flags = item.flags });
if (previous == 0) e.nodes.items[parent].first = index else e.nodes.items[previous].next = index;
@ -112,35 +140,48 @@ fn add(e: *Export, menu: *Resource, parent: usize) !void {
if (item.submenu) |child| try add(e, @ptrCast(@alignCast(child)), index);
}
}
fn create(w: *native.Window, root: *Resource) !*Export {
const e = try b().app.gpa.create(Export);
errdefer b().app.gpa.destroy(e);
s().sequence += 1;
e.* = .{ .window = w, .root = root, .arena = .init(b().app.gpa), .path = "" };
fn create(w: ?*native.Window, root: *Resource) !*Export {
const e = try backend().app.gpa.create(Export);
errdefer backend().app.gpa.destroy(e);
menuState().sequence += 1;
e.* = .{ .window = w, .root = root, .arena = .init(backend().app.gpa), .path = "" };
errdefer e.arena.deinit();
e.path = try std.fmt.allocPrintSentinel(e.arena.allocator(), prefix ++ "{d}", .{s().sequence}, 0);
e.path = try std.fmt.allocPrintSentinel(e.arena.allocator(), prefix ++ "{d}", .{menuState().sequence}, 0);
try e.nodes.append(e.arena.allocator(), .{});
try add(e, root, 0);
runtime.retain(root);
e.registry_next = menuState().exports;
menuState().exports = e;
return e;
}
pub fn createTray(tray: *n.uhdk_tray, root: *Resource) !*Export {
const e = try create(null, root);
e.tray = tray;
return e;
}
fn replace(w: *native.Window, e: ?*Export) void {
const old = w.menu_export;
w.menu_export = e;
if (old) |value| destroy(value);
if (e) |value| associate(value);
}
pub fn inherit(w: *native.Window) !void {
if (s().app_menu) |root| replace(w, try create(w, root));
if (menuState().app_menu) |root| replace(w, try create(w, root));
}
pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
const root: ?*Resource = if (menu) |p| @ptrCast(@alignCast(p)) else null;
if (root != null) {
if (s().manager == null) return n.UHDK_STATUS_UNSUPPORTED;
if (b().portal.connection == null) return abi.UNAVAILABLE;
if (menuState().manager == null) return n.UHDK_STATUS_UNSUPPORTED;
if (backend().portal.connection == null) return abi.UNAVAILABLE;
}
if (w) |window| {
const effective = root orelse s().app_menu;
const effective = root orelse menuState().app_menu;
const e = if (effective) |r| create(window, r) catch return abi.OOM else null;
if (root) |r| runtime.retain(r);
if (window.menu_override) |r| runtime.release(r);
@ -153,57 +194,69 @@ pub fn attach(w: ?*native.Window, menu: ?*anyopaque) u32 {
pending = e.next;
destroy(e);
};
if (root) |r| {
var cursor = b().windows;
var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
const e = create(window, r) catch return abi.OOM;
e.next = pending;
pending = e;
};
runtime.retain(r);
}
if (s().app_menu) |r| runtime.release(r);
s().app_menu = root;
if (menuState().app_menu) |r| runtime.release(r);
menuState().app_menu = root;
if (root == null) {
var cursor = b().windows;
var cursor = backend().windows;
while (cursor) |window| : (cursor = window.next) if (window.menu_override == null) {
replace(window, null);
};
}
while (pending) |e| {
pending = e.next;
e.next = null;
replace(e.window, e);
replace(e.window.?, e);
}
}
return abi.OK;
}
pub fn forget(w: *native.Window) void {
replace(w, null);
if (w.menu_override) |root| runtime.release(root);
w.menu_override = null;
}
pub fn deinit() void {
if (s().app_menu) |root| runtime.release(root);
s().app_menu = null;
if (menuState().app_menu) |root| runtime.release(root);
menuState().app_menu = null;
destroyManager();
}
fn enabled(e: *Export, index: usize) bool {
var i = index;
while (i != 0) : (i = e.nodes.items[i].parent) if (e.nodes.items[i].item.?.flags & n.UHDK_MENU_DISABLED != 0) return false;
return true;
}
fn activate(e: *Export, index: usize, input_id: u64) void {
const item = e.nodes.items[index].item orelse return;
if (!enabled(e, index) or item.flags & n.UHDK_MENU_SEPARATOR != 0 or item.submenu != null) return;
Menu.activate(e.window, item, input_id);
if (e.tray) |tray| n.z_tray_command(tray, item) else Menu.activate(e.window.?, item, input_id);
}
fn folded(key: u32) u32 {
return if (key >= 'A' and key <= 'Z') key + ('a' - 'A') else key;
}
pub fn shortcut(w: *native.Window, key: u32, mods: u32, input_id: u64) bool {
const e = w.menu_export orelse return false;
if (key == 0) return false;
const mask: u32 = n.UHDK_MOD_SHIFT | n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER;
for (e.nodes.items[1..], 1..) |node, i| {
const item = node.item.?;
@ -213,17 +266,21 @@ pub fn shortcut(w: *native.Window, key: u32, mods: u32, input_id: u64) bool {
return true;
}
}
return false;
}
fn nodeId(e: *Export, value: i32) ?usize {
return if (value >= 0 and value < e.nodes.items.len) @intCast(value) else null;
}
fn variant(i: *Bus.Iter, comptime sig: [:0]const u8, value: anytype) !void {
var v = try Bus.open(i, c.DBUS_TYPE_VARIANT, sig);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(i, &v);
try Bus.basic(&v, sig[0], value);
try Bus.close(i, &v);
}
fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
const node = e.nodes.items[index];
const item = node.item;
@ -231,8 +288,10 @@ fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
if (same(name, "type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_SEPARATOR != 0) "separator" else "standard")) else if (same(name, "label")) try variant(out, "s", node.label.ptr) else if (same(name, "enabled")) try variant(out, "b", @as(u32, @intFromBool(enabled(e, index)))) else if (same(name, "visible")) try variant(out, "b", @as(u32, 1)) else if (same(name, "children-display")) try variant(out, "s", @as([*:0]const u8, if (index == 0 or (item != null and item.?.submenu != null)) "submenu" else "")) else if (same(name, "toggle-type")) try variant(out, "s", @as([*:0]const u8, if (flags & n.UHDK_MENU_CHECKED != 0) "checkmark" else "")) else if (same(name, "toggle-state")) try variant(out, "i", @as(i32, if (flags & n.UHDK_MENU_CHECKED != 0) 1 else 0)) else if (same(name, "shortcut")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "aas");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var arrays = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "as");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&v, &arrays);
var buffer: [32]u8 = undefined;
if (item) |value| if (Menu.keyName(value.shortcut_key, &buffer)) |key_name| {
var keys = try Bus.open(&arrays, c.DBUS_TYPE_ARRAY, "s");
@ -240,23 +299,29 @@ fn property(e: *Export, index: usize, name: []const u8, out: *Bus.Iter) !bool {
inline for (.{ .{ n.UHDK_MOD_CONTROL, "Control" }, .{ n.UHDK_MOD_ALT, "Alt" }, .{ n.UHDK_MOD_SHIFT, "Shift" }, .{ n.UHDK_MOD_SUPER, "Super" } }) |mod| {
if (value.shortcut_modifiers & mod[0] != 0) try Bus.string(&keys, mod[1]);
}
try Bus.string(&keys, key_name.ptr);
try Bus.close(&arrays, &keys);
};
try Bus.close(&v, &arrays);
try Bus.close(out, &v);
} else return false;
return true;
}
fn wanted(filter: ?Bus.Iter, name: []const u8) bool {
var iter = filter orelse return true;
if (Bus.kind(&iter) == c.DBUS_TYPE_INVALID) return true;
while (Bus.str(&iter)) |value| {
if (same(value, name)) return true;
if (!Bus.next(&iter)) break;
}
return false;
}
fn props(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
var dict = try Bus.open(out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &dict);
@ -267,13 +332,16 @@ fn props(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
_ = try property(e, index, name, &pair);
try Bus.close(&dict, &pair);
};
try Bus.close(out, &dict);
}
fn layout(e: *Export, index: usize, depth: i32, filter: Bus.Iter, out: *Bus.Iter) Bus.Error!void {
var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple);
try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(index)));
try props(e, index, filter, &tuple);
var children = try Bus.open(&tuple, c.DBUS_TYPE_ARRAY, "v");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&tuple, &children);
if (depth != 0) {
@ -285,9 +353,11 @@ fn layout(e: *Export, index: usize, depth: i32, filter: Bus.Iter, out: *Bus.Iter
try Bus.close(&children, &v);
}
}
try Bus.close(&tuple, &children);
try Bus.close(out, &tuple);
}
fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void {
var tuple = try Bus.open(out, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &tuple);
@ -295,41 +365,60 @@ fn groupItem(e: *Export, index: usize, filter: ?Bus.Iter, out: *Bus.Iter) !void
try props(e, index, filter, &tuple);
try Bus.close(out, &tuple);
}
pub fn updateFlags() u32 {
var cursor = b().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
var cursor = menuState().exports;
while (cursor) |e| : (cursor = e.registry_next) {
changed(e) catch return abi.OOM;
};
}
return abi.OK;
}
fn changed(e: *Export) !void {
var dirty = false;
for (e.nodes.items[1..]) |node| if (node.flags != node.item.?.flags) {
dirty = true;
break;
};
if (!dirty) return;
if (b().portal.ready and e.proxy != null) {
if ((backend().portal.ready and e.proxy != null) or e.connection != null) {
const message = c.z_dbus_message_new_signal.?(e.path.ptr, iface, "ItemsPropertiesUpdated") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message);
var out = Bus.append(message);
var updates = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &updates);
// Include descendants: a disabled ancestor also disables their activation.
for (e.nodes.items[1..], 1..) |_, i| try groupItem(e, i, null, &updates);
try Bus.close(&out, &updates);
var removed = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ias)");
try Bus.close(&out, &removed);
_ = try Portal.send(message);
_ = try send(e, message);
}
for (e.nodes.items[1..]) |*node| node.flags = node.item.?.flags;
}
fn fail(message: *Bus.Message, name: [*:0]const u8) !void {
fn send(e: *Export, message: *Bus.Message) !u32 {
if (e.connection) |connection| {
var serial: u32 = 0;
if (c.z_dbus_connection_send.?(connection, message, &serial) == 0) return error.OutOfMemory;
return serial;
}
return Portal.send(message);
}
fn fail(e: *Export, message: *Bus.Message, name: [*:0]const u8) !void {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return;
const reply = c.z_dbus_message_new_error.?(message, name, "Menu request could not be handled") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
_ = try Portal.send(reply);
_ = try send(e, reply);
}
const invalid = "org.freedesktop.DBus.Error.InvalidArgs";
const missing = "com.canonical.dbusmenu.Error.InvalidMenuItem";
fn callIs(message: *Bus.Message, interface: []const u8, member: []const u8) bool {
@ -337,51 +426,68 @@ fn callIs(message: *Bus.Message, interface: []const u8, member: []const u8) bool
const z = c.z_dbus_message_get_member.?(message);
return a != null and z != null and same(std.mem.span(a), interface) and same(std.mem.span(z), member);
}
fn signature(message: *Bus.Message, sig: [*:0]const u8) bool {
return c.z_dbus_message_has_signature.?(message, sig) != 0;
}
fn globalProperty(name: []const u8, out: *Bus.Iter) !bool {
if (same(name, "Version")) try variant(out, "u", @as(u32, 3)) else if (same(name, "TextDirection")) try variant(out, "s", @as([*:0]const u8, "ltr")) else if (same(name, "Status")) try variant(out, "s", @as([*:0]const u8, "normal")) else if (same(name, "IconThemePath")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "as");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var paths = try Bus.open(&v, c.DBUS_TYPE_ARRAY, "s");
try Bus.close(&v, &paths);
try Bus.close(out, &v);
} else return false;
return true;
}
pub fn process(message: *Bus.Message) !bool {
if (c.z_dbus_message_get_type.?(message) != c.DBUS_MESSAGE_TYPE_METHOD_CALL) return false;
const path = c.z_dbus_message_get_path.?(message);
if (path == null or !std.mem.startsWith(u8, std.mem.span(path), prefix)) return false;
var found: ?*Export = null;
var cursor = b().windows;
while (cursor) |w| : (cursor = w.next) if (w.menu_export) |e| {
if (same(e.path, std.mem.span(path))) {
var cursor = menuState().exports;
while (cursor) |e| : (cursor = e.registry_next) {
if (e.tray == null and same(e.path, std.mem.span(path))) {
found = e;
break;
}
};
if (found) |e| try dispatch(e, message) else try fail(message, "org.freedesktop.DBus.Error.UnknownObject");
}
if (found) |e| {
try dispatch(e, message);
} else {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return true;
const reply = c.z_dbus_message_new_error.?(message, "org.freedesktop.DBus.Error.UnknownObject", "Unknown menu") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
_ = try Portal.send(reply);
}
return true;
}
fn dispatch(e: *Export, message: *Bus.Message) !void {
pub fn dispatch(e: *Export, message: *Bus.Message) !void {
const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
var out = Bus.append(reply);
var args = Bus.parse(message);
if (callIs(message, "org.freedesktop.DBus.Introspectable", "Introspect")) {
if (!signature(message, "")) return fail(message, invalid);
if (!signature(message, "")) return fail(e, message, invalid);
try Bus.string(&out, @embedFile("dbusmenu.xml"));
} else if (callIs(message, "org.freedesktop.DBus.Peer", "Ping")) {
if (!signature(message, "")) return fail(message, invalid);
if (!signature(message, "")) return fail(e, message, invalid);
} else if (callIs(message, "org.freedesktop.DBus.Properties", "Get") or callIs(message, "org.freedesktop.DBus.Properties", "GetAll")) {
const single = callIs(message, "org.freedesktop.DBus.Properties", "Get");
if (!signature(message, if (single) "ss" else "s")) return fail(message, invalid);
if (!same(Bus.str(&args).?, iface)) return fail(message, "org.freedesktop.DBus.Error.UnknownInterface");
if (!signature(message, if (single) "ss" else "s")) return fail(e, message, invalid);
if (!same(Bus.str(&args).?, iface)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownInterface");
if (single) {
_ = Bus.next(&args);
if (!try globalProperty(Bus.str(&args).?, &out)) return fail(message, "org.freedesktop.DBus.Error.UnknownProperty");
if (!try globalProperty(Bus.str(&args).?, &out)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else {
var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
@ -392,21 +498,27 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
_ = try globalProperty(name, &pair);
try Bus.close(&dict, &pair);
}
try Bus.close(&out, &dict);
}
} else if (callIs(message, iface, "GetLayout")) {
if (!signature(message, "iias")) return fail(message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
if (!signature(message, "iias")) return fail(e, message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
const depth = Bus.int(&args).?;
if (depth < -1) return fail(message, invalid);
if (depth < -1) return fail(e, message, invalid);
_ = Bus.next(&args);
try Bus.basic(&out, c.DBUS_TYPE_UINT32, @as(u32, 1));
try layout(e, index, depth, Bus.child(&args), &out);
} else if (callIs(message, iface, "GetGroupProperties")) {
if (!signature(message, "aias")) return fail(message, invalid);
if (!signature(message, "aias")) return fail(e, message, invalid);
var ids = Bus.child(&args);
_ = Bus.next(&args);
const filter = Bus.child(&args);
var items = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "(ia{sv})");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &items);
@ -416,31 +528,38 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
if (nodeId(e, value)) |i| try groupItem(e, i, filter, &items);
if (!Bus.next(&ids)) break;
}
try Bus.close(&out, &items);
} else if (callIs(message, iface, "GetProperty")) {
if (!signature(message, "is")) return fail(message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
if (!signature(message, "is")) return fail(e, message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
if (!try property(e, index, Bus.str(&args).?, &out)) return fail(message, "org.freedesktop.DBus.Error.UnknownProperty");
if (!try property(e, index, Bus.str(&args).?, &out)) return fail(e, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else if (callIs(message, iface, "Event")) {
if (!signature(message, "isvu")) return fail(message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
if (!signature(message, "isvu")) return fail(e, message, invalid);
const index = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
_ = Bus.next(&args);
if (same(Bus.str(&args).?, "clicked")) activate(e, index, Input.id());
} else if (callIs(message, iface, "AboutToShow")) {
if (!signature(message, "i")) return fail(message, invalid);
_ = nodeId(e, Bus.int(&args).?) orelse return fail(message, missing);
if (!signature(message, "i")) return fail(e, message, invalid);
_ = nodeId(e, Bus.int(&args).?) orelse return fail(e, message, missing);
try Bus.basic(&out, c.DBUS_TYPE_BOOLEAN, @as(u32, 0));
} else if (callIs(message, iface, "EventGroup") or callIs(message, iface, "AboutToShowGroup")) {
const events = callIs(message, iface, "EventGroup");
if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(message, invalid);
if (!signature(message, if (events) "a(isvu)" else "ai")) return fail(e, message, invalid);
var ids = Bus.child(&args);
if (!events) {
var empty = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i");
try Bus.close(&out, &empty);
}
var errors = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "i");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &errors);
var valid_count: usize = 0;
var error_count: usize = 0;
while (Bus.kind(&ids) != c.DBUS_TYPE_INVALID) {
@ -456,10 +575,12 @@ fn dispatch(e: *Export, message: *Bus.Message) !void {
error_count += 1;
try Bus.basic(&errors, c.DBUS_TYPE_INT32, number);
}
if (!Bus.next(&ids)) break;
}
try Bus.close(&out, &errors);
if (valid_count == 0 and error_count != 0) return fail(message, missing);
} else return fail(message, "org.freedesktop.DBus.Error.UnknownMethod");
if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try Portal.send(reply);
if (valid_count == 0 and error_count != 0) return fail(e, message, missing);
} else return fail(e, message, "org.freedesktop.DBus.Error.UnknownMethod");
if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try send(e, reply);
}

View File

@ -6,7 +6,7 @@ const n = @import("native");
/// physical positions, independently of the compositor-supplied XKB layout.
pub fn physical(code: u32) u32 {
const map = comptime blk: {
var t = [_]u16{0} ** 256;
var t: [256]u16 = @splat(0);
const pairs = [_][2]u16{
.{ 1, 41 }, .{ 12, 45 }, .{ 13, 46 }, .{ 14, 42 }, .{ 15, 43 }, .{ 26, 47 }, .{ 27, 48 }, .{ 28, 40 }, .{ 29, 224 },
.{ 39, 51 }, .{ 40, 52 }, .{ 41, 53 }, .{ 42, 225 }, .{ 43, 49 }, .{ 51, 54 }, .{ 52, 55 }, .{ 53, 56 }, .{ 54, 229 },
@ -16,6 +16,7 @@ pub fn physical(code: u32) u32 {
.{ 102, 74 }, .{ 103, 82 }, .{ 104, 75 }, .{ 105, 80 }, .{ 106, 79 }, .{ 107, 77 }, .{ 108, 81 }, .{ 109, 78 }, .{ 110, 73 },
.{ 111, 76 }, .{ 119, 72 }, .{ 125, 227 }, .{ 126, 231 }, .{ 127, 101 },
};
for (pairs) |p| t[p[0]] = p[1];
for (0..10) |i| t[2 + i] = 30 + i;
for (0..10) |i| t[59 + i] = 58 + i;
@ -27,6 +28,7 @@ pub fn physical(code: u32) u32 {
};
return if (code < map.len) map[code] else 0;
}
pub fn logical(sym: u32) u32 {
return switch (sym) {
c.XKB_KEY_Escape => n.UHDK_KEY_ESCAPE,
@ -47,6 +49,7 @@ pub fn logical(sym: u32) u32 {
else => c.z_xkb_keysym_to_utf32.?(sym),
};
}
pub fn edit(key: u32, mods: u32) u32 {
return n.z_edit_key(key, mods);
}

View File

@ -18,8 +18,10 @@ pub fn activate(window: *native.Window, item: *const n.uhdk_menu_item, input_id:
Input.send(window, &event);
}
}
pub fn keyName(key: u32, buffer: *[32]u8) ?[:0]const u8 {
if (key >= n.UHDK_KEY_F1 and key < n.UHDK_KEY_F1 + 24) return std.fmt.bufPrintZ(buffer, "F{d}", .{key - n.UHDK_KEY_F1 + 1}) catch unreachable;
if (key >= n.UHDK_KEY_F1 and key < n.UHDK_KEY_F1 + 24) return std.mem.printSentinel(buffer, "F{d}", .{key - n.UHDK_KEY_F1 + 1}, 0) catch unreachable;
switch (key) {
n.UHDK_KEY_ESCAPE => return "Escape",
n.UHDK_KEY_ENTER => return "Return",
@ -38,7 +40,9 @@ pub fn keyName(key: u32, buffer: *[32]u8) ?[:0]const u8 {
' ' => return "space",
else => {},
}
if (key < 0x21 or key > 0x10ffff) return null;
const k = if (key >= 'a' and key <= 'z') key - ('a' - 'A') else key;
const len = std.unicode.utf8Encode(@intCast(k), buffer) catch return null;
buffer[len] = 0;
@ -55,6 +59,7 @@ pub fn shortcut(item: n.uhdk_menu_item, buffer: *[96]u8) []const u8 {
end += mod[1].len;
}
}
@memcpy(buffer[end..][0..key.len], key);
end += key.len;
return buffer[0..end];

View File

@ -10,7 +10,13 @@ const abi = @import("../abi.zig");
const Input = @import("Input.zig");
const Menu = @import("Menu.zig");
const Bitmap = @import("Bitmap.zig");
const Buffer = struct { proxy: ?*c.struct_wl_buffer = null, mapping: ?*anyopaque = null, size: usize = 0, busy: bool = false };
const Buffer = struct {
proxy: ?*c.struct_wl_buffer = null,
mapping: ?*anyopaque = null,
size: usize = 0,
busy: bool = false,
};
const Panel = struct {
parent: ?*Panel,
menu: *Resource,
@ -31,6 +37,7 @@ const Panel = struct {
dirty: bool = true,
deadline: u64 = 0,
};
pub const State = struct {
window: ?*native.Window = null,
root: ?*Resource = null,
@ -40,150 +47,184 @@ pub const State = struct {
serial: u32 = 0,
hover_at: u64 = 0,
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
fn s() *State {
return &b().popup;
fn popupState() *State {
return &backend().popup;
}
pub fn active() bool {
return s().request != 0;
return popupState().request != 0;
}
pub fn capability() void {
native.setCapability(n.UHDK_CAP_CONTEXT_MENU, b().desktop.shm != null and Input.state().seat != null);
native.setCapability(n.UHDK_CAP_CONTEXT_MENU, backend().desktop.shm != null and Input.state().seat != null);
}
fn panel(raw: ?*anyopaque) *Panel {
return @ptrCast(@alignCast(raw.?));
}
fn rowHeight(item: n.uhdk_menu_item) i32 {
return if (item.flags & n.UHDK_MENU_SEPARATOR != 0) 9 else 26;
}
fn usable(item: n.uhdk_menu_item) bool {
return item.flags & (n.UHDK_MENU_DISABLED | n.UHDK_MENU_SEPARATOR) == 0;
}
fn rowY(p: *Panel, index: usize) i32 {
var y: i32 = 4;
for (p.menu.payload.menu.items[0..index]) |item| y += rowHeight(item);
return y - p.scroll;
}
fn lookup(surface: ?*c.struct_wl_surface) ?*Panel {
var cursor = s().top;
var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) if (p.surface == surface) return p;
return null;
}
pub fn owner(surface: ?*c.struct_wl_surface) ?*native.Window {
return if (lookup(surface) != null) s().window else null;
return if (lookup(surface) != null) popupState().window else null;
}
fn freeBuffer(buf: *Buffer) void {
if (buf.proxy != null) c.wl_buffer_destroy(buf.proxy);
if (buf.mapping) |mapping| _ = c.munmap(mapping, buf.size);
buf.* = .{};
}
fn destroy(p: *Panel) void {
if (s().pointer == p) s().pointer = null;
if (popupState().pointer == p) popupState().pointer = null;
if (p.popup != null) c.xdg_popup_destroy(p.popup);
if (p.xdg != null) c.xdg_surface_destroy(p.xdg);
if (p.surface != null) c.wl_surface_destroy(p.surface);
for (&p.buffers) |*buf| freeBuffer(buf);
b().app.gpa.destroy(p);
backend().app.gpa.destroy(p);
}
fn closeChildren(p: *Panel) void {
while (s().top != p) {
const top = s().top orelse return;
s().top = top.parent;
while (popupState().top != p) {
const top = popupState().top orelse return;
popupState().top = top.parent;
destroy(top);
}
}
fn finish(status: u32) void {
if (!active()) return;
const request_id = s().request;
while (s().top) |top| {
s().top = top.parent;
const request_id = popupState().request;
while (popupState().top) |top| {
popupState().top = top.parent;
destroy(top);
}
const root = s().root.?;
s().* = .{};
const root = popupState().root.?;
popupState().* = .{};
runtime.release(root);
n.z_complete(runtime.toAppHandle(b().app), request_id, status, null);
n.z_complete(runtime.toAppHandle(backend().app), request_id, status, null);
}
pub fn forget(w: *native.Window) void {
if (s().window == w) finish(abi.CANCELLED);
if (popupState().window == w) finish(abi.CANCELLED);
}
pub fn cancel(id: u64) bool {
if (s().request != id or !active()) return false;
if (popupState().request != id or !active()) return false;
finish(abi.CANCELLED);
return true;
}
pub fn deinit() void {
finish(abi.CANCELLED);
}
pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (active()) return n.UHDK_STATUS_BUSY;
if (b().desktop.shm == null or Input.state().seat == null) return n.UHDK_STATUS_UNSUPPORTED;
if (backend().desktop.shm == null or Input.state().seat == null) return n.UHDK_STATUS_UNSUPPORTED;
const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.other) orelse return abi.UNAVAILABLE));
const input = Input.state();
if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(b().app.io) -| input.popup_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE;
if (!w.visible or !w.configured or input.popup_window != w or input.popup_serial == 0 or runtime.now(backend().app.io) -| input.popup_time > 5 * std.time.ns_per_s) return abi.UNAVAILABLE;
const root: *Resource = @ptrCast(@alignCast(cmd.target.?));
if (root.payload.menu.items.len == 0) return abi.CANCELLED;
s().window = w;
s().root = root;
s().serial = input.popup_serial;
popupState().window = w;
popupState().root = root;
popupState().serial = input.popup_serial;
runtime.retain(root);
const point: n.uhdk_point = .{ .x = std.math.clamp(cmd.point.x, 0, @as(f32, @floatFromInt(@max(0, w.width - 1)))), .y = std.math.clamp(cmd.point.y, 0, @as(f32, @floatFromInt(@max(0, w.height - 1)))) };
const p = create(root, null, @intFromFloat(point.x), @intFromFloat(point.y), 1) catch {
runtime.release(root);
s().* = .{};
popupState().* = .{};
return abi.OOM;
};
s().top = p;
s().request = id;
popupState().top = p;
popupState().request = id;
Input.beginPopup();
input.popup_serial = 0; // A root grab consumes its triggering action.
return n.Z_DEFERRED;
}
fn create(menu: *Resource, parent: ?*Panel, x: i32, y: i32, anchor_height: i32) !*Panel {
const p = try b().app.gpa.create(Panel);
p.* = .{ .parent = parent, .menu = menu, .scale = @intCast(std.math.clamp((s().window.?.scale + 119) / 120, 1, 4)), .deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s };
const p = try backend().app.gpa.create(Panel);
p.* = .{ .parent = parent, .menu = menu, .scale = @intCast(std.math.clamp((popupState().window.?.scale + 119) / 120, 1, 4)), .deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s };
errdefer destroy(p);
for (menu.payload.menu.items) |item| {
var buffer: [96]u8 = undefined;
p.width = @max(p.width, 60 + Bitmap.width(abi.textBytes(item.label)) + Bitmap.width(Menu.shortcut(item, &buffer)));
p.total += rowHeight(item);
}
p.width = @min(p.width, 480);
p.height = @min(p.total, 480);
p.pending_width = p.width;
p.pending_height = p.height;
p.surface = c.wl_compositor_create_surface(b().compositor) orelse return error.OutOfMemory;
p.surface = c.wl_compositor_create_surface(backend().compositor) orelse return error.OutOfMemory;
if (c.wl_surface_add_listener(p.surface, &surface_listener, p) != 0) return error.OutOfMemory;
p.xdg = c.xdg_wm_base_get_xdg_surface(b().shell, p.surface) orelse return error.OutOfMemory;
p.xdg = c.xdg_wm_base_get_xdg_surface(backend().shell, p.surface) orelse return error.OutOfMemory;
if (c.xdg_surface_add_listener(p.xdg, &xdg_listener, p) != 0) return error.OutOfMemory;
const pos = c.xdg_wm_base_create_positioner(b().shell) orelse return error.OutOfMemory;
const pos = c.xdg_wm_base_create_positioner(backend().shell) orelse return error.OutOfMemory;
defer c.xdg_positioner_destroy(pos);
c.xdg_positioner_set_size(pos, p.width, p.height);
c.xdg_positioner_set_anchor_rect(pos, x, y, 1, @max(1, anchor_height));
c.xdg_positioner_set_anchor(pos, if (parent != null) c.XDG_POSITIONER_ANCHOR_TOP_RIGHT else c.XDG_POSITIONER_ANCHOR_BOTTOM_LEFT);
c.xdg_positioner_set_gravity(pos, c.XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT);
c.xdg_positioner_set_constraint_adjustment(pos, c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X | c.XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y);
p.popup = c.xdg_surface_get_popup(p.xdg, if (parent) |v| v.xdg else s().window.?.xdg, pos) orelse return error.OutOfMemory;
p.popup = c.xdg_surface_get_popup(p.xdg, if (parent) |v| v.xdg else popupState().window.?.xdg, pos) orelse return error.OutOfMemory;
if (c.xdg_popup_add_listener(p.popup, &popup_listener, p) != 0) return error.OutOfMemory;
c.xdg_popup_grab(p.popup, Input.state().seat, s().serial);
c.xdg_popup_grab(p.popup, Input.state().seat, popupState().serial);
c.wl_surface_commit(p.surface);
return p;
}
fn configure(raw: ?*anyopaque, _: ?*c.struct_xdg_popup, _: i32, _: i32, width: i32, height: i32) callconv(.c) void {
const p = panel(raw);
if (width < 1 or height < 1 or width > 1024 or height > 1024) {
finish(n.UHDK_STATUS_OS_ERROR);
return;
}
// Geometry belongs to the next xdg_surface.configure, which can arrive in
// another socket read. Do not render/commit it before acknowledging that.
p.pending_width = width;
p.pending_height = height;
p.configured = false;
p.deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s;
p.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
}
fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void {
const p = panel(raw);
c.xdg_surface_ack_configure(p.xdg, serial);
@ -193,22 +234,26 @@ fn configured(raw: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv
p.height = p.pending_height;
p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height));
}
p.configured = true;
p.deadline = 0;
p.dirty = true;
render(p) catch finish(abi.OOM);
}
fn done(raw: ?*anyopaque, _: ?*c.struct_xdg_popup) callconv(.c) void {
const p = panel(raw);
if (p.parent) |parent| {
closeChildren(parent);
s().hover_at = 0;
popupState().hover_at = 0;
} else finish(abi.CANCELLED);
}
fn repositioned(_: ?*anyopaque, _: ?*c.struct_xdg_popup, _: u32) callconv(.c) void {}
const popup_listener: c.struct_xdg_popup_listener = .{ .configure = configure, .popup_done = done, .repositioned = repositioned };
const xdg_listener: c.struct_xdg_surface_listener = .{ .configure = configured };
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {}
fn scale(raw: ?*anyopaque, _: ?*c.struct_wl_surface, value: i32) callconv(.c) void {
const p = panel(raw);
const next = std.math.clamp(value, 1, 4);
@ -217,6 +262,7 @@ fn scale(raw: ?*anyopaque, _: ?*c.struct_wl_surface, value: i32) callconv(.c) vo
for (&p.buffers) |*buf| freeBuffer(buf);
p.dirty = true;
}
fn transform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {}
const surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = scale, .preferred_buffer_transform = transform };
fn released(raw: ?*anyopaque, proxy: ?*c.struct_wl_buffer) callconv(.c) void {
@ -225,6 +271,7 @@ fn released(raw: ?*anyopaque, proxy: ?*c.struct_wl_buffer) callconv(.c) void {
buf.busy = false;
};
}
const buffer_listener: c.struct_wl_buffer_listener = .{ .release = released };
fn allocateBuffer(p: *Panel, buf: *Buffer) !void {
const size: usize = @intCast(p.width * p.height * p.scale * p.scale * 4);
@ -232,25 +279,31 @@ fn allocateBuffer(p: *Panel, buf: *Buffer) !void {
if (fd < 0) return error.OutOfMemory;
defer _ = c.close(fd);
if (c.ftruncate(fd, @intCast(size)) != 0) return error.OutOfMemory;
const mapping = c.mmap(null, size, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
if (mapping == c.MAP_FAILED) return error.OutOfMemory;
buf.mapping = mapping;
buf.size = size;
errdefer freeBuffer(buf);
const pool = c.wl_shm_create_pool(b().desktop.shm, fd, @intCast(size)) orelse return error.OutOfMemory;
const pool = c.wl_shm_create_pool(backend().desktop.shm, fd, @intCast(size)) orelse return error.OutOfMemory;
defer c.wl_shm_pool_destroy(pool);
buf.proxy = c.wl_shm_pool_create_buffer(pool, 0, p.width * p.scale, p.height * p.scale, p.width * p.scale * 4, c.WL_SHM_FORMAT_ARGB8888) orelse return error.OutOfMemory;
if (c.wl_buffer_add_listener(buf.proxy, &buffer_listener, p) != 0) return error.OutOfMemory;
}
fn render(p: *Panel) !void {
if (!p.configured or !p.dirty) return;
const buf: *Buffer = for (&p.buffers) |*value| {
if (!value.busy) break value;
} else return;
if (buf.proxy == null) try allocateBuffer(p, buf);
const words: [*]u32 = @ptrCast(@alignCast(buf.mapping.?));
const canvas: Bitmap.Canvas = .{ .pixels = words[0 .. buf.size / 4], .width = p.width, .height = p.height, .scale = p.scale };
paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, b().portal.preferences.appearance == n.UHDK_APPEARANCE_LIGHT);
paint(canvas, p.menu.payload.menu.items, p.selected, p.scroll, backend().portal.preferences.appearance == n.UHDK_APPEARANCE_LIGHT);
c.wl_surface_set_buffer_scale(p.surface, p.scale);
c.xdg_surface_set_window_geometry(p.xdg, 0, 0, p.width, p.height);
c.wl_surface_attach(p.surface, buf.proxy, 0, 0);
@ -259,11 +312,13 @@ fn render(p: *Panel) !void {
buf.busy = true;
p.dirty = false;
}
pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?usize, scroll_offset: i32, light: bool) void {
const background: u32 = if (light) 0xf6f6f6 else 0x292c30;
const foreground: u32 = if (light) 0x202124 else 0xf1f2f3;
const border: u32 = if (light) 0xc4c7ca else 0x53585e;
canvas.rect(0, 0, canvas.width, canvas.height, background);
var y: i32 = 4 - scroll_offset;
for (items, 0..) |item, i| {
const height = rowHeight(item);
@ -273,12 +328,14 @@ pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?
canvas.rect(8, y + 4, canvas.width - 16, 1, border);
continue;
}
const color: u32 = if (item.flags & n.UHDK_MENU_DISABLED != 0) (if (light) @as(u32, 0x85888c) else 0x8d939a) else if (selected == i) 0xffffff else foreground;
if (selected == i and usable(item)) canvas.rect(3, y, canvas.width - 6, height, 0x2969b0);
if (item.flags & n.UHDK_MENU_CHECKED != 0) {
for (0..4) |j| canvas.rect(10 + @as(i32, @intCast(j)), y + 12 + @as(i32, @intCast(j)), 2, 2, color);
for (0..7) |j| canvas.rect(13 + @as(i32, @intCast(j)), y + 15 - @as(i32, @intCast(j)), 2, 2, color);
}
var storage: [96]u8 = undefined;
const shortcut = Menu.shortcut(item, &storage);
const shortcut_width = @min(Bitmap.width(shortcut), @max(0, @divTrunc(canvas.width, 2) - 30));
@ -290,6 +347,7 @@ pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?
canvas.rect(canvas.width - 13 + offset, y + 8 + offset, 1, 9 - 2 * offset, color);
};
}
// Padding masks partially scrolled rows and keeps the border intact.
canvas.rect(0, 0, canvas.width, 4, background);
canvas.rect(0, canvas.height - 4, canvas.width, 4, background);
@ -300,63 +358,81 @@ pub fn paint(canvas: Bitmap.Canvas, items: []const n.uhdk_menu_item, selected: ?
if (scroll_offset > 0) canvas.rect(@divTrunc(canvas.width, 2) - 5, 1, 10, 2, foreground);
if (y > canvas.height - 4) canvas.rect(@divTrunc(canvas.width, 2) - 5, canvas.height - 3, 10, 2, foreground);
}
fn choose(p: *Panel, index: ?usize) void {
if (p.selected == index) return;
closeChildren(p);
p.selected = index;
p.pressed = null;
p.dirty = true;
s().hover_at = if (index != null and p.menu.payload.menu.items[index.?].submenu != null) runtime.now(b().app.io) + 200 * std.time.ns_per_ms else 0;
popupState().hover_at = if (index != null and p.menu.payload.menu.items[index.?].submenu != null) runtime.now(backend().app.io) + 200 * std.time.ns_per_ms else 0;
}
fn hit(p: *Panel, x: f32, y: f32) ?usize {
if (x < 3 or x >= @as(f32, @floatFromInt(p.width - 3)) or y < 4 or y >= @as(f32, @floatFromInt(p.height - 4))) return null;
var top: i32 = 4 - p.scroll;
for (p.menu.payload.menu.items, 0..) |item, i| {
const bottom = top + rowHeight(item);
if (y >= @as(f32, @floatFromInt(top)) and y < @as(f32, @floatFromInt(bottom))) return if (usable(item)) i else null;
top = bottom;
}
return null;
}
pub fn pointerEnter(surface: ?*c.struct_wl_surface, x: f32, y: f32, serial: u32) bool {
s().pointer = lookup(surface);
const p = s().pointer orelse return false;
popupState().pointer = lookup(surface);
const p = popupState().pointer orelse return false;
const input = Input.state();
if (input.cursor_device != null) c.wp_cursor_shape_device_v1_set_shape(input.cursor_device, serial, c.WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT);
choose(p, hit(p, x, y));
return true;
}
pub fn pointerLeave() void {
s().pointer = null;
s().hover_at = 0;
popupState().pointer = null;
popupState().hover_at = 0;
}
pub fn motion(x: f32, y: f32) void {
if (s().pointer) |p| choose(p, hit(p, x, y));
if (popupState().pointer) |p| choose(p, hit(p, x, y));
}
pub fn button(code: u32, down: bool, serial: u32) void {
if (down) s().serial = serial;
const p = s().pointer orelse {
if (down) popupState().serial = serial;
const p = popupState().pointer orelse {
if (down) finish(abi.CANCELLED);
return;
};
if (code != 0x110) return;
if (down) p.pressed = p.selected else if (p.pressed != null and p.pressed == p.selected) select(p);
}
fn openChild(p: *Panel) void {
s().hover_at = 0;
popupState().hover_at = 0;
const index = p.selected orelse return;
const item = p.menu.payload.menu.items[index];
if (!usable(item) or item.submenu == null) return;
closeChildren(p);
const menu: *Resource = @ptrCast(@alignCast(item.submenu.?));
if (menu.payload.menu.items.len == 0) return;
const y = std.math.clamp(rowY(p, index), 0, p.height - 1);
const child = create(menu, p, p.width - 1, y, @min(26, p.height - y)) catch {
finish(abi.OOM);
return;
};
s().top = child;
popupState().top = child;
}
fn select(p: *Panel) void {
const index = p.selected orelse return;
const item = &p.menu.payload.menu.items[index];
@ -365,9 +441,11 @@ fn select(p: *Panel) void {
openChild(p);
return;
}
Menu.activate(s().window.?, item, Input.id());
Menu.activate(popupState().window.?, item, Input.id());
finish(abi.OK); // Command event must precede request completion.
}
fn reveal(p: *Panel) void {
const index = p.selected orelse return;
const y = rowY(p, index);
@ -376,24 +454,28 @@ fn reveal(p: *Panel) void {
p.scroll = std.math.clamp(p.scroll, 0, @max(0, p.total - p.height));
p.dirty = true;
}
fn move(p: *Panel, forward: bool) void {
const items = p.menu.payload.menu.items;
if (items.len == 0) return;
var index = p.selected orelse (if (forward) items.len - 1 else 0);
for (0..items.len) |_| {
index = if (forward) (index + 1) % items.len else (index + items.len - 1) % items.len;
if (usable(items[index])) {
choose(p, index);
s().hover_at = 0;
popupState().hover_at = 0;
reveal(p);
return;
}
}
}
pub fn key(logical: u32, down: bool, serial: u32) void {
if (!down) return;
const p = s().top orelse return;
s().serial = serial;
const p = popupState().top orelse return;
popupState().serial = serial;
switch (logical) {
n.UHDK_KEY_ESCAPE => finish(abi.CANCELLED),
n.UHDK_KEY_UP => move(p, false),
@ -408,27 +490,29 @@ pub fn key(logical: u32, down: bool, serial: u32) void {
},
n.UHDK_KEY_RIGHT => {
openChild(p);
if (s().top != p and s().top != null) move(s().top.?, true);
if (popupState().top != p and popupState().top != null) move(popupState().top.?, true);
},
n.UHDK_KEY_LEFT => if (p.parent) |parent| {
closeChildren(parent);
s().hover_at = 0;
popupState().hover_at = 0;
},
n.UHDK_KEY_ENTER, ' ' => select(p),
else => {},
}
}
pub fn scroll(delta: f32) void {
const p = s().pointer orelse return;
const p = popupState().pointer orelse return;
closeChildren(p);
p.scroll = std.math.clamp(p.scroll + @as(i32, @intFromFloat(std.math.clamp(delta, -480, 480))), 0, @max(0, p.total - p.height));
p.selected = null;
p.pressed = null;
p.dirty = true;
s().hover_at = 0;
popupState().hover_at = 0;
}
pub fn flags() void {
var cursor = s().top;
var cursor = popupState().top;
while (cursor) |p| : (cursor = p.parent) {
p.dirty = true;
if (p.selected) |index| if (!usable(p.menu.payload.menu.items[index])) {
@ -438,27 +522,33 @@ pub fn flags() void {
};
}
}
pub fn tick() i32 {
if (!active()) return -1;
const now = runtime.now(b().app.io);
if (s().hover_at != 0 and now >= s().hover_at) {
if (s().pointer) |p| openChild(p);
s().hover_at = 0;
const now = runtime.now(backend().app.io);
if (popupState().hover_at != 0 and now >= popupState().hover_at) {
if (popupState().pointer) |p| openChild(p);
popupState().hover_at = 0;
}
var cursor = s().top;
var timeout: i32 = if (s().hover_at != 0) 25 else -1;
var cursor = popupState().top;
var timeout: i32 = if (popupState().hover_at != 0) 25 else -1;
while (cursor) |p| : (cursor = p.parent) {
if (!p.configured) {
if (now >= p.deadline) {
finish(abi.UNAVAILABLE);
return -1;
}
timeout = 100;
}
render(p) catch {
finish(abi.OOM);
return -1;
};
}
return timeout;
}

View File

@ -6,6 +6,7 @@ const n = @import("native");
const native = @import("native.zig");
const KdeAppMenu = @import("KdeAppMenu.zig");
const Bus = @import("Bus.zig");
const Tray = @import("Tray.zig");
const Files = @import("Files.zig");
const Input = @import("Input.zig");
const runtime = @import("../runtime.zig");
@ -29,12 +30,13 @@ const Pending = struct {
activation: ?*c.struct_xdg_activation_token_v1 = null,
deadline: u64,
};
pub const State = struct {
connection: ?*c.DBusConnection = null,
unique: ?[:0]u8 = null,
owner: ?[:0]u8 = null,
hello: u32 = 0,
matches: [3]u32 = @splat(0),
matches: [5]u32 = @splat(0),
ready: bool = false,
version_serial: u32 = 0,
settings_serial: u32 = 0,
@ -44,81 +46,100 @@ pub const State = struct {
exporter: ?*c.struct_zxdg_exporter_v2 = null,
preferences: n.uhdk_preferences = .{ .struct_size = @sizeOf(n.uhdk_preferences), .appearance = n.UHDK_APPEARANCE_UNKNOWN, .reduced_motion = 0, .high_contrast = 0 },
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
fn s() *State {
return &b().portal;
fn portalState() *State {
return &backend().portal;
}
pub fn send(message: *Bus.Message) !u32 {
var serial: u32 = 0;
if (c.z_dbus_connection_send.?(s().connection, message, &serial) == 0) return error.OutOfMemory;
if (c.z_dbus_connection_send.?(portalState().connection, message, &serial) == 0) return error.OutOfMemory;
return serial;
}
pub fn global(registry: ?*c.struct_wl_registry, name: u32, interface: []const u8, _: u32) void {
if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) s().exporter = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zxdg_exporter_v2_interface, 1));
if (std.mem.eql(u8, interface, "zxdg_exporter_v2")) portalState().exporter = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_zxdg_exporter_v2_interface, 1));
}
pub fn initialize() void {
if (c.z_linux_dbus_available() == 0 or c.z_dbus_threads_init_default.?() == 0) return;
// Avoid libdbus autolaunch/process spawning. Desktop sessions provide this
// address; absence disables portals without affecting windows or input.
const address = c.getenv("DBUS_SESSION_BUS_ADDRESS");
if (address == null or !std.mem.startsWith(u8, std.mem.span(address), "unix:")) return;
s().connection = c.z_dbus_connection_open_private.?(address, null) orelse return;
c.z_dbus_connection_set_exit_on_disconnect.?(s().connection, 0);
s().startup_deadline = runtime.now(b().app.io) + 5 * std.time.ns_per_s;
portalState().connection = c.z_dbus_connection_open_private.?(address, null) orelse return;
c.z_dbus_connection_set_exit_on_disconnect.?(portalState().connection, 0);
portalState().startup_deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
const message = Bus.method(dbus, dbus_path, dbus, "Hello") catch {
disconnect();
return;
};
defer c.z_dbus_message_unref.?(message);
s().hello = send(message) catch {
portalState().hello = send(message) catch {
disconnect();
return;
};
}
fn addMatches() !void {
const rules = [_][*:0]const u8{
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Request',member='Response'",
"type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged',path='/org/freedesktop/portal/desktop'",
"type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.portal.Desktop'",
"type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.kde.StatusNotifierWatcher'",
"type='signal',sender='org.kde.StatusNotifierWatcher',interface='org.kde.StatusNotifierWatcher',path='/StatusNotifierWatcher'",
};
for (rules, 0..) |rule, i| {
const message = try Bus.method(dbus, dbus_path, dbus, "AddMatch");
defer c.z_dbus_message_unref.?(message);
var args = Bus.append(message);
try Bus.string(&args, rule);
s().matches[i] = try send(message);
portalState().matches[i] = try send(message);
}
}
fn discover() !void {
const version = try Bus.method(desktop, path, "org.freedesktop.DBus.Properties", "Get");
defer c.z_dbus_message_unref.?(version);
var args = Bus.append(version);
try Bus.string(&args, chooser);
try Bus.string(&args, "version");
s().version_serial = try send(version);
portalState().version_serial = try send(version);
const read = try Bus.method(desktop, path, settings, "ReadAll");
defer c.z_dbus_message_unref.?(read);
args = Bus.append(read);
var namespaces = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "s");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &namespaces);
try Bus.string(&namespaces, "org.freedesktop.appearance");
try Bus.close(&args, &namespaces);
s().settings_serial = try send(read);
portalState().settings_serial = try send(read);
}
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
const connection = s().connection orelse return;
const connection = portalState().connection orelse return;
var fd: c_int = -1;
if (c.z_dbus_connection_get_unix_fd.?(connection, &fd) != 0)
try fds.append(b().app.gpa, .{ .fd = fd, .events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(connection) != 0) c.POLLOUT else 0), .revents = 0 });
try fds.append(backend().app.gpa, .{ .fd = fd, .events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(connection) != 0) c.POLLOUT else 0), .revents = 0 });
}
pub fn tick() i32 {
const connection = s().connection orelse return -1;
const connection = portalState().connection orelse return -1;
if (c.z_dbus_connection_read_write.?(connection, 0) == 0) {
disconnect();
return -1;
}
// Bound dispatch work so an active bus cannot starve Wayland or app commands.
for (0..64) |_| {
const message = c.z_dbus_connection_pop_message.?(connection) orelse break;
@ -127,14 +148,17 @@ pub fn tick() i32 {
disconnect();
return -1;
};
if (s().connection == null) return -1;
if (portalState().connection == null) return -1;
} else return 0;
const now = runtime.now(b().app.io);
if (!s().ready and now >= s().startup_deadline) {
const now = runtime.now(backend().app.io);
if (!portalState().ready and now >= portalState().startup_deadline) {
disconnect();
return -1;
}
var cursor = s().pending;
var cursor = portalState().pending;
while (cursor) |pending| {
cursor = pending.next;
if (pending.deadline != 0 and now >= pending.deadline) {
@ -143,56 +167,70 @@ pub fn tick() i32 {
destroy(pending);
}
}
return if (s().pending != null or !s().ready) 100 else -1;
return if (portalState().pending != null or !portalState().ready) 100 else -1;
}
fn setOwner(message: *Bus.Message) !void {
const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null) return;
if (s().owner) |old| b().app.gpa.free(old);
s().owner = try b().app.gpa.dupeZ(u8, std.mem.span(sender));
if (portalState().owner) |old| backend().app.gpa.free(old);
portalState().owner = try backend().app.gpa.dupeSentinel(u8, std.mem.span(sender), 0);
}
fn process(message: *Bus.Message) !void {
if (try Tray.process(message)) return;
if (try KdeAppMenu.process(message)) return;
const serial = c.z_dbus_message_get_reply_serial.?(message);
const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
var args = Bus.parse(message);
if (serial != 0 and serial == s().hello) {
s().hello = 0;
if (serial != 0 and serial == portalState().hello) {
portalState().hello = 0;
if (failed or c.z_dbus_message_has_signature.?(message, "s") == 0) {
disconnect();
return;
}
s().unique = try b().app.gpa.dupeZ(u8, Bus.str(&args).?);
portalState().unique = try backend().app.gpa.dupeSentinel(u8, Bus.str(&args).?, 0);
try addMatches();
return;
}
for (&s().matches) |*match| if (serial != 0 and serial == match.*) {
for (&portalState().matches) |*match| if (serial != 0 and serial == match.*) {
if (failed) {
disconnect();
return;
}
match.* = 0;
if (std.mem.allEqual(u32, &s().matches, 0)) {
s().ready = true;
if (std.mem.allEqual(u32, &portalState().matches, 0)) {
portalState().ready = true;
KdeAppMenu.ready();
try Tray.ready();
try discover();
}
return;
};
if (serial != 0 and serial == s().version_serial) {
s().version_serial = 0;
if (serial != 0 and serial == portalState().version_serial) {
portalState().version_serial = 0;
if (!failed) {
var value = Bus.variant(&args) orelse return;
s().chooser_version = Bus.uint(&value) orelse 0;
portalState().chooser_version = Bus.uint(&value) orelse 0;
try setOwner(message);
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, s().chooser_version >= 3);
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, portalState().chooser_version >= 3);
}
return;
}
if (serial != 0 and serial == s().settings_serial) {
s().settings_serial = 0;
if (serial != 0 and serial == portalState().settings_serial) {
portalState().settings_serial = 0;
if (!failed and c.z_dbus_message_has_signature.?(message, "a{sa{sv}}") != 0) {
try setOwner(message);
var appearance = Bus.entry(&args, "org.freedesktop.appearance") orelse return;
inline for (.{ "color-scheme", "contrast", "reduced-motion" }) |key| {
if (Bus.entry(&appearance, key)) |raw| {
@ -204,37 +242,45 @@ fn process(message: *Bus.Message) !void {
}
}
}
return;
}
if (c.z_dbus_message_is_signal.?(message, dbus, "NameOwnerChanged") != 0 and c.z_dbus_message_has_signature.?(message, "sss") != 0) {
const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null or !std.mem.eql(u8, std.mem.span(sender), dbus)) return;
if (!std.mem.eql(u8, Bus.str(&args).?, desktop)) return;
_ = Bus.next(&args);
const old = Bus.str(&args).?;
_ = Bus.next(&args);
const new = Bus.str(&args).?;
if (old.len != 0) {
while (s().pending) |p| {
while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null);
destroy(p);
}
s().chooser_version = 0;
portalState().chooser_version = 0;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
if (s().owner) |owner| b().app.gpa.free(owner);
s().owner = null;
if (portalState().owner) |owner| backend().app.gpa.free(owner);
portalState().owner = null;
preference("color-scheme", 0);
preference("contrast", 0);
preference("reduced-motion", 0);
}
if (new.len != 0) {
if (s().owner) |owner| b().app.gpa.free(owner);
s().owner = try b().app.gpa.dupeZ(u8, new);
if (portalState().owner) |owner| backend().app.gpa.free(owner);
portalState().owner = try backend().app.gpa.dupeSentinel(u8, new, 0);
try discover();
}
return;
}
var cursor = s().pending;
var cursor = portalState().pending;
while (cursor) |pending| : (cursor = pending.next) {
if (serial != 0 and serial == pending.serial) {
pending.replied = true;
@ -243,13 +289,15 @@ fn process(message: *Bus.Message) !void {
destroy(pending);
return;
}
if (c.z_dbus_message_has_signature.?(message, "o") == 0) {
complete(pending, n.UHDK_STATUS_OS_ERROR, null);
destroy(pending);
return;
}
const handle = try b().app.gpa.dupeZ(u8, Bus.str(&args).?);
b().app.gpa.free(pending.handle);
const handle = try backend().app.gpa.dupeSentinel(u8, Bus.str(&args).?, 0);
backend().app.gpa.free(pending.handle);
pending.handle = handle;
if (pending.id == 0) {
if (pending.cancelled) closeRequest(pending.handle);
@ -258,69 +306,79 @@ fn process(message: *Bus.Message) !void {
return;
}
}
// Match rules are installed on the bus, and sender validation also protects
// against unrelated unicast signals sent directly to our private connection.
const sender = c.z_dbus_message_get_sender.?(message);
if (sender == null or s().owner == null or !std.mem.eql(u8, std.mem.span(sender), s().owner.?)) return;
if (sender == null or portalState().owner == null or !std.mem.eql(u8, std.mem.span(sender), portalState().owner.?)) return;
if (c.z_dbus_message_is_signal.?(message, settings, "SettingChanged") != 0 and c.z_dbus_message_has_signature.?(message, "ssv") != 0) {
if (!std.mem.eql(u8, Bus.str(&args).?, "org.freedesktop.appearance")) return;
_ = Bus.next(&args);
const key = Bus.str(&args).?;
_ = Bus.next(&args);
var value = Bus.variant(&args).?;
preference(key, Bus.uint(&value) orelse 0);
} else if (c.z_dbus_message_is_signal.?(message, "org.freedesktop.portal.Request", "Response") != 0 and c.z_dbus_message_has_signature.?(message, "ua{sv}") != 0) {
const response_path = c.z_dbus_message_get_path.?(message);
if (response_path == null) return;
cursor = s().pending;
cursor = portalState().pending;
while (cursor) |pending| : (cursor = pending.next) if (std.mem.eql(u8, pending.handle, std.mem.span(response_path))) {
const code = Bus.uint(&args).?;
_ = Bus.next(&args);
if (pending.id != 0) {
if (code != 0) complete(pending, if (code == 1) abi.CANCELLED else n.UHDK_STATUS_OS_ERROR, null) else if (pending.command.?.op == n.Z_URL) complete(pending, abi.OK, null) else responseFiles(pending, &args);
}
if (pending.replied) destroy(pending);
return;
};
}
}
fn errorStatus(message: *Bus.Message) u32 {
const name = c.z_dbus_message_get_error_name.?(message);
if (name != null and (std.mem.endsWith(u8, std.mem.span(name), ".NotFound") or std.mem.endsWith(u8, std.mem.span(name), ".ServiceUnknown") or std.mem.endsWith(u8, std.mem.span(name), ".UnknownMethod"))) return n.UHDK_STATUS_UNSUPPORTED;
return n.UHDK_STATUS_OS_ERROR;
}
fn preference(key: []const u8, value: u32) void {
const old = s().preferences;
if (std.mem.eql(u8, key, "color-scheme")) s().preferences.appearance = switch (value) {
const old = portalState().preferences;
if (std.mem.eql(u8, key, "color-scheme")) portalState().preferences.appearance = switch (value) {
1 => n.UHDK_APPEARANCE_DARK,
2 => n.UHDK_APPEARANCE_LIGHT,
else => n.UHDK_APPEARANCE_UNKNOWN,
} else if (std.mem.eql(u8, key, "contrast")) s().preferences.high_contrast = @intFromBool(value == 1) else if (std.mem.eql(u8, key, "reduced-motion")) s().preferences.reduced_motion = @intFromBool(value == 1);
if (!std.meta.eql(old, s().preferences)) n.z_preferences(runtime.toAppHandle(b().app), &s().preferences);
} else if (std.mem.eql(u8, key, "contrast")) portalState().preferences.high_contrast = @intFromBool(value == 1) else if (std.mem.eql(u8, key, "reduced-motion")) portalState().preferences.reduced_motion = @intFromBool(value == 1);
if (!std.meta.eql(old, portalState().preferences)) n.z_preferences(runtime.toAppHandle(backend().app), &portalState().preferences);
}
pub fn request(cmd: *const n.z_command, id: u64) u32 {
if (!s().ready or s().connection == null) return abi.UNAVAILABLE;
if (cmd.op == n.Z_DIALOG and s().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED;
if (!portalState().ready or portalState().connection == null) return abi.UNAVAILABLE;
if (cmd.op == n.Z_DIALOG and portalState().chooser_version < 3) return n.UHDK_STATUS_UNSUPPORTED;
const p = allocate(cmd, id) catch return abi.OOM;
p.next = s().pending;
s().pending = p;
if (cmd.op == n.Z_DIALOG and cmd.dialog.parent != null and s().exporter != null) {
p.next = portalState().pending;
portalState().pending = p;
if (cmd.op == n.Z_DIALOG and cmd.dialog.parent != null and portalState().exporter != null) {
const w: *native.Window = @ptrCast(@alignCast(n.z_object_native(cmd.dialog.parent) orelse {
destroy(p);
return abi.UNAVAILABLE;
}));
p.exported = c.zxdg_exporter_v2_export_toplevel(s().exporter, w.surface) orelse {
p.exported = c.zxdg_exporter_v2_export_toplevel(portalState().exporter, w.surface) orelse {
destroy(p);
return abi.OOM;
};
_ = c.zxdg_exported_v2_add_listener(p.exported, &export_listener, p);
} else if (cmd.op == n.Z_URL and b().desktop.activation != null and Input.state().key_focus != null and
Input.state().serial != 0 and runtime.now(b().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s)
} else if (cmd.op == n.Z_URL and backend().desktop.activation != null and Input.state().key_focus != null and
Input.state().serial != 0 and runtime.now(backend().app.io) -| Input.state().serial_time <= 5 * std.time.ns_per_s)
{
p.activation = c.xdg_activation_v1_get_activation_token(b().desktop.activation) orelse {
p.activation = c.xdg_activation_v1_get_activation_token(backend().desktop.activation) orelse {
destroy(p);
return abi.OOM;
};
_ = c.xdg_activation_token_v1_add_listener(p.activation, &activation_listener, p);
c.xdg_activation_token_v1_set_serial(p.activation, Input.state().serial, Input.state().seat);
c.xdg_activation_token_v1_set_surface(p.activation, Input.state().key_focus.?.surface);
@ -331,32 +389,37 @@ pub fn request(cmd: *const n.z_command, id: u64) u32 {
};
return n.Z_DEFERRED;
}
fn allocate(cmd: *const n.z_command, id: u64) !*Pending {
const gpa = b().app.gpa;
const gpa = backend().app.gpa;
const p = try gpa.create(Pending);
errdefer gpa.destroy(p);
const token = try std.fmt.allocPrintSentinel(gpa, "uhdk_{x}", .{id}, 0);
errdefer gpa.free(token);
const unique = s().unique.?;
const unique = portalState().unique.?;
const name = try gpa.dupe(u8, unique[1..]);
defer gpa.free(name);
std.mem.replaceScalar(u8, name, '.', '_');
p.* = .{ .id = id, .command = cmd, .token = token, .handle = try std.fmt.allocPrintSentinel(gpa, path ++ "/request/{s}/{s}", .{ name, token }, 0), .deadline = runtime.now(b().app.io) + 30 * std.time.ns_per_s };
p.* = .{ .id = id, .command = cmd, .token = token, .handle = try std.fmt.allocPrintSentinel(gpa, path ++ "/request/{s}/{s}", .{ name, token }, 0), .deadline = runtime.now(backend().app.io) + 30 * std.time.ns_per_s };
return p;
}
fn exported(raw: ?*anyopaque, _: ?*c.struct_zxdg_exported_v2, handle: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?));
const parent = std.fmt.allocPrintSentinel(b().app.gpa, "wayland:{s}", .{std.mem.span(handle)}, 0) catch {
const parent = std.fmt.allocPrintSentinel(backend().app.gpa, "wayland:{s}", .{std.mem.span(handle)}, 0) catch {
complete(p, abi.OOM, null);
destroy(p);
return;
};
defer b().app.gpa.free(parent);
defer backend().app.gpa.free(parent);
submit(p, parent, null) catch {
complete(p, abi.OOM, null);
destroy(p);
};
}
const export_listener: c.struct_zxdg_exported_v2_listener = .{ .handle = exported };
fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c]const u8) callconv(.c) void {
const p: *Pending = @ptrCast(@alignCast(raw.?));
@ -365,18 +428,22 @@ fn activated(raw: ?*anyopaque, _: ?*c.struct_xdg_activation_token_v1, token: [*c
destroy(p);
};
}
const activation_listener: c.struct_xdg_activation_token_v1_listener = .{ .done = activated };
fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8) !void {
const cmd = p.command.?;
const dialog = cmd.op == n.Z_DIALOG;
const message = try Bus.method(desktop, path, if (dialog) chooser else "org.freedesktop.portal.OpenURI", if (!dialog) "OpenURI" else if (cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) "SaveFile" else "OpenFile");
defer c.z_dbus_message_unref.?(message);
var arena: std.heap.ArenaAllocator = .init(b().app.gpa);
var arena: std.heap.ArenaAllocator = .init(backend().app.gpa);
defer arena.deinit();
const gpa = arena.allocator();
var args = Bus.append(message);
try Bus.string(&args, parent);
try Bus.string(&args, try gpa.dupeZ(u8, abi.textBytes(if (dialog) cmd.dialog.title else cmd.text)));
try Bus.string(&args, try gpa.dupeSentinel(u8, abi.textBytes(if (dialog) cmd.dialog.title else cmd.text), 0));
var options = try Bus.open(&args, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&args, &options);
try Bus.option(&options, "handle_token", "s", p.token.ptr);
@ -387,15 +454,18 @@ fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8)
try Bus.option(&options, "multiple", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_FILES)));
try Bus.option(&options, "directory", "b", @as(u32, @intFromBool(cmd.dialog.kind == n.UHDK_DIALOG_OPEN_DIRECTORY)));
}
if (cmd.dialog.accept_label.len != 0) try Bus.option(&options, "accept_label", "s", (try gpa.dupeZ(u8, abi.textBytes(cmd.dialog.accept_label))).ptr);
if (cmd.dialog.suggested_name.len != 0 and cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) try Bus.option(&options, "current_name", "s", (try gpa.dupeZ(u8, abi.textBytes(cmd.dialog.suggested_name))).ptr);
if (cmd.dialog.accept_label.len != 0) try Bus.option(&options, "accept_label", "s", (try gpa.dupeSentinel(u8, abi.textBytes(cmd.dialog.accept_label), 0)).ptr);
if (cmd.dialog.suggested_name.len != 0 and cmd.dialog.kind == n.UHDK_DIALOG_SAVE_FILE) try Bus.option(&options, "current_name", "s", (try gpa.dupeSentinel(u8, abi.textBytes(cmd.dialog.suggested_name), 0)).ptr);
if (cmd.dialog.initial_directory != null) {
const directory = abi.bytes(n.z_file_path(cmd.dialog.initial_directory));
var entry = try Bus.open(&options, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&options, &entry);
try Bus.string(&entry, "current_folder");
var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "ay");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant);
var bytes = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "y");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &bytes);
for (directory) |byte| try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, byte);
@ -404,23 +474,29 @@ fn submit(p: *Pending, parent: [*:0]const u8, activation_token: ?[*:0]const u8)
try Bus.close(&entry, &variant);
try Bus.close(&options, &entry);
}
if (cmd.dialog.filters_len != 0) try filters(&options, cmd.dialog, gpa);
}
try Bus.close(&args, &options);
p.serial = try send(message);
}
fn filters(options: *Bus.Iter, desc: n.uhdk_file_dialog_desc, gpa: std.mem.Allocator) !void {
var entry = try Bus.open(options, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(options, &entry);
try Bus.string(&entry, "filters");
var variant = try Bus.open(&entry, c.DBUS_TYPE_VARIANT, "a(sa(us))");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&entry, &variant);
var list = try Bus.open(&variant, c.DBUS_TYPE_ARRAY, "(sa(us))");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&variant, &list);
for (desc.filters[0..@intCast(desc.filters_len)]) |filter| {
var pair = try Bus.open(&list, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&list, &pair);
try Bus.string(&pair, try gpa.dupeZ(u8, abi.textBytes(filter.label)));
try Bus.string(&pair, try gpa.dupeSentinel(u8, abi.textBytes(filter.label), 0));
var patterns = try Bus.open(&pair, c.DBUS_TYPE_ARRAY, "(us)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&pair, &patterns);
for (0..@max(1, filter.extensions.len)) |index| {
@ -431,71 +507,86 @@ fn filters(options: *Bus.Iter, desc: n.uhdk_file_dialog_desc, gpa: std.mem.Alloc
try Bus.string(&rule, pattern);
try Bus.close(&patterns, &rule);
}
try Bus.close(&pair, &patterns);
try Bus.close(&list, &pair);
}
try Bus.close(&variant, &list);
try Bus.close(&entry, &variant);
try Bus.close(options, &entry);
}
fn responseFiles(p: *Pending, args: *Bus.Iter) void {
var raw = Bus.entry(args, "uris") orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
};
var value = Bus.variant(&raw) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
};
if (Bus.kind(&value) != c.DBUS_TYPE_ARRAY) {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
}
var strings = Bus.child(&value);
var files: std.ArrayList(?*n.uhdk_file) = .empty;
defer {
for (files.items) |file| n.uhdk_file_release(file);
files.deinit(b().app.gpa);
files.deinit(backend().app.gpa);
}
while (Bus.kind(&strings) != c.DBUS_TYPE_INVALID) {
const uri = Bus.str(&strings) orelse {
complete(p, n.UHDK_STATUS_OS_ERROR, null);
return;
};
const bytes = Files.decode(b().app.gpa, uri) catch |err| {
const bytes = Files.decode(backend().app.gpa, uri) catch |err| {
complete(p, if (err == error.OutOfMemory) abi.OOM else n.UHDK_STATUS_UNSUPPORTED, null);
return;
};
defer b().app.gpa.free(bytes);
const file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse {
defer backend().app.gpa.free(bytes);
const file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = bytes.ptr, .len = bytes.len }, null) orelse {
complete(p, abi.OOM, null);
return;
};
files.append(b().app.gpa, file) catch {
files.append(backend().app.gpa, file) catch {
n.uhdk_file_release(file);
complete(p, abi.OOM, null);
return;
};
if (!Bus.next(&strings)) break;
}
var result = std.mem.zeroes(n.z_request_result);
result.value.files = .{ .ptr = files.items.ptr, .len = files.items.len };
complete(p, if (files.items.len == 0) abi.CANCELLED else abi.OK, &result);
}
fn complete(p: *Pending, status: u32, result: ?*n.z_request_result) void {
if (p.id != 0) n.z_complete(runtime.toAppHandle(b().app), p.id, status, result);
if (p.id != 0) n.z_complete(runtime.toAppHandle(backend().app), p.id, status, result);
p.id = 0;
p.command = null;
}
fn closeRequest(handle: [*:0]const u8) void {
if (s().connection == null) return;
if (portalState().connection == null) return;
const message = Bus.method(desktop, handle, "org.freedesktop.portal.Request", "Close") catch return;
defer c.z_dbus_message_unref.?(message);
c.z_dbus_message_set_no_reply.?(message, 1);
_ = send(message) catch {};
}
pub fn cancel(id: u64) bool {
var cursor = s().pending;
var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) if (p.id == id) {
if (p.serial != 0) closeRequest(p.handle);
p.cancelled = true;
@ -505,35 +596,41 @@ pub fn cancel(id: u64) bool {
};
return false;
}
fn destroy(p: *Pending) void {
var link = &s().pending;
var link = &portalState().pending;
while (link.* != p) link = &link.*.?.next;
link.* = p.next;
if (p.exported != null) c.zxdg_exported_v2_destroy(p.exported);
if (p.activation != null) c.xdg_activation_token_v1_destroy(p.activation);
b().app.gpa.free(p.handle);
b().app.gpa.free(p.token);
b().app.gpa.destroy(p);
backend().app.gpa.free(p.handle);
backend().app.gpa.free(p.token);
backend().app.gpa.destroy(p);
}
fn disconnect() void {
Tray.disconnected();
KdeAppMenu.disconnected();
while (s().pending) |p| {
while (portalState().pending) |p| {
complete(p, abi.UNAVAILABLE, null);
destroy(p);
}
if (s().connection) |connection| {
if (portalState().connection) |connection| {
c.z_dbus_connection_close.?(connection);
c.z_dbus_connection_unref.?(connection);
}
s().connection = null;
s().ready = false;
portalState().connection = null;
portalState().ready = false;
native.setCapability(n.UHDK_CAP_FILE_DIALOGS, false);
}
pub fn deinit() void {
var cursor = s().pending;
var cursor = portalState().pending;
while (cursor) |p| : (cursor = p.next) closeRequest(p.handle);
disconnect();
if (s().unique) |unique| b().app.gpa.free(unique);
if (s().owner) |owner| b().app.gpa.free(owner);
if (s().exporter != null) c.zxdg_exporter_v2_destroy(s().exporter);
if (portalState().unique) |unique| backend().app.gpa.free(unique);
if (portalState().owner) |owner| backend().app.gpa.free(owner);
if (portalState().exporter != null) c.zxdg_exporter_v2_destroy(portalState().exporter);
}

View File

@ -7,16 +7,17 @@ logical/pixel metrics, EGL desktop OpenGL, and local POSIX file references.
Keyboard/pointer input, cursor shapes, XKB composition, text-input-v3 IME,
clipboard, incoming file drops, portal dialogs/URLs/preferences, activation,
application icons, inotify file watches, Plasma app/window menu export, and
software-rendered context menus are also implemented.
software-rendered context menus and StatusNotifier tray icons are also implemented.
A cursor-theme fallback, client-side window decorations, and X11
remain unsupported. Protocol tests cover IME batching; a live Fcitx/IBus CJK
A cursor-theme fallback, library-rendered client-side decorations, and X11
remain unsupported. Applications can disable native decoration and render their
own chrome. Protocol tests cover IME batching; a live Fcitx/IBus CJK
session and other desktops still need qualification. Missing optional protocols
or libraries disable their features without a desktop-name whitelist.
## Build and run
Normal builds require only Zig 0.16.0 on a glibc Linux target:
Normal builds require only Zig 0.17.0 on a glibc Linux target:
```sh
zig build
@ -40,7 +41,7 @@ means the mechanism is available, not that every context creation must succeed.
`AUTO` selects Wayland; explicit X11 requests return `UNSUPPORTED`. Before a
successful run, the Linux backend query returns `AUTO` and all capabilities are
false. Startup discovers the registry before publishing `READY`. The protocol
false. Startup discovers the registry before `uhdk_open` returns. The protocol
handshake and initial window configure have five-second deadlines. Display
failure requests shutdown and cancels pending work; it never switches backends.
@ -48,16 +49,15 @@ 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.
Zig 0.17.0 should already be on PATH. The shell is optional for compilation.
Its nixpkgs revision and source hash live in `nix/pkgs.nix`. It also supports
maintainer [header/protocol refreshes](vendor/README.md). Running packaged apps
on NixOS should use the application's normal Nix wrapper and graphics setup.
@ -72,7 +72,7 @@ For distribution on conventional glibc systems, build the application explicitly
for the chosen baseline, for example:
```sh
zig build -Dtarget=x86_64-linux-gnu.2.35 -Dcpu=baseline -Doptimize=ReleaseSafe
zig build -Dtarget=x86_64-linux-gnu.2.35 -Dcpu=baseline -Doptimize=safe
python3 src/linux/tools/audit-elf.py /path/to/application
```
@ -85,12 +85,14 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
- A decorated window requires xdg-decoration server-side mode. A compositor that
lacks it returns `UNSUPPORTED`; a libdecor adapter is future work. Undecorated
windows remain possible. No desktop-name checks or Qt/KDE linkage are used.
- The application ID is copied from `uhdk_app_desc` and sent as the xdg-toplevel
windows remain possible, and `uhdk_window_set_style` can switch the
decoration request at runtime. No desktop-name checks or Qt/KDE linkage are used.
- The application ID is copied from `uhdk_options` and sent as the xdg-toplevel
app ID. Applications own their desktop-file and icon installation.
- A window is created hidden after its first configure. Showing requests mapping;
the first successful buffer swap supplies its content. `visible` is the
application's show/hide intent, not proof that the compositor displays it.
- `uhdk_open` returns a primary window with visibility requested;
`uhdk_window_create` returns an additional hidden native window. Showing
requests mapping; the first committed buffer supplies its content. `visible`
is the application's show/hide intent, not proof that the compositor displays it.
- Size/state commands acknowledge submission. Confirmed geometry and focus arrive
through metrics. Wayland cannot report minimized state, force focus, or directly
undo minimization. Metrics expose known resizing and (xdg-shell v6+) suspension
@ -103,17 +105,22 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
integer buffer scale is used when wl_surface v6 is available. Older compositors
without those mechanisms currently use scale 1. Fractional/mixed-DPI behavior
still needs runtime validation.
- Native requests and protocol dispatch run on the OS main thread. GL work runs
on the application thread. Main-thread drawable updates use a nonblocking lock
attempt; the dispatcher never waits behind an in-progress swap. End-frame wakes
it to retry deferred updates.
- Native requests, protocol dispatch and application GL work run on OS main.
The session frame boundaries release GL ownership before pumping native work.
File execution/watch preparation use an independent internal worker. Long
application updates delay native dispatch; there is no attached render thread.
- Hiding replaces the EGL presentation surface so an outstanding frame callback
cannot hang remapping. The GL context and its application-owned resources
survive. Swapping a hidden/unconfigured window returns `UNAVAILABLE`.
- Every GL call belongs inside begin/end-frame. Clear/make-current are supported
within that bracket. Actual GL version reporting is queried in the active
context. Window framebuffer dimensions describe the presentation target;
applications continue to own their viewport and rendering resources.
survive. Hidden windows still receive events; `uhdk_end_frame` does not present
iterations whose `frame.drawable` is false.
- In GL sessions, the context is current after `uhdk_open` and between iterations
until `uhdk_close`. Create and destroy GL resources on OS main, including
before the first frame and after the loop. `uhdk_next_frame` releases GL
ownership while pumping native work and restores it before returning. Draw
to the window only when `frame.drawable` is true, and pair each successful
`uhdk_next_frame` with `uhdk_end_frame`. Framebuffer dimensions describe the
presentation target; applications own their viewport and rendering resources.
## Input and desktop services
@ -135,8 +142,14 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
Escape first cancels composition before becoming an application action.
- Pointer motion, buttons, wheel/touchpad frames and cursor-shape-v1 are supported.
Capture acknowledges Wayland's implicit button grab during a selection drag;
requesting it without a held button/focused pointer returns `UNAVAILABLE`.
The last button release or focus loss restores normal mode. There is no pointer
requests without a held button/focused pointer are ignored at native dispatch.
The last button release or focus loss restores normal mode. Confinement uses
pointer-constraints-v1 when `UHDK_CAP_POINTER_CONFINEMENT` is available. It
requires a visible window with keyboard/pointer focus and uses the complete
content input region, including after resizing. `POINTER_MODE_CHANGED` reports
actual activation; the compositor may defer or decline it. Focus loss, hiding,
minimization, seat loss, or compositor cancellation also cancels pending
confinement. Applications must explicitly request it again. There is no pointer
lock, relative motion, touch, tablet, or themed-cursor fallback yet.
- Clipboard writes require keyboard focus and a triggering input serial. They
never wait for an unrelated future key. Reads negotiate UTF-8/plain text,
@ -150,7 +163,7 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
support filters, initial directories, suggested names and multiple selection.
A private D-Bus connection subscribes before submission, correlates early
responses, closes cancelled requests, and handles portal-owner changes.
Portal discovery is asynchronous, so its capability can appear after `READY`.
Portal discovery is asynchronous, so its capability can appear after `uhdk_open` returns.
Connection/method setup is bounded; human interaction has no timeout. URL
handoff includes an activation token when recent focused input permits it.
- Portal Settings supplies appearance, contrast and reduced-motion preferences
@ -174,6 +187,18 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
menu. Enabled/checked changes are signalled to consumers, and disabled parents
block their descendants. Labels are literal UTF-8, with mnemonic markers
escaped. The current API has no separate checkable/radio or RTL setting.
- Tray icons use `org.kde.StatusNotifierWatcher`/`org.kde.StatusNotifierItem` and
the same D-BusMenu exporter. They do not require KDE's Wayland appmenu protocol.
A compatible StatusNotifier host is required (for example Plasma's tray or a
configured Waybar tray); desktops without one report `UHDK_CAP_TRAY` false.
Registration is asynchronous and recovers when the watcher or host returns.
Each item owns a private bus identity so hiding/destroying one unregisters it
independently. Full session-bus replacement requires reopening the session.
Hosts render menus themselves; a host that only calls `ContextMenu` without
supporting D-BusMenu cannot display the tray menu. Secondary activation and
the primary-menu hint depend on host support. Host-supplied Wayland activation
tokens are consumed once by the next window focus request within five seconds.
RGBA pixels are exported as network-order ARGB; no icon installation is needed.
- Menu accelerators use logical keys and Shift/Control/Alt/Super, ignoring lock
flags and ASCII letter case. They dispatch menu/edit/quit events before raw
keys or text; matching key releases and repeats are consumed. They remain
@ -184,7 +209,7 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
reconnecting to a replaced session bus requires restarting the application.
Restarting just the menu consumer does not require reattachment.
- Context menus use an internal software renderer and `xdg_popup`, with a
checked-in 16px Roboto bitmap (about 24 KB). They need `wl_shm` and a seat,
checked-in 16px Roboto bitmap. They need `wl_shm` and a seat,
independently of KDE appmenu export or a session bus. No Qt/GTK, runtime font
library, image decoder, or application GL context is used for menu drawing.
`CONTEXT_MENU` reports protocol availability; opening also requires a visible,
@ -200,65 +225,77 @@ NixOS with Plasma 6.5.6 and Mesa 25.2.6; other systems are not runtime-qualified
hiding/destruction and seat removal complete as `CANCELLED`.
- This small menu has its own light/dark palette, selected from portal appearance
preferences when available. It does not reproduce arbitrary KDE widget themes
or expose an accessibility tree. The bitmap covers printable ASCII, Latin-1
and selected punctuation/arrows, with a replacement glyph for other text; no
shaping or bidi is implemented. Output scales enlarge the 16px bitmap instead
of rerasterizing it. Font provenance, license and maintainer regeneration
instructions are in [font/README.md](font/README.md). The renderer and font stay
entirely inside the Linux backend.
or expose an accessibility tree. The bitmap covers printable ASCII and uses
`?` for unsupported codepoints; no shaping or bidi is implemented. Output
scales enlarge the 16px bitmap instead of rerasterizing it. Font provenance,
license and regeneration instructions are in [font/README.md](font/README.md).
The renderer and font stay entirely inside the Linux backend.
- File watches use inotify. A document watch follows its named path through
atomic replacement by observing its parent. Directory watches observe immediate
children. Queue overflow requests a rescan; lost roots are invalidated. Each
watch owns an inotify descriptor and is subject to the host's instance limits.
## Not yet implemented
Release readiness is the first supported Linux milestone; until then the backend
remains a preview. The remaining milestones, in order:
- Release readiness: run the identical portable artifact on at least two clean
non-Nix Plasma distributions, for example a Kubuntu LTS and Fedora KDE, without
the Nix shell. Check launch, graphics, clipboard and portal dialogs rather than
linkage alone, and confirm native NixOS launches outside `nix-shell`. Report
unverified IME, fractional-scale or hardware cases separately. Shared builds
limit exports with `exports.map`, but no Linux check compares them with the
public header yet.
- Other Wayland desktops: test GNOME, Sway and Hyprland with their portal and IME
setups and broaden GPU coverage, including NVIDIA. Compositors without
server-side decorations need a libdecor adapter that owns toplevel role
creation, because libdecor cannot wrap an independently created `xdg_toplevel`.
Compositors without cursor-shape-v1 need a `libwayland-cursor.so.0` theme
fallback. These fallbacks must work before those desktops are claimed.
- X11: add `src/linux/x11/`, reuse the portal, file, watch and keyboard code, and
choose EGL or GLX from its own driver matrix. `AUTO` may then try X11 after
Wayland startup fails; explicit preferences never fall back. Backend-selection
and Xorg/XWayland tests arrive with it. Until then builds contain no X11
sources or dependencies.
## Tradeoffs
- Runtime verification concentrates on one Plasma Wayland session. Behavior
follows advertised standard protocols and services, with KDE-specific adapters
optional, which keeps GNOME and wlroots compositors reachable; those desktops
and X11 remain follow-on support rather than advertised parity.
- Graphics use EGL on Wayland only, which matches the observed driver stack. X11
graphics choices remain open.
- Zig owns state machines, allocations and lifetimes; C is limited to generated
protocol code and the small `libraries.c` loader. This costs more binding work
than a large C bridge but keeps lifetime and test logic in the library's
primary language.
- Vendored ABI headers and runtime-loaded host libraries give clone-and-build
with Zig alone. UHDK maintains small loaders and a declared runtime baseline
instead of library implementations; host libraries, drivers and loader
compatibility still need validation on each target.
- Server-side decorations avoid a libdecor dependency on KWin; compositors without
them need the adapter above. Library-drawn decorations would add rendering, hit
testing, move/resize and accessibility responsibilities.
- Portals share one asynchronous integration and the sandbox path but depend on
installed portal services. Toolkit dialogs would add dependencies and
event-loop complexity.
- Global-menu export neither guarantees a visible consumer nor supplies context
menus. Accelerators therefore work without a consumer, and context menus use
the internal renderer: no toolkit or font library, but no theme matching,
complex text shaping or accessibility tree.
- XKB composition gives basic typing without an input method; text-input-v3 adds
protocol, range, ordering and interoperability work. `UHDK_CAP_TEXT_INPUT`
reports keyboard text entry, not a working input method.
## Validation
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.

View File

@ -17,6 +17,7 @@ const Sent = struct {
start: usize,
len: usize,
};
pub const State = struct {
enabled: bool = false,
composing: bool = false,
@ -34,15 +35,18 @@ pub const State = struct {
before: u32 = 0,
after: u32 = 0,
};
pub fn listen(input: ?*c.struct_zwp_text_input_v3) void {
_ = c.zwp_text_input_v3_add_listener(input, &listener, null);
}
fn commit() u32 {
const s = Input.state();
s.text_serial +%= 1;
c.zwp_text_input_v3_commit(s.text_input);
return s.text_serial;
}
fn enter(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, surface: ?*c.struct_wl_surface) callconv(.c) void {
const s = Input.state();
s.text_focus = Input.find(surface);
@ -51,49 +55,60 @@ fn enter(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, surface: ?*c.struct_wl
_ = publish(w);
};
}
fn leave(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, _: ?*c.struct_wl_surface) callconv(.c) void {
if (Input.state().text_focus) |w| {
end(w);
clearPending(w);
clearSent(w);
}
Input.state().text_focus = null;
}
fn own(w: *native.Window, destination: *?[]u8, text: [*c]const u8) void {
if (destination.*) |old| w.owner.gpa.free(old);
const bytes = if (text == null) "" else std.mem.span(text);
destination.* = w.owner.gpa.dupe(u8, bytes) catch null;
}
fn preedit(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, text: [*c]const u8, first: i32, last: i32) callconv(.c) void {
const w = Input.state().text_focus orelse return;
own(w, &w.text.pending_preedit, text);
w.text.cursor_begin = first;
w.text.cursor_end = last;
}
fn committed(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, text: [*c]const u8) callconv(.c) void {
const w = Input.state().text_focus orelse return;
own(w, &w.text.pending_commit, text);
}
fn deleted(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, before: u32, after: u32) callconv(.c) void {
const w = Input.state().text_focus orelse return;
w.text.before = before;
w.text.after = after;
}
fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.c) void {
Input.flushKey();
const w = Input.state().text_focus orelse return;
const t = &w.text;
defer clearPending(w);
if (!t.enabled) return;
var sent = t.sent;
while (sent) |value| {
if (value.serial == serial) break;
sent = value.next;
}
// A cleared serial belongs to a cancelled/disabled input session.
const basis = sent orelse return;
if (t.pending_commit) |bytes| if (!std.unicode.utf8ValidateSlice(bytes)) return;
end(w);
if (t.pending_commit != null or t.before != 0 or t.after != 0) {
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_TEXT_COMMIT;
@ -102,6 +117,7 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
event.data.text.revision = basis.revision;
if (t.before != 0 or t.after != 0) {
if (t.before > basis.start or t.after > basis.bytes.len - basis.start - basis.len) return;
const start = basis.start - t.before;
const length = t.before + basis.len + t.after;
if (!abi.boundary(basis.bytes, start) or !abi.boundary(basis.bytes, start + length)) return;
@ -109,28 +125,35 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
event.data.text.replacement_start = basis.offset + start;
event.data.text.replacement_len = length;
}
t.last_edit = event.input_id;
Input.send(w, &event);
end(w);
}
if (t.pending_preedit) |bytes| {
if (bytes.len == 0) end(w);
if (bytes.len != 0 and std.unicode.utf8ValidateSlice(bytes)) {
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_TEXT_PREEDIT;
event.input_id = Input.id();
event.data.text.text = abi.textSpan(bytes);
event.data.text.revision = basis.revision;
const lo: usize = @intCast(@max(0, @min(t.cursor_begin, t.cursor_end)));
const hi: usize = @intCast(@max(0, @max(t.cursor_begin, t.cursor_end)));
if (lo <= hi and hi <= bytes.len and abi.boundary(bytes, lo) and abi.boundary(bytes, hi)) {
event.data.text.selection_start = lo;
event.data.text.selection_len = hi - lo;
}
t.composing = true;
t.ime_composing = true;
t.last_edit = event.input_id;
Input.send(w, &event);
}
}
// Keep the acknowledged basis: more than one done can share its serial.
while (t.sent != basis) {
const old = t.sent.?;
@ -139,21 +162,29 @@ fn done(_: ?*anyopaque, _: ?*c.struct_zwp_text_input_v3, serial: u32) callconv(.
w.owner.gpa.destroy(old);
t.sent_count -= 1;
}
// Never send pending state in response to an older serial. A later matching
// done or an acknowledged application basis will release the throttle.
if (serial == Input.state().text_serial and t.dirty and t.snapshot.acknowledged_input_id >= t.last_edit) _ = publish(w);
}
const listener: c.struct_zwp_text_input_v3_listener = .{ .enter = enter, .leave = leave, .preedit_string = preedit, .commit_string = committed, .delete_surrounding_text = deleted, .done = done };
pub fn crop(bytes: []const u8, start: usize, length: usize) ?struct { start: usize, end: usize } {
pub fn crop(bytes: []const u8, start: usize, length: usize) ?struct {
start: usize,
end: usize,
} {
if (length > 4000 or std.mem.findScalar(u8, bytes, 0) != null) return null;
var lo = start -| ((4000 - length) / 2);
while (lo < start and !abi.boundary(bytes, lo)) lo += 1;
var hi = @min(bytes.len, lo + 4000);
while (hi > start + length and !abi.boundary(bytes, hi)) hi -= 1;
if (hi < start + length) return null;
return .{ .start = lo, .end = hi };
}
fn publish(w: *native.Window) u32 {
const s = Input.state();
const t = &w.text;
@ -162,25 +193,30 @@ fn publish(w: *native.Window) u32 {
t.dirty = true;
return abi.OK;
}
// Bound unacknowledged snapshots without discarding snapshots a late IME
// batch may still refer to. Keep the newest application state for later.
if (t.sent_count >= 32) {
t.dirty = true;
return abi.OK;
}
const range = crop(t.surrounding, @intCast(t.snapshot.selection_start), @intCast(t.snapshot.selection_len));
const sent = w.owner.gpa.create(Sent) catch return abi.OOM;
const bytes = w.owner.gpa.dupeZ(u8, if (range) |r| t.surrounding[r.start..r.end] else "") catch {
const bytes = w.owner.gpa.dupeSentinel(u8, if (range) |r| t.surrounding[r.start..r.end] else "", 0) catch {
w.owner.gpa.destroy(sent);
return abi.OOM;
};
sent.* = .{ .serial = s.text_serial +% 1, .revision = t.snapshot.revision, .bytes = bytes, .offset = if (range) |r| r.start else 0, .start = if (range) |r| @intCast(t.snapshot.selection_start - r.start) else 0, .len = if (range != null) @intCast(t.snapshot.selection_len) else 0 };
c.zwp_text_input_v3_set_surrounding_text(s.text_input, bytes, @intCast(sent.start + sent.len), @intCast(sent.start));
const caret = t.snapshot.caret;
c.zwp_text_input_v3_set_cursor_rectangle(s.text_input, @intFromFloat(std.math.clamp(caret.x, -1000000, 1000000)), @intFromFloat(std.math.clamp(caret.y, -1000000, 1000000)), @intFromFloat(@min(caret.width, 1000000)), @intFromFloat(@min(caret.height, 1000000)));
c.zwp_text_input_v3_set_content_type(s.text_input, c.ZWP_TEXT_INPUT_V3_CONTENT_HINT_MULTILINE, c.ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL);
c.zwp_text_input_v3_set_text_change_cause(s.text_input, if (t.snapshot.acknowledged_input_id == t.last_edit) c.ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_INPUT_METHOD else c.ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_OTHER);
_ = commit();
var link = &t.sent;
while (link.*) |item| link = &item.next;
link.* = sent;
@ -188,9 +224,11 @@ fn publish(w: *native.Window) u32 {
t.dirty = false;
return abi.OK;
}
pub fn snapshot(w: *native.Window, value: n.uhdk_text_state) u32 {
const t = &w.text;
if (value.acknowledged_input_id < t.last_edit) return abi.OK;
const bytes = abi.textBytes(value.surrounding_text);
const same = t.snapshot.revision == value.revision and t.snapshot.selection_start == value.selection_start and t.snapshot.selection_len == value.selection_len and
std.meta.eql(t.snapshot.caret, value.caret) and std.mem.eql(u8, t.surrounding, bytes);
@ -200,35 +238,44 @@ pub fn snapshot(w: *native.Window, value: n.uhdk_text_state) u32 {
t.snapshot = value;
t.snapshot.surrounding_text = abi.textSpan(copy);
if (same and !t.dirty) return abi.OK;
t.dirty = true;
return publish(w);
}
pub fn enable(w: *native.Window, enabled: bool) u32 {
const t = &w.text;
if (enabled and Input.state().context == null) return n.UHDK_STATUS_UNSUPPORTED;
if (t.enabled == enabled) return abi.OK;
end(w);
clearPending(w);
clearSent(w);
if (Input.state().compose != null) c.z_xkb_compose_state_reset.?(Input.state().compose);
t.enabled = enabled;
const s = Input.state();
if (s.text_input != null and s.text_focus == w) {
if (enabled) {
c.zwp_text_input_v3_enable(s.text_input);
return publish(w);
}
c.zwp_text_input_v3_disable(s.text_input);
_ = commit();
}
return abi.OK;
}
fn end(w: *native.Window) void {
if (w.text.composing) endAt(w, Input.id());
}
fn endAt(w: *native.Window, input_id: u64) void {
const t = &w.text;
if (!t.composing) return;
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_TEXT_COMPOSITION_END;
e.input_id = input_id;
@ -237,6 +284,7 @@ fn endAt(w: *native.Window, input_id: u64) void {
t.composing = false;
t.ime_composing = false;
}
fn clearPending(w: *native.Window) void {
const t = &w.text;
if (t.pending_preedit) |p| w.owner.gpa.free(p);
@ -246,19 +294,23 @@ fn clearPending(w: *native.Window) void {
t.before = 0;
t.after = 0;
}
fn clearSent(w: *native.Window) void {
while (w.text.sent) |item| {
w.text.sent = item.next;
w.owner.gpa.free(item.bytes);
w.owner.gpa.destroy(item);
}
w.text.sent_count = 0;
w.text.dirty = true;
}
pub fn cancel(w: *native.Window) void {
end(w);
clearPending(w);
clearSent(w);
const s = Input.state();
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
if (s.text_input != null and s.text_focus == w and w.text.enabled) {
@ -268,21 +320,26 @@ pub fn cancel(w: *native.Window) void {
_ = publish(w);
}
}
pub fn forget(w: *native.Window) void {
if (Input.state().text_focus == w) {
_ = enable(w, false);
Input.state().text_focus = null;
}
end(w);
clearPending(w);
clearSent(w);
}
pub fn deinit(w: *native.Window) void {
forget(w);
w.owner.gpa.free(w.text.surrounding);
}
pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u64) void {
if (w.text.ime_composing) return;
// A mutation or movement makes old surrounding-text ranges unsafe. Copy
// leaves the document/selection untouched, so delayed IME batches may retain
// their previously published basis. New state is published only on app ack.
@ -290,6 +347,7 @@ pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u6
clearPending(w);
clearSent(w);
}
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_EDIT_COMMAND;
event.input_id = input_id;
@ -297,6 +355,7 @@ pub fn editCommand(w: *native.Window, command: u32, modifiers: u32, input_id: u6
w.text.last_edit = input_id;
Input.send(w, &event);
}
pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers: u32, plain: []const u8) void {
const s = Input.state();
const t = &w.text;
@ -305,6 +364,7 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
if (Keyboard.edit(logical, modifiers) == n.UHDK_EDIT_CANCEL) cancel(w);
return;
}
const edit = Keyboard.edit(logical, modifiers);
if (edit != 0) {
// Escape cancels an XKB compose sequence before becoming an app action.
@ -313,11 +373,13 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
endAt(w, input_id);
return;
}
if (s.compose != null) c.z_xkb_compose_state_reset.?(s.compose);
endAt(w, input_id);
editCommand(w, edit, modifiers, input_id);
return;
}
if (modifiers & (n.UHDK_MOD_CONTROL | n.UHDK_MOD_ALT | n.UHDK_MOD_SUPER) != 0) return;
var buffer: [256]u8 = undefined;
var length: c_int = @intCast(plain.len);
@ -342,6 +404,7 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
else => {},
}
}
if (length <= 0 or length >= buffer.len or buffer[0] < 32 or buffer[0] == 127) return;
var e = std.mem.zeroes(n.z_event);
e.type = n.UHDK_EVENT_TEXT_COMMIT;
@ -351,12 +414,14 @@ pub fn key(w: *native.Window, sym: u32, logical: u32, input_id: u64, modifiers:
t.last_edit = input_id;
Input.send(w, &e);
}
test "surrounding crop preserves UTF-8 and complete selections" {
var bytes: [8000]u8 = undefined;
for (0..4000) |i| {
bytes[i * 2] = 0xc3;
bytes[i * 2 + 1] = 0xa9;
}
const range = crop(&bytes, 3998, 4).?;
try std.testing.expect(range.start % 2 == 0 and range.end % 2 == 0 and range.end - range.start <= 4000);
try std.testing.expect(range.start <= 3998 and range.end >= 4002);

440
src/linux/Tray.zig Normal file
View File

@ -0,0 +1,440 @@
//! StatusNotifierItem without a toolkit. Each item has a private bus identity so
//! disconnecting it removes it from watchers that offer no unregister method.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
const native = @import("native.zig");
const runtime = @import("../runtime.zig");
const abi = @import("../abi.zig");
const Bus = @import("Bus.zig");
const Portal = @import("Portal.zig");
const Menus = @import("KdeAppMenu.zig");
const Desktop = @import("Desktop.zig");
const watcher = "org.kde.StatusNotifierWatcher";
const watcher_path = "/StatusNotifierWatcher";
const iface = "org.kde.StatusNotifierItem";
const path = "/StatusNotifierItem";
const properties = "org.freedesktop.DBus.Properties";
const dbus = "org.freedesktop.DBus";
pub const Item = struct {
next: ?*Item = null,
handle: *n.uhdk_tray,
menu: ?*Menus.Export = null,
connection: ?*c.DBusConnection = null,
hello: u32 = 0,
registration: u32 = 0,
registered: bool = false,
deadline: u64 = 0,
};
pub const State = struct {
items: ?*Item = null,
owner: ?[:0]u8 = null,
owner_query: u32 = 0,
host_query: u32 = 0,
host: bool = false,
};
fn backend() *native.Backend {
return native.instance.?;
}
fn state() *State {
return &backend().tray;
}
fn same(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
fn send(connection: *c.DBusConnection, message: *Bus.Message) !u32 {
var serial: u32 = 0;
if (c.z_dbus_connection_send.?(connection, message, &serial) == 0) return error.OutOfMemory;
return serial;
}
fn report(item: *Item) void {
const hidden = n.z_tray_desc(item.handle).*.hidden != 0;
n.z_tray_state(item.handle, @intFromBool(item.registered and !hidden), if (hidden or item.registered) abi.OK else abi.UNAVAILABLE);
}
fn stop(item: *Item) void {
if (item.menu) |menu| menu.connection = null;
if (item.connection) |conn| {
c.z_dbus_connection_close.?(conn);
c.z_dbus_connection_unref.?(conn);
}
item.connection = null;
item.hello = 0;
item.registration = 0;
item.registered = false;
item.deadline = 0;
report(item);
}
fn start(item: *Item) !void {
if (!state().host or item.connection != null or n.z_tray_desc(item.handle).*.hidden != 0) {
report(item);
return;
}
const address = c.getenv("DBUS_SESSION_BUS_ADDRESS") orelse return;
const conn = c.z_dbus_connection_open_private.?(address, null) orelse return;
item.connection = conn;
errdefer stop(item);
c.z_dbus_connection_set_exit_on_disconnect.?(conn, 0);
const hello = try Bus.method(dbus, "/org/freedesktop/DBus", dbus, "Hello");
defer c.z_dbus_message_unref.?(hello);
item.hello = try send(conn, hello);
item.deadline = runtime.now(backend().app.io) + 5 * std.time.ns_per_s;
}
pub fn update(handle: *n.uhdk_tray, desc: *const n.uhdk_tray_desc) u32 {
const existing = n.z_object_native(handle);
const item: *Item = if (existing) |p| @ptrCast(@alignCast(p)) else backend().app.gpa.create(Item) catch return abi.OOM;
const menu = if (desc.menu) |root| Menus.createTray(handle, runtime.fromObjectHandle(root)) catch {
if (existing == null) backend().app.gpa.destroy(item);
return abi.OOM;
} else null;
if (existing == null) {
item.* = .{ .handle = handle, .next = state().items };
state().items = item;
n.z_object_set_native(handle, item);
}
if (item.menu) |old| Menus.destroy(old);
item.menu = menu;
if (menu) |m| m.connection = if (item.hello == 0) item.connection else null;
if (desc.hidden != 0) {
stop(item);
} else {
start(item) catch {};
if (item.registered) changed(item) catch {
stop(item);
};
}
report(item);
return abi.OK;
}
pub fn destroy(item: *Item) void {
stop(item);
if (item.menu) |menu| Menus.destroy(menu);
var link = &state().items;
while (link.* != item) link = &link.*.?.next;
link.* = item.next;
backend().app.gpa.destroy(item);
}
pub fn ready() !void {
const query = try Bus.method(dbus, "/org/freedesktop/DBus", dbus, "GetNameOwner");
defer c.z_dbus_message_unref.?(query);
var args = Bus.append(query);
try Bus.string(&args, watcher);
state().owner_query = try Portal.send(query);
}
fn setOwner(owner: []const u8) !void {
const copied = if (owner.len != 0) try backend().app.gpa.dupeSentinel(u8, owner, 0) else null;
if (state().owner) |old| backend().app.gpa.free(old);
state().owner = copied;
state().host_query = 0;
state().host = false;
native.setCapability(n.UHDK_CAP_TRAY, false);
var cursor = state().items;
while (cursor) |item| : (cursor = item.next) stop(item);
if (copied) |name| {
const query = try Bus.method(name.ptr, watcher_path, properties, "Get");
defer c.z_dbus_message_unref.?(query);
var args = Bus.append(query);
try Bus.string(&args, watcher);
try Bus.string(&args, "IsStatusNotifierHostRegistered");
state().host_query = try Portal.send(query);
}
}
fn setHost(host: bool) void {
state().host = host;
native.setCapability(n.UHDK_CAP_TRAY, host);
var cursor = state().items;
while (cursor) |item| : (cursor = item.next) {
if (host) start(item) catch {} else stop(item);
}
}
pub fn process(message: *Bus.Message) !bool {
const serial = c.z_dbus_message_get_reply_serial.?(message);
const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
var args = Bus.parse(message);
if (serial != 0 and serial == state().owner_query) {
state().owner_query = 0;
try setOwner(if (!failed) Bus.str(&args) orelse "" else "");
return true;
}
if (serial != 0 and serial == state().host_query) {
state().host_query = 0;
if (!failed) {
var value = Bus.variant(&args) orelse return true;
if (Bus.kind(&value) == c.DBUS_TYPE_BOOLEAN) {
var yes: c.dbus_bool_t = 0;
c.z_dbus_message_iter_get_basic.?(&value, &yes);
setHost(yes != 0);
}
}
return true;
}
const sender = c.z_dbus_message_get_sender.?(message) orelse return false;
if (same(std.mem.span(sender), dbus) and c.z_dbus_message_is_signal.?(message, dbus, "NameOwnerChanged") != 0 and c.z_dbus_message_has_signature.?(message, "sss") != 0 and same(Bus.str(&args).?, watcher)) {
_ = Bus.next(&args);
_ = Bus.next(&args);
state().owner_query = 0; // Do not resurrect a superseded discovery reply.
try setOwner(Bus.str(&args).?);
return true;
}
if (state().owner) |owner| {
if (same(std.mem.span(sender), owner)) {
if (c.z_dbus_message_is_signal.?(message, watcher, "StatusNotifierHostRegistered") != 0) {
state().host_query = 0;
setHost(true);
return true;
}
if (c.z_dbus_message_is_signal.?(message, watcher, "StatusNotifierHostUnregistered") != 0) {
state().host_query = 0;
setHost(false);
return true;
}
}
}
return false;
}
pub fn disconnected() void {
state().owner_query = 0;
state().host_query = 0;
setHost(false);
if (state().owner) |owner| backend().app.gpa.free(owner);
state().owner = null;
}
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var cursor = state().items;
while (cursor) |item| : (cursor = item.next) {
if (item.connection) |conn| {
var fd: c_int = -1;
if (c.z_dbus_connection_get_unix_fd.?(conn, &fd) != 0) try fds.append(backend().app.gpa, .{
.fd = fd,
.events = @as(c_short, c.POLLIN) | @as(c_short, if (c.z_dbus_connection_has_messages_to_send.?(conn) != 0) c.POLLOUT else 0),
.revents = 0,
});
}
}
}
pub fn tick() i32 {
var pending = false;
var cursor = state().items;
while (cursor) |item| : (cursor = item.next) {
const conn = item.connection orelse continue;
if (c.z_dbus_connection_read_write.?(conn, 0) == 0) {
stop(item);
continue;
}
for (0..32) |_| {
const message = c.z_dbus_connection_pop_message.?(conn) orelse break;
defer c.z_dbus_message_unref.?(message);
dispatch(item, message) catch {
stop(item);
break;
};
if (item.connection == null) break;
} else pending = true;
if (item.deadline != 0) {
if (runtime.now(backend().app.io) >= item.deadline) stop(item) else pending = true;
}
}
return if (pending) 10 else -1;
}
fn fail(item: *Item, message: *Bus.Message, name: [*:0]const u8) !void {
if (c.z_dbus_message_get_no_reply.?(message) != 0) return;
const reply = c.z_dbus_message_new_error.?(message, name, "Tray request could not be handled") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
_ = try send(item.connection.?, reply);
}
fn variant(out: *Bus.Iter, comptime signature: [:0]const u8, value: anytype) !void {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, signature);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
try Bus.basic(&v, signature[0], value);
try Bus.close(out, &v);
}
fn textVariant(out: *Bus.Iter, text: n.uhdk_text) !void {
// Tray snapshots own sentinel-terminated copies of public spans.
try variant(out, "s", text.ptr);
}
fn pixmap(out: *Bus.Iter, icon: ?*const n.uhdk_image) !void {
var list = try Bus.open(out, c.DBUS_TYPE_ARRAY, "(iiay)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &list);
if (icon) |i| {
var tuple = try Bus.open(&list, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&list, &tuple);
try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(i.width)));
try Bus.basic(&tuple, c.DBUS_TYPE_INT32, @as(i32, @intCast(i.height)));
var bytes = try Bus.open(&tuple, c.DBUS_TYPE_ARRAY, "y");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&tuple, &bytes);
var offset: usize = 0;
while (offset < i.pixels.len) : (offset += 4) {
for ([_]usize{ 3, 0, 1, 2 }) |channel| try Bus.basic(&bytes, c.DBUS_TYPE_BYTE, i.pixels.ptr[offset + channel]);
}
try Bus.close(&tuple, &bytes);
try Bus.close(&list, &tuple);
}
try Bus.close(out, &list);
}
const names = [_][:0]const u8{ "Category", "Id", "Title", "Status", "WindowId", "IconName", "IconPixmap", "OverlayIconName", "OverlayIconPixmap", "AttentionIconName", "AttentionIconPixmap", "AttentionMovieName", "IconThemePath", "ToolTip", "ItemIsMenu", "Menu" };
fn property(item: *Item, name: []const u8, out: *Bus.Iter) !bool {
const d = n.z_tray_desc(item.handle);
if (same(name, "Id")) {
try textVariant(out, d.*.id);
} else if (same(name, "Title")) {
try textVariant(out, d.*.title);
} else if (same(name, "Category")) {
try variant(out, "s", @as([*:0]const u8, "ApplicationStatus"));
} else if (same(name, "Status")) {
try variant(out, "s", @as([*:0]const u8, if (d.*.hidden != 0) "Passive" else "Active"));
} else if (same(name, "WindowId")) {
try variant(out, "i", @as(i32, 0));
} else if (same(name, "ItemIsMenu")) {
try variant(out, "b", @as(u32, @intCast(d.*.menu_on_primary)));
} else if (same(name, "Menu")) {
try variant(out, "o", @as([*:0]const u8, if (item.menu) |menu| menu.path.ptr else "/NO_DBUSMENU"));
} else if (same(name, "IconPixmap") or same(name, "OverlayIconPixmap") or same(name, "AttentionIconPixmap")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "a(iiay)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
try pixmap(&v, if (same(name, "IconPixmap")) &d.*.icon else null);
try Bus.close(out, &v);
} else if (same(name, "ToolTip")) {
var v = try Bus.open(out, c.DBUS_TYPE_VARIANT, "(sa(iiay)ss)");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(out, &v);
var tuple = try Bus.open(&v, c.DBUS_TYPE_STRUCT, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&v, &tuple);
try Bus.string(&tuple, "");
try pixmap(&tuple, null);
try Bus.string(&tuple, if (d.*.tooltip.len != 0) d.*.tooltip.ptr else d.*.title.ptr);
// Hosts may interpret the body as markup; plain text belongs in title.
// Include tooltip as the title when provided and leave the markup body empty.
try Bus.string(&tuple, "");
try Bus.close(&v, &tuple);
try Bus.close(out, &v);
} else {
for ([_][]const u8{ "IconName", "OverlayIconName", "AttentionIconName", "AttentionMovieName", "IconThemePath" }) |key| {
if (same(name, key)) {
try variant(out, "s", @as([*:0]const u8, ""));
return true;
}
}
return false;
}
return true;
}
fn changed(item: *Item) !void {
for ([_][*:0]const u8{ "NewTitle", "NewIcon", "NewToolTip" }) |name| {
const message = c.z_dbus_message_new_signal.?(path, iface, name) orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message);
_ = try send(item.connection.?, message);
}
const message = c.z_dbus_message_new_signal.?(path, properties, "PropertiesChanged") orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(message);
var out = Bus.append(message);
try Bus.string(&out, iface);
var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
for ([_][:0]const u8{ "Menu", "ItemIsMenu" }) |name| {
var pair = try Bus.open(&dict, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&dict, &pair);
try Bus.string(&pair, name.ptr);
_ = try property(item, name, &pair);
try Bus.close(&dict, &pair);
}
try Bus.close(&out, &dict);
var invalidated = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "s");
try Bus.close(&out, &invalidated);
_ = try send(item.connection.?, message);
}
fn dispatch(item: *Item, message: *Bus.Message) !void {
const serial = c.z_dbus_message_get_reply_serial.?(message);
const failed = c.z_dbus_message_get_type.?(message) == c.DBUS_MESSAGE_TYPE_ERROR;
var args = Bus.parse(message);
if (serial != 0 and serial == item.hello) {
item.hello = 0;
if (failed or Bus.str(&args) == null) {
stop(item);
return;
}
if (item.menu) |menu| menu.connection = item.connection;
const request = try Bus.method(state().owner.?.ptr, watcher_path, watcher, "RegisterStatusNotifierItem");
defer c.z_dbus_message_unref.?(request);
var out = Bus.append(request);
try Bus.string(&out, @ptrCast(Bus.str(&args).?.ptr));
item.registration = try send(item.connection.?, request);
return;
}
if (serial != 0 and serial == item.registration) {
item.registration = 0;
item.deadline = 0;
if (failed) stop(item) else {
item.registered = true;
report(item);
}
return;
}
if (c.z_dbus_message_get_type.?(message) != c.DBUS_MESSAGE_TYPE_METHOD_CALL) return;
const raw_path = c.z_dbus_message_get_path.?(message) orelse return;
if (item.menu) |menu| {
if (same(std.mem.span(raw_path), menu.path)) return Menus.dispatch(menu, message);
}
if (!same(std.mem.span(raw_path), path)) return fail(item, message, "org.freedesktop.DBus.Error.UnknownObject");
const raw_iface = c.z_dbus_message_get_interface.?(message) orelse return fail(item, message, "org.freedesktop.DBus.Error.UnknownInterface");
const raw_member = c.z_dbus_message_get_member.?(message) orelse return;
const interface = std.mem.span(raw_iface);
const member = std.mem.span(raw_member);
const reply = c.z_dbus_message_new_method_return.?(message) orelse return error.OutOfMemory;
defer c.z_dbus_message_unref.?(reply);
var out = Bus.append(reply);
const invalid = "org.freedesktop.DBus.Error.InvalidArgs";
if (same(interface, properties) and (same(member, "Get") or same(member, "GetAll"))) {
const single = same(member, "Get");
if (c.z_dbus_message_has_signature.?(message, if (single) "ss" else "s") == 0) return fail(item, message, invalid);
if (!same(Bus.str(&args).?, iface)) return fail(item, message, "org.freedesktop.DBus.Error.UnknownInterface");
if (single) {
_ = Bus.next(&args);
if (!try property(item, Bus.str(&args).?, &out)) return fail(item, message, "org.freedesktop.DBus.Error.UnknownProperty");
} else {
var dict = try Bus.open(&out, c.DBUS_TYPE_ARRAY, "{sv}");
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&out, &dict);
for (names) |name| {
var pair = try Bus.open(&dict, c.DBUS_TYPE_DICT_ENTRY, null);
errdefer c.z_dbus_message_iter_abandon_container_if_open.?(&dict, &pair);
try Bus.string(&pair, name.ptr);
_ = try property(item, name, &pair);
try Bus.close(&dict, &pair);
}
try Bus.close(&out, &dict);
}
} else if (same(interface, "org.freedesktop.DBus.Introspectable") and same(member, "Introspect")) {
if (c.z_dbus_message_has_signature.?(message, "") == 0) return fail(item, message, invalid);
try Bus.string(&out, @embedFile("tray.xml"));
} else if (same(interface, "org.freedesktop.DBus.Peer") and same(member, "Ping")) {
if (c.z_dbus_message_has_signature.?(message, "") == 0) return fail(item, message, invalid);
} else if (same(interface, iface) and (same(member, "Activate") or same(member, "SecondaryActivate"))) {
if (c.z_dbus_message_has_signature.?(message, "ii") == 0) return fail(item, message, invalid);
n.z_tray_activate(item.handle, if (same(member, "Activate")) n.UHDK_TRAY_ACTIVATE_PRIMARY else n.UHDK_TRAY_ACTIVATE_SECONDARY);
} else if (same(interface, iface) and same(member, "ContextMenu")) {
if (c.z_dbus_message_has_signature.?(message, "ii") == 0) return fail(item, message, invalid);
return fail(item, message, "org.freedesktop.DBus.Error.NotSupported"); // Host renders Menu.
} else if (same(interface, iface) and same(member, "ProvideXdgActivationToken")) {
if (c.z_dbus_message_has_signature.?(message, "s") == 0) return fail(item, message, invalid);
const token = Bus.str(&args).?;
if (token.len > 4096) return fail(item, message, invalid);
try Desktop.trayToken(token);
} else if (same(interface, iface) and same(member, "Scroll")) {
if (c.z_dbus_message_has_signature.?(message, "is") == 0) return fail(item, message, invalid);
} else return fail(item, message, "org.freedesktop.DBus.Error.UnknownMethod");
if (c.z_dbus_message_get_no_reply.?(message) == 0) _ = try send(item.connection.?, reply);
}

View File

@ -14,47 +14,62 @@ pub const Watch = struct {
directory: []u8,
name: []u8,
};
fn b() *native.Backend {
fn backend() *native.Backend {
return native.instance.?;
}
pub fn create(cmd: *const n.z_command, result: *n.z_request_result) u32 {
const root: ?*n.uhdk_file = @ptrCast(cmd.target);
const path = b().app.gpa.dupeZ(u8, abi.bytes(n.z_file_path(root))) catch return abi.OOM;
defer b().app.gpa.free(path);
pub fn prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
const path = backend().app.gpa.dupeSentinel(u8, abi.bytes(n.z_file_path(root)), 0) catch return abi.OOM;
defer backend().app.gpa.free(path);
const kind = c.z_linux_is_directory(path);
if (kind < 0 and c.z_linux_errno() != c.ENOENT) return n.UHDK_STATUS_OS_ERROR;
const directory = b().app.gpa.dupeZ(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/") catch return abi.OOM;
defer b().app.gpa.free(directory);
const directory = backend().app.gpa.dupeSentinel(u8, if (kind == 1) path else std.fs.path.dirname(path) orelse "/", 0) catch return abi.OOM;
defer backend().app.gpa.free(directory);
const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
if (fd < 0) return n.UHDK_STATUS_OS_ERROR;
const mask = c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_MODIFY | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_ONLYDIR;
if (c.inotify_add_watch(fd, directory, mask) < 0) {
_ = c.close(fd);
return n.UHDK_STATUS_OS_ERROR;
}
const w = allocate(fd, root, @ptrCast(cmd.other), directory, if (kind == 1) "" else std.fs.path.basename(path)) catch {
const w = allocate(fd, root, handle, directory, if (kind == 1) "" else std.fs.path.basename(path)) catch {
_ = c.close(fd);
return abi.OOM;
};
w.next = b().watches;
b().watches = w;
n.z_object_set_native(cmd.other, w);
result.value.watch = w.handle;
out.* = w;
return abi.OK;
}
pub fn commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
const w: *Watch = @ptrCast(@alignCast(prepared));
w.next = backend().watches;
backend().watches = w;
n.z_object_set_native(handle, w);
}
fn allocate(fd: c_int, root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, directory: []const u8, name: []const u8) !*Watch {
const gpa = b().app.gpa;
const gpa = backend().app.gpa;
const w = try gpa.create(Watch);
errdefer gpa.destroy(w);
const dir = try gpa.dupe(u8, directory);
errdefer gpa.free(dir);
w.* = .{ .fd = fd, .root = root, .handle = handle, .directory = dir, .name = try gpa.dupe(u8, name) };
return w;
}
pub fn poll(fds: *std.ArrayList(c.struct_pollfd)) !void {
var w = b().watches;
while (w) |item| : (w = item.next) if (item.fd >= 0) try fds.append(b().app.gpa, .{ .fd = item.fd, .events = c.POLLIN, .revents = 0 });
var w = backend().watches;
while (w) |item| : (w = item.next) if (item.fd >= 0) try fds.append(backend().app.gpa, .{ .fd = item.fd, .events = c.POLLIN, .revents = 0 });
}
pub fn flags(mask: u32) u32 {
var value: u32 = 0;
if (mask & (c.IN_CREATE | c.IN_MOVED_TO) != 0) value |= n.UHDK_CHANGE_CREATED;
@ -66,25 +81,29 @@ pub fn flags(mask: u32) u32 {
if (mask & (c.IN_DELETE_SELF | c.IN_MOVE_SELF | c.IN_IGNORED | c.IN_UNMOUNT) != 0) value |= n.UHDK_CHANGE_ROOT_INVALIDATED;
return value;
}
fn emit(w: *Watch, changes: u32, name: []const u8, status: u32) void {
var file = w.root;
if (w.name.len == 0 and name.len != 0) {
const path = std.fs.path.join(b().app.gpa, &.{ w.directory, name }) catch null;
const path = std.fs.path.join(backend().app.gpa, &.{ w.directory, name }) catch null;
if (path) |p| {
defer b().app.gpa.free(p);
file = n.z_file_from_url(runtime.toAppHandle(b().app), .{ .ptr = p.ptr, .len = p.len }, null);
defer backend().app.gpa.free(p);
file = n.z_file_from_url(runtime.toAppHandle(backend().app), .{ .ptr = p.ptr, .len = p.len }, null);
} else file = null;
}
defer if (file != null and file != w.root) n.uhdk_file_release(file);
var event = std.mem.zeroes(n.z_event);
event.type = n.UHDK_EVENT_WATCH;
event.data.watch = .{ .watch = w.handle, .flags = changes, .status = status, .file = file };
n.z_emit(runtime.toAppHandle(b().app), &event);
n.z_emit(runtime.toAppHandle(backend().app), &event);
}
pub fn tick() void {
var cursor = b().watches;
var cursor = backend().watches;
while (cursor) |w| : (cursor = w.next) {
if (w.fd < 0) continue;
var buffer: [65536]u8 align(@alignOf(c.struct_inotify_event)) = undefined;
const count = c.z_linux_read(w.fd, &buffer, buffer.len);
if (count < 0) {
@ -93,14 +112,17 @@ pub fn tick() void {
_ = c.close(w.fd);
w.fd = -1;
}
continue;
}
var offset: usize = 0;
while (offset + @sizeOf(c.struct_inotify_event) <= @as(usize, @intCast(count))) {
const event: *const c.struct_inotify_event = @ptrCast(@alignCast(&buffer[offset]));
const start = offset + @sizeOf(c.struct_inotify_event);
offset = start + event.len;
if (offset > @as(usize, @intCast(count))) break;
const bytes = buffer[start..offset];
const name = bytes[0 .. std.mem.findScalar(u8, bytes, 0) orelse bytes.len];
const changes = flags(event.mask);
@ -114,15 +136,17 @@ pub fn tick() void {
}
}
}
pub fn destroy(w: *Watch) void {
var link = &b().watches;
var link = &backend().watches;
while (link.* != w) link = &link.*.?.next;
link.* = w.next;
if (w.fd >= 0) _ = c.close(w.fd);
b().app.gpa.free(w.directory);
b().app.gpa.free(w.name);
b().app.gpa.destroy(w);
backend().app.gpa.free(w.directory);
backend().app.gpa.free(w.name);
backend().app.gpa.destroy(w);
}
test "watch replacement is remove/create, overflow and invalidation stay distinct" {
try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_CREATED | n.UHDK_CHANGE_RENAMED), flags(c.IN_MOVED_TO));
try std.testing.expectEqual(@as(u32, n.UHDK_CHANGE_RESCAN_REQUIRED), flags(c.IN_Q_OVERFLOW));

View File

@ -10,6 +10,7 @@ pub const Observation = struct {
suspended: bool = false,
known: u32 = n.UHDK_WINDOW_OBSERVE_RESIZING,
};
pub fn observe(version: u32, states: []const u32) Observation {
var result: Observation = .{};
if (version >= 6) result.known |= n.UHDK_WINDOW_OBSERVE_SUSPENDED;
@ -25,6 +26,7 @@ pub fn observe(version: u32, states: []const u32) Observation {
};
return result;
}
pub const Capabilities = struct {
// Before v5 there is no advertisement; preserve best-effort requests.
minimize: bool = true,
@ -42,18 +44,22 @@ pub const Capabilities = struct {
return result;
}
};
test "Wayland observations do not invent minimization or occlusion" {
const old = observe(5, &.{ 1, 2, 3, 4, 9, 999 });
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_FULLSCREEN), old.geometry);
try std.testing.expect(old.focused and old.resizing and !old.suspended);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_OBSERVE_RESIZING), old.known);
const modern = observe(6, &.{ 9, 2, 1 });
try std.testing.expect(modern.suspended and !modern.resizing);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_FULLSCREEN), modern.geometry);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_OBSERVE_RESIZING | n.UHDK_WINDOW_OBSERVE_SUSPENDED), modern.known);
const resumed = observe(6, &.{});
try std.testing.expect(!resumed.suspended and !resumed.focused and !resumed.resizing);
try std.testing.expectEqual(@as(u32, n.UHDK_WINDOW_NORMAL), resumed.geometry);
const caps = Capabilities.announced(&.{ 2, 999 });
try std.testing.expect(caps.maximize and !caps.minimize and !caps.fullscreen);
try std.testing.expect(!Capabilities.announced(&.{}).maximize);

View File

@ -5,7 +5,6 @@
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdlib.h>
@ -32,6 +31,7 @@
#include "viewporter.h"
#include "fractional-scale-v1.h"
#include "cursor-shape-v1.h"
#include "pointer-constraints-unstable-v1.h"
#include "text-input-unstable-v3.h"
#include "xdg-activation-v1.h"
#include "xdg-foreign-unstable-v2.h"
@ -50,5 +50,4 @@ int z_linux_poll(struct pollfd *, nfds_t, int);
ssize_t z_linux_read(int, void *, size_t);
ssize_t z_linux_write(int, const void *, size_t);
ssize_t z_linux_pipe_write(int, const void *, size_t);
int z_linux_is_main_thread(void);
#endif

View File

@ -1,47 +1,53 @@
const std = @import("std");
pub fn configure(b: *std.Build, module: *std.Build.Module, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) void {
pub fn configure(b: *std.Build, module: *std.Build.Module, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize) void {
const bindings = b.addTranslateC(.{
.root_source_file = b.path("src/linux/bindings.h"),
.target = target,
.optimize = optimize,
});
for ([_][]const u8{ "src/linux", "src/linux/vendor/wayland", "src/linux/vendor", "src/linux/vendor/dbus", "src/linux/vendor/khronos", "src/linux/protocols/generated" }) |path| {
for ([_][]const u8{
"src/linux",
"src/linux/vendor/wayland",
"src/linux/vendor",
"src/linux/vendor/dbus",
"src/linux/vendor/khronos",
"src/linux/protocols/generated",
}) |path| {
bindings.addIncludePath(b.path(path));
module.addIncludePath(b.path(path));
}
module.addImport("linux_c", bindings.createModule());
module.addCSourceFile(.{ .file = b.path("src/linux/libraries.c"), .flags = &.{ "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } });
for ([_][]const u8{ "wayland", "xdg-shell", "xdg-decoration-unstable-v1", "viewporter", "fractional-scale-v1", "cursor-shape-v1", "tablet-v2", "text-input-unstable-v3", "xdg-activation-v1", "xdg-foreign-unstable-v2", "xdg-toplevel-icon-v1", "appmenu" }) |name| {
module.addCSourceFile(.{
.file = b.path("src/linux/libraries.c"),
.flags = &.{ "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" },
});
for ([_][]const u8{
"wayland",
"xdg-shell",
"xdg-decoration-unstable-v1",
"viewporter",
"fractional-scale-v1",
"cursor-shape-v1",
"pointer-constraints-unstable-v1",
"tablet-v2",
"text-input-unstable-v3",
"xdg-activation-v1",
"xdg-foreign-unstable-v2",
"xdg-toplevel-icon-v1",
"appmenu",
}) |name| {
module.addCSourceFile(.{
.file = b.path(b.fmt("src/linux/protocols/generated/{s}.c", .{name})),
.flags = &.{ "-std=c99", "-include", b.path("src/linux/protocols/generated/private-symbols.h").getPath(b) },
.flags = &.{
"-std=c99",
"-fdata-sections",
},
});
}
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" } });
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" } });
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);
}

6
src/linux/exports.map Normal file
View File

@ -0,0 +1,6 @@
{
global:
uhdk_*;
local:
*;
};

View File

@ -1,11 +1,12 @@
# Linux menu bitmap
`roboto-16.bin` contains Roboto Regular rasterized at 16 pixels, with 8-bit
`roboto-16.fontatlas` contains Roboto Regular rasterized at 16 pixels, with 4-bit
antialiased coverage. It is embedded into the Linux backend; no font parser,
font discovery, image decoder, or runtime rasterizer is linked into UHDK.
font discovery, image decoder, runtime allocation, or runtime rasterizer is
linked into UHDK. Each glyph is decoded directly while it is drawn.
Coverage: printable ASCII, Latin-1, selected punctuation/currency/arrows, and
U+FFFD. Other codepoints use the replacement glyph. There is no shaping, bidi,
Coverage is printable ASCII. Other codepoints use `?`; broader coverage is
intended to come from optional Unicode font packages. There is no shaping, bidi,
kerning, or combining-mark placement. Larger output scales enlarge the bitmap;
they do not rerasterize the font. This is an intentionally fixed, small menu font.
@ -13,13 +14,17 @@ The source is the unmodified Google Fonts Roboto variable TTF, pinned in
`manifest.json`, with weight 400 and width 100. The generated bitmap is a font
derivative distributed under the accompanying SIL Open Font License (`OFL.txt`).
The TTF is downloaded only for maintainer regeneration and is not shipped here.
The Python generator rasterizes the TTF and writes the packed `.fontatlas`
directly, with no intermediate file format or separate packing tool.
Binary format, little-endian: `UF16`, u32 glyph count, sorted 16-byte records
(u32 codepoint, u32 absolute pixel offset, u8 width/height, i8 x/y bearing relative
to the baseline, u8 advance, three padding bytes), followed by tightly packed,
row-major grayscale glyph bitmaps.
Binary format, little-endian: `FAP1`, u16 glyph count, u16 fallback glyph index,
then sorted 12-byte records (u16 codepoint, u16 absolute data offset, u16 data
size, u8 width/height, i8 x/y bearing relative to the baseline, u8 advance, one
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:
To check the bundled bitmap or regenerate it:
```sh
python3 src/linux/tools/bitmap-font.py --check

View File

@ -18,6 +18,6 @@
"freetype": "2.13.3"
},
"generated": {
"roboto-16.bin": "23bfe858a9ff398b3826d836bb815255ced0e50ac7f695b2d9309a15b32d335e"
"roboto-16.fontatlas": "6fe87564a24392257fc03e48a7044e18b69d07e9a3461be502c8a1f99fefcab3"
}
}

Binary file not shown.

Binary file not shown.

View File

@ -1,89 +1,93 @@
Z_FUNCTION(wl_display_connect)
Z_FUNCTION(wl_display_disconnect)
Z_FUNCTION(wl_display_get_fd)
Z_FUNCTION(wl_display_dispatch_pending)
Z_FUNCTION(wl_display_prepare_read)
Z_FUNCTION(wl_display_read_events)
Z_FUNCTION(wl_display_cancel_read)
Z_FUNCTION(wl_display_flush)
Z_FUNCTION(wl_proxy_marshal_flags)
Z_FUNCTION(wl_proxy_add_listener)
Z_FUNCTION(wl_proxy_destroy)
Z_FUNCTION(wl_proxy_get_version)
Z_FUNCTION(wl_proxy_set_user_data)
Z_FUNCTION(wl_proxy_get_user_data)
Z_FUNCTION(wl_egl_window_create)
Z_FUNCTION(wl_egl_window_destroy)
Z_FUNCTION(wl_egl_window_resize)
Z_FUNCTION(eglGetPlatformDisplay)
Z_FUNCTION(eglInitialize)
Z_FUNCTION(eglTerminate)
Z_FUNCTION(eglBindAPI)
Z_FUNCTION(eglChooseConfig)
Z_FUNCTION(eglCreateContext)
Z_FUNCTION(eglDestroyContext)
Z_FUNCTION(eglCreateWindowSurface)
Z_FUNCTION(eglDestroySurface)
Z_FUNCTION(eglMakeCurrent)
Z_FUNCTION(eglGetCurrentContext)
Z_FUNCTION(eglSwapBuffers)
Z_FUNCTION(eglSwapInterval)
Z_FUNCTION(eglGetProcAddress)
Z_FUNCTION(eglReleaseThread)
Z_FUNCTION(xkb_context_new)
Z_FUNCTION(xkb_context_unref)
Z_FUNCTION(xkb_keymap_new_from_string)
Z_FUNCTION(xkb_keymap_unref)
Z_FUNCTION(xkb_keymap_key_repeats)
Z_FUNCTION(xkb_state_new)
Z_FUNCTION(xkb_state_unref)
Z_FUNCTION(xkb_state_update_mask)
Z_FUNCTION(xkb_state_key_get_one_sym)
Z_FUNCTION(xkb_state_key_get_utf8)
Z_FUNCTION(xkb_state_mod_name_is_active)
Z_FUNCTION(xkb_keysym_to_utf32)
Z_FUNCTION(xkb_compose_table_new_from_locale)
Z_FUNCTION(xkb_compose_table_unref)
Z_FUNCTION(xkb_compose_state_new)
Z_FUNCTION(xkb_compose_state_unref)
Z_FUNCTION(xkb_compose_state_feed)
Z_FUNCTION(xkb_compose_state_reset)
Z_FUNCTION(xkb_compose_state_get_status)
Z_FUNCTION(xkb_compose_state_get_utf8)
Z_FUNCTION(dbus_connection_open_private)
Z_FUNCTION(dbus_connection_set_exit_on_disconnect)
Z_FUNCTION(dbus_connection_close)
Z_FUNCTION(dbus_connection_unref)
Z_FUNCTION(dbus_connection_get_is_connected)
Z_FUNCTION(dbus_connection_get_unix_fd)
Z_FUNCTION(dbus_connection_has_messages_to_send)
Z_FUNCTION(dbus_connection_read_write)
Z_FUNCTION(dbus_connection_pop_message)
Z_FUNCTION(dbus_connection_send)
Z_FUNCTION(dbus_message_new_method_call)
Z_FUNCTION(dbus_message_unref)
Z_FUNCTION(dbus_message_get_type)
Z_FUNCTION(dbus_message_get_reply_serial)
Z_FUNCTION(dbus_message_get_path)
Z_FUNCTION(dbus_message_get_sender)
Z_FUNCTION(dbus_message_get_error_name)
Z_FUNCTION(dbus_message_is_signal)
Z_FUNCTION(dbus_message_has_signature)
Z_FUNCTION(dbus_message_set_no_reply)
Z_FUNCTION(dbus_message_iter_init)
Z_FUNCTION(dbus_message_iter_init_append)
Z_FUNCTION(dbus_message_iter_get_arg_type)
Z_FUNCTION(dbus_message_iter_next)
Z_FUNCTION(dbus_message_iter_recurse)
Z_FUNCTION(dbus_message_iter_get_basic)
Z_FUNCTION(dbus_message_iter_append_basic)
Z_FUNCTION(dbus_message_iter_open_container)
Z_FUNCTION(dbus_message_iter_close_container)
Z_FUNCTION(dbus_message_iter_abandon_container_if_open)
Z_FUNCTION(dbus_threads_init_default)
Z_FUNCTION(dbus_message_new_method_return)
Z_FUNCTION(dbus_message_new_error)
Z_FUNCTION(dbus_message_new_signal)
Z_FUNCTION(dbus_message_get_interface)
Z_FUNCTION(dbus_message_get_member)
Z_FUNCTION(dbus_message_get_no_reply)
Z_REQUIRED(wl_display_connect)
Z_REQUIRED(wl_display_disconnect)
Z_REQUIRED(wl_display_get_fd)
Z_REQUIRED(wl_display_dispatch_pending)
Z_REQUIRED(wl_display_prepare_read)
Z_REQUIRED(wl_display_read_events)
Z_REQUIRED(wl_display_cancel_read)
Z_REQUIRED(wl_display_flush)
Z_REQUIRED(wl_proxy_marshal_flags)
Z_REQUIRED(wl_proxy_add_listener)
Z_REQUIRED(wl_proxy_destroy)
Z_REQUIRED(wl_proxy_get_version)
Z_REQUIRED(wl_proxy_set_user_data)
Z_REQUIRED(wl_proxy_get_user_data)
Z_OPTIONAL(wayland_egl, have_egl, wl_egl_window_create)
Z_OPTIONAL(wayland_egl, have_egl, wl_egl_window_destroy)
Z_OPTIONAL(wayland_egl, have_egl, wl_egl_window_resize)
Z_OPTIONAL(egl, have_egl, eglGetPlatformDisplay)
Z_OPTIONAL(egl, have_egl, eglInitialize)
Z_OPTIONAL(egl, have_egl, eglTerminate)
Z_OPTIONAL(egl, have_egl, eglBindAPI)
Z_OPTIONAL(egl, have_egl, eglChooseConfig)
Z_OPTIONAL(egl, have_egl, eglCreateContext)
Z_OPTIONAL(egl, have_egl, eglDestroyContext)
Z_OPTIONAL(egl, have_egl, eglCreateWindowSurface)
Z_OPTIONAL(egl, have_egl, eglDestroySurface)
Z_OPTIONAL(egl, have_egl, eglMakeCurrent)
Z_OPTIONAL(egl, have_egl, eglGetCurrentContext)
Z_OPTIONAL(egl, have_egl, eglSwapBuffers)
Z_OPTIONAL(egl, have_egl, eglSwapInterval)
Z_OPTIONAL(egl, have_egl, eglGetProcAddress)
Z_OPTIONAL(egl, have_egl, eglReleaseThread)
Z_OPTIONAL(xkb, have_xkb, xkb_context_new)
Z_OPTIONAL(xkb, have_xkb, xkb_context_unref)
Z_OPTIONAL(xkb, have_xkb, xkb_keymap_new_from_string)
Z_OPTIONAL(xkb, have_xkb, xkb_keymap_unref)
Z_OPTIONAL(xkb, have_xkb, xkb_keymap_key_repeats)
Z_OPTIONAL(xkb, have_xkb, xkb_state_new)
Z_OPTIONAL(xkb, have_xkb, xkb_state_unref)
Z_OPTIONAL(xkb, have_xkb, xkb_state_update_mask)
Z_OPTIONAL(xkb, have_xkb, xkb_state_key_get_one_sym)
Z_OPTIONAL(xkb, have_xkb, xkb_state_key_get_utf8)
Z_OPTIONAL(xkb, have_xkb, xkb_state_mod_name_is_active)
Z_OPTIONAL(xkb, have_xkb, xkb_keysym_to_utf32)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_table_new_from_locale)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_table_unref)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_state_new)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_state_unref)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_state_feed)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_state_reset)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_state_get_status)
Z_OPTIONAL(xkb, have_xkb, xkb_compose_state_get_utf8)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_open_private)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_set_exit_on_disconnect)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_close)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_unref)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_get_is_connected)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_get_unix_fd)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_has_messages_to_send)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_read_write)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_pop_message)
Z_OPTIONAL(dbus, have_dbus, dbus_connection_send)
Z_OPTIONAL(dbus, have_dbus, dbus_message_new_method_call)
Z_OPTIONAL(dbus, have_dbus, dbus_message_unref)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_type)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_reply_serial)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_path)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_sender)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_error_name)
Z_OPTIONAL(dbus, have_dbus, dbus_message_is_signal)
Z_OPTIONAL(dbus, have_dbus, dbus_message_has_signature)
Z_OPTIONAL(dbus, have_dbus, dbus_message_set_no_reply)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_init)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_init_append)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_get_arg_type)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_next)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_recurse)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_get_basic)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_append_basic)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_open_container)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_close_container)
Z_OPTIONAL(dbus, have_dbus, dbus_message_iter_abandon_container_if_open)
Z_OPTIONAL(dbus, have_dbus, dbus_threads_init_default)
Z_OPTIONAL(dbus, have_dbus, dbus_message_new_method_return)
Z_OPTIONAL(dbus, have_dbus, dbus_message_new_error)
Z_OPTIONAL(dbus, have_dbus, dbus_message_new_signal)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_interface)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_member)
Z_OPTIONAL(dbus, have_dbus, dbus_message_get_no_reply)

View File

@ -6,8 +6,6 @@
#include <pthread.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <unistd.h>
#include "wayland-client-core.h"
@ -21,9 +19,11 @@
#include <dbus/dbus.h>
#include "dbus-imports.h"
#include "function-pointers.h"
#define Z_FUNCTION(name) __typeof__(name) *z_##name;
#define Z_REQUIRED(name) __typeof__(name) *z_##name;
#define Z_OPTIONAL(library, available, name) __typeof__(name) *z_##name;
#include "functions.inc"
#undef Z_FUNCTION
#undef Z_OPTIONAL
#undef Z_REQUIRED
static void *wayland, *wayland_egl, *egl, *xkb, *dbus;
static int have_egl, have_xkb, have_dbus;
@ -59,9 +59,11 @@ void z_linux_libraries_close(void) {
if (wayland)
dlclose(wayland);
wayland = wayland_egl = egl = NULL;
#define Z_FUNCTION(name) z_##name = NULL;
#define Z_REQUIRED(name) z_##name = NULL;
#define Z_OPTIONAL(library, available, name) z_##name = NULL;
#include "functions.inc"
#undef Z_FUNCTION
#undef Z_OPTIONAL
#undef Z_REQUIRED
}
int z_linux_libraries_open(void) {
@ -75,34 +77,24 @@ int z_linux_libraries_open(void) {
have_xkb = xkb != NULL;
dbus = open_library("libdbus-1.so.3");
have_dbus = dbus != NULL;
#define Z_FUNCTION(name) \
#define Z_REQUIRED(name) \
do { \
const char *symbol = #name; \
int bus = strncmp(symbol, "dbus_", 5) == 0; \
int keyboard = strncmp(symbol, "xkb_", 4) == 0; \
int graphics = strncmp(symbol, "egl", 3) == 0 || strncmp(symbol, "wl_egl_", 7) == 0; \
void *library = \
bus ? dbus \
: keyboard \
? xkb \
: (strncmp(symbol, "egl", 3) == 0 ? egl : (graphics ? wayland_egl : wayland)); \
if (library) \
z_##name = (__typeof__(z_##name))dlsym(library, symbol); \
z_##name = (__typeof__(z_##name))dlsym(wayland, #name); \
if (!z_##name) { \
if (bus) \
have_dbus = 0; \
else if (keyboard) \
have_xkb = 0; \
else if (graphics) \
have_egl = 0; \
else { \
z_linux_libraries_close(); \
return 0; \
} \
z_linux_libraries_close(); \
return 0; \
} \
} while (0);
#define Z_OPTIONAL(library, available, name) \
do { \
if (library) \
z_##name = (__typeof__(z_##name))dlsym(library, #name); \
if (!z_##name) \
available = 0; \
} while (0);
#include "functions.inc"
#undef Z_FUNCTION
#undef Z_OPTIONAL
#undef Z_REQUIRED
return 1;
}
@ -112,10 +104,6 @@ int z_linux_egl_available(void) {
int z_linux_errno(void) {
return errno;
}
int z_linux_is_main_thread(void) {
return syscall(SYS_gettid) == getpid();
}
/* Keep libc's optimization/fortify inline implementation on the C side. */
int z_linux_poll(struct pollfd *fds, nfds_t count, int timeout) {
return poll(fds, count, timeout);

View File

@ -1,5 +1,5 @@
//! Wayland platform owner. Protocol dispatch and native commands stay on the OS
//! thread; the application thread holds each window's lock only while rendering.
//! thread; session boundaries release GL ownership before native dispatch.
const std = @import("std");
const c = @import("linux_c");
const n = @import("native");
@ -11,6 +11,7 @@ const Input = @import("Input.zig");
const Desktop = @import("Desktop.zig");
const WindowState = @import("WindowState.zig");
const Portal = @import("Portal.zig");
const Tray = @import("Tray.zig");
const Watch = @import("Watch.zig");
const Data = @import("Data.zig");
const Popup = @import("Popup.zig");
@ -48,6 +49,7 @@ pub const Window = struct {
observation: WindowState.Observation = .{},
wm_caps: WindowState.Capabilities = .{},
flags: u32,
style: n.uhdk_window_style,
cursor: u32 = n.UHDK_CURSOR_ARROW,
text: Text.State = .{},
menu_override: ?*@import("../Resource.zig") = null,
@ -72,6 +74,7 @@ pub const Backend = struct {
data: Data.State = .{},
watches: ?*Watch.Watch = null,
portal: Portal.State = .{},
tray: Tray.State = .{},
desktop: Desktop.State = .{},
menus: KdeAppMenu.State = .{},
popup: Popup.State = .{},
@ -79,16 +82,20 @@ pub const Backend = struct {
running: bool = true,
failed: std.atomic.Value(bool) = .init(false),
};
pub var instance: ?*Backend = null;
var wake_fd: std.atomic.Value(c_int) = .init(-1);
pub fn backend(handle: ?*n.uhdk_app) u32 {
pub fn backend(handle: ?*n.uhdk_session) u32 {
if (handle == null) return n.UHDK_BACKEND_AUTO;
const app = runtime.fromAppHandle(handle);
return if (app.has_run) n.UHDK_BACKEND_WAYLAND else n.UHDK_BACKEND_AUTO;
return if (app.native_started) n.UHDK_BACKEND_WAYLAND else n.UHDK_BACKEND_AUTO;
}
pub fn capability(handle: ?*n.uhdk_app, cap: u32) n.uhdk_bool {
pub fn capability(handle: ?*n.uhdk_session, cap: u32) n.uhdk_bool {
if (handle == null) return 0;
const b = instance orelse return 0;
if (b.app != runtime.fromAppHandle(handle) or !b.app.running or b.failed.load(.acquire)) return 0;
return @intFromBool(cap < 32 and b.capabilities.load(.acquire) & (@as(u32, 1) << @intCast(cap)) != 0);
@ -100,68 +107,85 @@ pub fn setCapability(cap: u32, available: bool) void {
}
export fn z_native_is_main_thread() c_int {
return c.z_linux_is_main_thread();
// Wayland connections are thread-affine, but do not require the process's
// initial thread. The first session records and enforces its owner thread.
return 1;
}
export fn z_native_start(handle: ?*n.uhdk_app, _: n.uhdk_text) u32 {
export fn z_native_start(handle: ?*n.uhdk_session, _: n.uhdk_text) u32 {
const app = runtime.fromAppHandle(handle);
if (c.z_linux_libraries_open() == 0) return abi.UNAVAILABLE;
const b = app.gpa.create(Backend) catch {
c.z_linux_libraries_close();
return abi.OOM;
};
b.* = .{ .app = app };
instance = b;
Input.initialize();
const fd = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
if (fd < 0) {
z_native_finish();
return n.UHDK_STATUS_OS_ERROR;
}
wake_fd.store(fd, .release);
b.display = c.z_wl_display_connect.?(null);
if (b.display == null) {
z_native_finish();
return abi.UNAVAILABLE;
}
b.registry = c.wl_display_get_registry(b.display);
if (b.registry == null) {
z_native_finish();
return abi.OOM;
}
if (c.wl_registry_add_listener(b.registry, &registry_listener, b) != 0 or !initialRegistry(b)) {
z_native_finish();
return n.UHDK_STATUS_OS_ERROR;
}
if (b.compositor == null or b.shell == null) {
z_native_finish();
return n.UHDK_STATUS_UNSUPPORTED;
}
Input.setup();
if (!initialRegistry(b)) {
z_native_finish();
return n.UHDK_STATUS_OS_ERROR;
}
Desktop.initialize();
Portal.initialize();
Egl.initialize(b);
setCapability(n.UHDK_CAP_OPENGL, b.egl_display != null);
return abi.OK;
}
// Startup also uses a bounded read/flush/poll handshake: an unresponsive
// compositor must not trap app_run before the application thread even starts.
// compositor must not trap uhdk_open before returning a session.
fn initialRegistry(b: *Backend) bool {
var done = false;
const callback = c.wl_display_sync(b.display) orelse return false;
defer c.wl_callback_destroy(callback);
const listener: c.struct_wl_callback_listener = .{ .done = registryDone };
if (c.wl_callback_add_listener(callback, &listener, &done) != 0) return false;
const deadline = runtime.now(b.app.io) + 5 * std.time.ns_per_s;
while (!done) {
if (c.z_wl_display_dispatch_pending.?(b.display) < 0) return false;
if (done) return true;
const now = runtime.now(b.app.io);
if (now >= deadline) return false;
if (c.z_wl_display_prepare_read.?(b.display) != 0) continue;
var events: c_short = c.POLLIN;
if (c.z_wl_display_flush.?(b.display) < 0) {
if (c.z_linux_errno() == c.EAGAIN) events |= c.POLLOUT else {
@ -169,6 +193,7 @@ fn initialRegistry(b: *Backend) bool {
return false;
}
}
var fd: c.struct_pollfd = .{ .fd = c.z_wl_display_get_fd.?(b.display), .events = events, .revents = 0 };
const ready = c.z_linux_poll(&fd, 1, @intCast(@min(5000, (deadline - now + std.time.ns_per_ms - 1) / std.time.ns_per_ms)));
if (ready > 0 and fd.revents & c.POLLIN != 0) {
@ -177,12 +202,15 @@ fn initialRegistry(b: *Backend) bool {
if (ready < 0 and c.z_linux_errno() != c.EINTR) return false;
if (fd.revents & (c.POLLHUP | c.POLLERR | c.POLLNVAL) != 0) return false;
}
return true;
}
fn registryDone(data: ?*anyopaque, _: ?*c.struct_wl_callback, _: u32) callconv(.c) void {
const done: *bool = @ptrCast(@alignCast(data.?));
done.* = true;
}
export fn z_native_finish() void {
const b = instance orelse return;
std.debug.assert(b.windows == null);
@ -201,56 +229,65 @@ export fn z_native_finish() void {
if (b.compositor != null) c.wl_compositor_destroy(b.compositor);
if (b.registry != null) c.wl_registry_destroy(b.registry);
if (b.display != null) c.z_wl_display_disconnect.?(b.display);
const fd = wake_fd.swap(-1, .acq_rel);
if (fd >= 0) _ = c.close(fd);
const gpa = b.app.gpa;
instance = null;
gpa.destroy(b);
c.z_linux_libraries_close();
}
export fn z_native_wake() void {
const fd = wake_fd.load(.acquire);
if (fd < 0) return;
const one: u64 = 1;
while (c.z_linux_write(fd, &one, @sizeOf(u64)) < 0) {
if (c.z_linux_errno() != c.EINTR) break; // EAGAIN already means readable.
}
}
export fn z_native_again() void {
z_native_wake();
}
export fn z_native_stop() void {
if (instance) |b| b.running = false;
}
export fn z_native_pool_push() ?*anyopaque {
return null;
}
export fn z_native_pool_pop(_: ?*anyopaque) void {}
fn fail(b: *Backend) void {
if (b.failed.swap(true, .acq_rel)) return;
b.app.lock();
b.app.stopping = true;
b.app.native_error = n.UHDK_STATUS_OS_ERROR;
b.app.notify();
b.app.unlock();
Popup.deinit();
runtime.simpleEvent(b.app, n.UHDK_EVENT_QUIT_REQUESTED);
}
export fn z_native_run() void {
const b = instance.?;
export fn z_native_pump(timeout_ns: u64) void {
const b = instance orelse return;
var fds: std.ArrayList(c.struct_pollfd) = .empty;
defer fds.deinit(b.app.gpa);
while (b.running) {
pump: {
if (!b.failed.load(.acquire) and c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b);
n.z_tick(runtime.toAppHandle(b.app));
n.z_dispatch(runtime.toAppHandle(b.app));
var cursor = b.windows;
var timeout: c_int = Input.tick();
Watch.tick();
const popup_timeout = Popup.tick();
if (popup_timeout >= 0) timeout = if (timeout < 0) popup_timeout else @min(timeout, popup_timeout);
const desktop_timeout = Desktop.tick();
if (desktop_timeout >= 0) timeout = if (timeout < 0) desktop_timeout else @min(timeout, desktop_timeout);
const portal_timeout = Portal.tick();
if (portal_timeout >= 0) timeout = if (timeout < 0) portal_timeout else @min(timeout, portal_timeout);
const tray_timeout = Tray.tick();
if (tray_timeout >= 0) timeout = if (timeout < 0) tray_timeout else @min(timeout, tray_timeout);
const data_timeout = Data.tick();
if (data_timeout >= 0) timeout = if (timeout < 0) data_timeout else @min(timeout, data_timeout);
while (cursor) |w| {
@ -262,22 +299,26 @@ export fn z_native_run() void {
continue;
}
}
if (!b.failed.load(.acquire)) apply(w);
}
if (!b.running) break;
if (!b.running) return;
var reading = false;
var display_events: c_short = c.POLLIN;
if (!b.failed.load(.acquire)) {
if (c.z_wl_display_prepare_read.?(b.display) != 0) continue;
if (c.z_wl_display_prepare_read.?(b.display) != 0) break :pump;
reading = true;
if (c.z_wl_display_flush.?(b.display) < 0) {
if (c.z_linux_errno() == c.EAGAIN) display_events |= c.POLLOUT else {
c.z_wl_display_cancel_read.?(b.display);
fail(b);
continue;
break :pump;
}
}
}
fds.clearRetainingCapacity();
fds.appendSlice(b.app.gpa, &.{
.{ .fd = if (reading) c.z_wl_display_get_fd.?(b.display) else -1, .events = display_events, .revents = 0 },
@ -285,29 +326,49 @@ export fn z_native_run() void {
}) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b);
continue;
break :pump;
};
Data.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b);
continue;
break :pump;
};
Watch.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b);
continue;
break :pump;
};
Tray.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b);
break :pump;
};
Portal.poll(&fds) catch {
if (reading) c.z_wl_display_cancel_read.?(b.display);
fail(b);
continue;
break :pump;
};
b.app.lock();
const queued = (b.app.pending_head != null or b.app.native_error != abi.OK);
b.app.unlock();
const wait_ns: u64 = if (queued) 0 else timeout_ns;
const budget: c_int = if (wait_ns == std.math.maxInt(u64)) -1 else @intCast(@min(std.math.maxInt(c_int), wait_ns / std.time.ns_per_ms + @intFromBool(wait_ns % std.time.ns_per_ms != 0)));
if (budget >= 0) timeout = if (timeout < 0) budget else @min(timeout, budget);
const ready = c.z_linux_poll(fds.items.ptr, fds.items.len, timeout);
if (reading) {
if (ready > 0 and fds.items[0].revents & c.POLLIN != 0) {
if (c.z_wl_display_read_events.?(b.display) < 0) fail(b);
if (c.z_wl_display_read_events.?(b.display) < 0 or
c.z_wl_display_dispatch_pending.?(b.display) < 0) fail(b);
} else c.z_wl_display_cancel_read.?(b.display);
}
if (ready < 0 and c.z_linux_errno() != c.EINTR) fail(b);
if (fds.items[0].revents & (c.POLLERR | c.POLLHUP | c.POLLNVAL) != 0) fail(b);
if (fds.items[1].revents & c.POLLIN != 0) {
@ -339,54 +400,68 @@ fn registryGlobal(data: ?*anyopaque, registry: ?*c.struct_wl_registry, name: u32
b.fractional = @ptrCast(c.wl_registry_bind(registry, name, &c.z_uhdk_wp_fractional_scale_manager_v1_interface, 1));
}
}
fn registryRemove(_: ?*anyopaque, _: ?*c.struct_wl_registry, name: u32) callconv(.c) void {
Input.remove(name);
KdeAppMenu.remove(name);
}
const registry_listener: c.struct_wl_registry_listener = .{ .global = registryGlobal, .global_remove = registryRemove };
fn ping(_: ?*anyopaque, shell: ?*c.struct_xdg_wm_base, serial: u32) callconv(.c) void {
c.xdg_wm_base_pong(shell, serial);
}
const shell_listener: c.struct_xdg_wm_base_listener = .{ .ping = ping };
fn window(data: ?*anyopaque) *Window {
return @ptrCast(@alignCast(data.?));
}
fn configure(data: ?*anyopaque, _: ?*c.struct_xdg_surface, serial: u32) callconv(.c) void {
const w = window(data);
w.serial = serial;
w.dirty = true;
}
const surface_listener: c.struct_xdg_surface_listener = .{ .configure = configure };
fn topConfigure(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel, width: i32, height: i32, states: [*c]c.struct_wl_array) callconv(.c) void {
const w = window(data);
if (width > 0) w.width = width;
if (height > 0) w.height = height;
const values: []const u32 = if (states.*.size == 0) &.{} else @as([*]const u32, @ptrCast(@alignCast(states.*.data)))[0 .. states.*.size / @sizeOf(u32)];
w.observation = WindowState.observe(c.xdg_toplevel_get_version(w.top), values);
w.focused = w.observation.focused;
if (!w.focused) Input.release(w, n.UHDK_CYCLE_FOCUS_LOST);
w.state = w.observation.geometry;
}
fn emit(w: *Window, kind: u32) void {
var event = std.mem.zeroes(n.z_event);
event.type = kind;
event.window = w.handle;
n.z_emit(runtime.toAppHandle(w.owner), &event);
}
fn topClose(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel) callconv(.c) void {
emit(window(data), n.UHDK_EVENT_WINDOW_CLOSE_REQUESTED);
}
fn bounds(_: ?*anyopaque, _: ?*c.struct_xdg_toplevel, _: i32, _: i32) callconv(.c) void {}
fn wmCaps(data: ?*anyopaque, _: ?*c.struct_xdg_toplevel, caps: [*c]c.struct_wl_array) callconv(.c) void {
const values: []const u32 = if (caps.*.size == 0) &.{} else @as([*]const u32, @ptrCast(@alignCast(caps.*.data)))[0 .. caps.*.size / @sizeOf(u32)];
window(data).wm_caps = WindowState.Capabilities.announced(values);
}
const top_listener: c.struct_xdg_toplevel_listener = .{ .configure = topConfigure, .close = topClose, .configure_bounds = bounds, .wm_capabilities = wmCaps };
fn decorationConfigure(data: ?*anyopaque, _: ?*c.struct_zxdg_toplevel_decoration_v1, mode: u32) callconv(.c) void {
const w = window(data);
// Until the client-decoration adapter exists, don't silently create a
// decorated window with no title bar on compositors that decline SSD.
if (mode != c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE and w.request != 0) completeCreation(w, n.UHDK_STATUS_UNSUPPORTED);
if (mode != c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE and w.style.decorated != 0 and w.request != 0) completeCreation(w, n.UHDK_STATUS_UNSUPPORTED);
}
const decoration_listener: c.struct_zxdg_toplevel_decoration_v1_listener = .{ .configure = decorationConfigure };
fn fraction(data: ?*anyopaque, _: ?*c.struct_wp_fractional_scale_v1, scale: u32) callconv(.c) void {
const w = window(data);
@ -394,8 +469,10 @@ fn fraction(data: ?*anyopaque, _: ?*c.struct_wp_fractional_scale_v1, scale: u32)
w.scale = scale;
w.dirty = true;
}
const fraction_listener: c.struct_wp_fractional_scale_v1_listener = .{ .preferred_scale = fraction };
fn enter(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: ?*c.struct_wl_output) callconv(.c) void {}
fn bufferScale(data: ?*anyopaque, _: ?*c.struct_wl_surface, scale: i32) callconv(.c) void {
const w = window(data);
if (w.fractional == null and scale > 0 and scale <= 16) {
@ -403,6 +480,7 @@ fn bufferScale(data: ?*anyopaque, _: ?*c.struct_wl_surface, scale: i32) callconv
w.dirty = true;
}
}
fn bufferTransform(_: ?*anyopaque, _: ?*c.struct_wl_surface, _: u32) callconv(.c) void {}
const wl_surface_listener: c.struct_wl_surface_listener = .{ .enter = enter, .leave = enter, .preferred_buffer_scale = bufferScale, .preferred_buffer_transform = bufferTransform };
@ -410,18 +488,19 @@ fn completeCreation(w: *Window, status: u32) void {
const id = w.request;
if (id == 0) return;
w.request = 0;
const app = runtime.toAppHandle(w.owner);
var result = std.mem.zeroes(n.z_request_result);
result.value.window = w.handle;
if (status != abi.OK) {
n.z_object_set_native(w.handle, null);
destroyWindow(w);
}
n.z_complete(app, id, status, &result);
n.z_complete(app, id, status, null);
}
fn apply(w: *Window) void {
if (!w.dirty or !w.mutex.tryLock()) return;
// Never block the display dispatcher behind eglSwapBuffers, which itself
// may be waiting for the dispatcher. end_frame wakes us to retry.
if (w.serial) |serial| {
@ -429,10 +508,12 @@ fn apply(w: *Window) void {
w.serial = null;
w.configured = true;
}
if (!w.configured) {
w.mutex.unlock(w.owner.io);
return;
}
const width = @min(w.width, 65536);
const height = @min(w.height, 65536);
const pixel_width: u32 = @intCast(@divTrunc(@as(i64, width) * w.scale + 119, 120));
@ -449,8 +530,10 @@ fn apply(w: *Window) void {
c.wl_surface_commit(w.surface);
w.configured = false;
}
w.visible = w.want_visible;
w.metrics = .{ .struct_size = @sizeOf(n.uhdk_window_metrics), .framebuffer_width = pixel_width, .framebuffer_height = pixel_height, .logical_size = .{ .width = @floatFromInt(width), .height = @floatFromInt(height) }, .scale = @as(f32, @floatFromInt(w.scale)) / 120, .state = w.state, .focused = @intFromBool(w.focused), .visible = @intFromBool(w.visible), .observations = w.observation.known, .resizing = @intFromBool(w.observation.resizing), .suspended = @intFromBool(w.observation.suspended), .minimized = 0, .occluded = 0 };
const metrics = w.metrics;
w.dirty = false;
w.mutex.unlock(w.owner.io);
@ -461,33 +544,41 @@ fn apply(w: *Window) void {
fn createWindow(b: *Backend, command: *const n.z_command, id: u64) u32 {
const desc = command.window;
if (desc.flags & n.UHDK_WINDOW_DECORATED != 0 and b.decorations == null) return n.UHDK_STATUS_UNSUPPORTED;
if (desc.style.decorated != 0 and b.decorations == null) return n.UHDK_STATUS_UNSUPPORTED;
const w = b.app.gpa.create(Window) catch return abi.OOM;
w.* = .{ .owner = b.app, .handle = @ptrCast(command.target), .width = @intFromFloat(@max(1, desc.content_size.width)), .height = @intFromFloat(@max(1, desc.content_size.height)), .min_width = @intFromFloat(desc.min_size.width), .min_height = @intFromFloat(desc.min_size.height), .max_width = @intFromFloat(desc.max_size.width), .max_height = @intFromFloat(desc.max_size.height), .flags = desc.flags };
w.* = .{ .owner = b.app, .handle = @ptrCast(command.target), .width = @intFromFloat(@max(1, desc.content_size.width)), .height = @intFromFloat(@max(1, desc.content_size.height)), .min_width = @intFromFloat(desc.min_size.width), .min_height = @intFromFloat(desc.min_size.height), .max_width = @intFromFloat(desc.max_size.width), .max_height = @intFromFloat(desc.max_size.height), .flags = desc.flags, .style = desc.style };
w.next = b.windows;
b.windows = w;
const status = setupWindow(b, w, desc);
if (status != abi.OK) {
destroyWindow(w);
return status;
}
n.z_object_set_native(command.target, w);
w.request = id;
w.deadline = runtime.now(b.app.io) + 5 * std.time.ns_per_s;
c.wl_surface_commit(w.surface); // Empty initial commit; wait for configure.
return n.Z_DEFERRED;
}
fn setupWindow(b: *Backend, w: *Window, desc: n.uhdk_window_desc) u32 {
const title = b.app.gpa.dupeZ(u8, abi.textBytes(desc.title)) catch return abi.OOM;
fn setupWindow(b: *Backend, w: *Window, desc: n.z_window_desc) u32 {
const title = b.app.gpa.dupeSentinel(u8, abi.textBytes(desc.title), 0) catch return abi.OOM;
defer b.app.gpa.free(title);
const app_id = b.app.gpa.dupeZ(u8, b.app.application_id) catch return abi.OOM;
const app_id = b.app.gpa.dupeSentinel(u8, b.app.application_id, 0) catch return abi.OOM;
defer b.app.gpa.free(app_id);
w.surface = c.wl_compositor_create_surface(b.compositor) orelse return abi.OOM;
if (c.wl_surface_add_listener(w.surface, &wl_surface_listener, w) != 0) return abi.OOM;
w.xdg = c.xdg_wm_base_get_xdg_surface(b.shell, w.surface) orelse return abi.OOM;
if (c.xdg_surface_add_listener(w.xdg, &surface_listener, w) != 0) return abi.OOM;
w.top = c.xdg_surface_get_toplevel(w.xdg) orelse return abi.OOM;
if (c.xdg_toplevel_add_listener(w.top, &top_listener, w) != 0) return abi.OOM;
c.xdg_toplevel_set_title(w.top, title);
c.xdg_toplevel_set_app_id(w.top, app_id);
Desktop.applyIcon(w);
@ -496,33 +587,61 @@ fn setupWindow(b: *Backend, w: *Window, desc: n.uhdk_window_desc) u32 {
const p: *Window = @ptrCast(@alignCast(n.z_object_native(parent) orelse return abi.UNAVAILABLE));
c.xdg_toplevel_set_parent(w.top, p.top);
}
if (w.flags & n.UHDK_WINDOW_RESIZABLE == 0) {
w.min_width = w.width;
w.min_height = w.height;
w.max_width = w.width;
w.max_height = w.height;
}
if (w.flags & n.UHDK_WINDOW_RESIZABLE != 0) {
if (w.style.resizable != 0) {
w.width = std.math.clamp(w.width, @max(1, w.min_width), if (w.max_width == 0) 65536 else w.max_width);
w.height = std.math.clamp(w.height, @max(1, w.min_height), if (w.max_height == 0) 65536 else w.max_height);
}
setLimits(w);
if (w.flags & n.UHDK_WINDOW_DECORATED != 0) {
if (w.style.decorated != 0) {
w.decoration = c.zxdg_decoration_manager_v1_get_toplevel_decoration(b.decorations, w.top) orelse return abi.OOM;
if (c.zxdg_toplevel_decoration_v1_add_listener(w.decoration, &decoration_listener, w) != 0) return abi.OOM;
c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
}
if (b.fractional != null and b.viewporter != null) {
w.viewport = c.wp_viewporter_get_viewport(b.viewporter, w.surface) orelse return abi.OOM;
w.fractional = c.wp_fractional_scale_manager_v1_get_fractional_scale(b.fractional, w.surface) orelse return abi.OOM;
if (c.wp_fractional_scale_v1_add_listener(w.fractional, &fraction_listener, w) != 0) return abi.OOM;
}
return abi.OK;
}
fn setLimits(w: *Window) void {
c.xdg_toplevel_set_min_size(w.top, w.min_width, w.min_height);
c.xdg_toplevel_set_max_size(w.top, w.max_width, w.max_height);
if (w.style.resizable != 0) {
c.xdg_toplevel_set_min_size(w.top, w.min_width, w.min_height);
c.xdg_toplevel_set_max_size(w.top, w.max_width, w.max_height);
} else {
c.xdg_toplevel_set_min_size(w.top, w.width, w.height);
c.xdg_toplevel_set_max_size(w.top, w.width, w.height);
}
}
fn setStyle(b: *Backend, w: *Window, style: n.uhdk_window_style) u32 {
if (style.decorated != 0) {
if (b.decorations == null) return n.UHDK_STATUS_UNSUPPORTED;
if (w.decoration == null) {
w.decoration = c.zxdg_decoration_manager_v1_get_toplevel_decoration(b.decorations, w.top) orelse return abi.OOM;
if (c.zxdg_toplevel_decoration_v1_add_listener(w.decoration, &decoration_listener, w) != 0) {
c.zxdg_toplevel_decoration_v1_destroy(w.decoration);
w.decoration = null;
return abi.OOM;
}
}
c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
} else if (w.decoration != null) {
c.zxdg_toplevel_decoration_v1_set_mode(w.decoration, c.ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE);
}
w.style = style;
setLimits(w);
return abi.OK;
}
fn destroyWindow(w: *Window) void {
const b = instance.?;
std.debug.assert(w.egl == null);
@ -532,14 +651,17 @@ fn destroyWindow(w: *Window) void {
Data.forget(w);
Input.forget(w);
Text.deinit(w);
var link = &b.windows;
while (link.*) |item| {
if (item == w) {
link.* = item.next;
break;
}
link = &item.next;
}
if (w.fractional != null) c.wp_fractional_scale_v1_destroy(w.fractional);
if (w.viewport != null) c.wp_viewport_destroy(w.viewport);
if (w.decoration != null) c.zxdg_toplevel_decoration_v1_destroy(w.decoration);
@ -548,7 +670,8 @@ fn destroyWindow(w: *Window) void {
if (w.surface != null) c.wl_surface_destroy(w.surface);
w.owner.gpa.destroy(w);
}
export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64, result: [*c]n.z_request_result) u32 {
export fn z_native_execute(_: ?*n.uhdk_session, raw: [*c]const n.z_command, id: u64, _: [*c]n.z_request_result) u32 {
const b = instance.?;
const cmd: *const n.z_command = &raw.*;
if (cmd.op == n.Z_DESTROY) {
@ -556,8 +679,10 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
z_native_destroy(n.z_object_kind(cmd.target), ptr);
n.z_object_set_native(cmd.target, null);
}
return abi.OK;
}
if (b.failed.load(.acquire)) return abi.UNAVAILABLE;
if (cmd.op == n.Z_WINDOW) return createWindow(b, cmd, id);
if (cmd.op == n.Z_APP_MENU) return KdeAppMenu.attach(null, cmd.other);
@ -565,41 +690,40 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
Popup.flags();
return KdeAppMenu.updateFlags();
}
if (cmd.op == n.Z_POPUP) return Popup.request(cmd, id);
if (cmd.op == n.Z_ICON) return Desktop.setIcon(cmd.image);
if (cmd.op == n.Z_DIALOG or cmd.op == n.Z_URL) return Portal.request(cmd, id);
if (cmd.op == n.Z_WATCH) return Watch.create(cmd, &result.*);
if (cmd.op == n.Z_CLIP_WRITE) return Data.write(cmd.text);
if (cmd.op == n.Z_CLIP_READ) return Data.read(id, cmd.limit);
const ptr = if (cmd.target != null) n.z_object_native(cmd.target) else null;
const w: *Window = if (ptr) |p| @ptrCast(@alignCast(p)) else return n.UHDK_STATUS_UNSUPPORTED;
switch (cmd.op) {
n.Z_WINDOW_MENU => return KdeAppMenu.attach(w, cmd.other),
n.Z_TITLE => {
const title = b.app.gpa.dupeZ(u8, abi.textBytes(cmd.text)) catch return abi.OOM;
const title = b.app.gpa.dupeSentinel(u8, abi.textBytes(cmd.text), 0) catch return abi.OOM;
defer b.app.gpa.free(title);
c.xdg_toplevel_set_title(w.top, title);
},
n.Z_SIZE => {
if (w.state != n.UHDK_WINDOW_NORMAL) return abi.UNAVAILABLE;
w.width = @intFromFloat(@max(1, cmd.size.width));
w.height = @intFromFloat(@max(1, cmd.size.height));
if (w.flags & n.UHDK_WINDOW_RESIZABLE != 0) {
if (w.style.resizable != 0) {
w.width = std.math.clamp(w.width, @max(1, w.min_width), if (w.max_width == 0) 65536 else w.max_width);
w.height = std.math.clamp(w.height, @max(1, w.min_height), if (w.max_height == 0) 65536 else w.max_height);
}
if (w.flags & n.UHDK_WINDOW_RESIZABLE == 0) {
w.min_width = w.width;
w.max_width = w.width;
w.min_height = w.height;
w.max_height = w.height;
setLimits(w);
}
if (w.style.resizable == 0) setLimits(w);
w.dirty = true;
},
n.Z_STATE => switch (cmd.number) {
n.UHDK_WINDOW_MINIMIZED => {
if (!w.wm_caps.minimize) return n.UHDK_STATUS_UNSUPPORTED;
Input.release(w, n.UHDK_CYCLE_HIDDEN);
c.xdg_toplevel_set_minimized(w.top);
},
n.UHDK_WINDOW_MAXIMIZED => {
@ -609,6 +733,7 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
},
n.UHDK_WINDOW_FULLSCREEN => {
if (!w.wm_caps.fullscreen) return n.UHDK_STATUS_UNSUPPORTED;
c.xdg_toplevel_set_fullscreen(w.top, null);
},
else => {
@ -619,28 +744,35 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
n.Z_VISIBLE => {
w.want_visible = cmd.number != 0;
if (!w.want_visible) {
Input.release(w, n.UHDK_CYCLE_HIDDEN);
Popup.forget(w);
Input.clearPopupTrigger(w);
}
if (w.want_visible and !w.configured) c.wl_surface_commit(w.surface);
w.dirty = true;
},
n.Z_STYLE => return setStyle(b, w, cmd.style),
n.Z_DROP => return Data.enable(w, cmd.number != 0),
n.Z_CURSOR => return Input.cursor(w, @intCast(cmd.number)),
n.Z_POINTER => return Input.capture(w, cmd.number != 0),
n.Z_POINTER => return Input.pointerMode(w, @intCast(cmd.number)),
n.Z_FUNCTION_KEYS => {}, // No native window fallback for received function keys.
n.Z_TEXT_ENABLE => return Text.enable(w, cmd.number != 0),
n.Z_TEXT_STATE => return Text.snapshot(w, cmd.text_state),
n.Z_TEXT_CANCEL => Text.cancel(w),
n.Z_FOCUS => return Desktop.focus(w, id),
n.Z_REDRAW => emit(w, n.UHDK_EVENT_WINDOW_REDRAW),
n.Z_GL => return Egl.create(b, w, cmd.other, result),
n.Z_GL => return Egl.create(b, w),
else => return n.UHDK_STATUS_UNSUPPORTED,
}
return abi.OK;
}
export fn z_native_cancel(id: u64) void {
const b = instance orelse return;
if (Popup.cancel(id) or Data.cancel(id) or Portal.cancel(id) or Desktop.cancel(id)) return;
var cursor = b.windows;
while (cursor) |w| : (cursor = w.next) {
if (w.request == id) {
@ -649,6 +781,11 @@ export fn z_native_cancel(id: u64) void {
}
}
}
export fn z_native_tray_update(handle: ?*n.uhdk_tray, desc: [*c]const n.uhdk_tray_desc) u32 {
return Tray.update(handle.?, desc);
}
export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void {
const p = ptr orelse return;
switch (kind) {
@ -656,21 +793,41 @@ export fn z_native_destroy(kind: u32, ptr: ?*anyopaque) void {
const w: *Window = @ptrCast(@alignCast(p));
if (w.request != 0) completeCreation(w, abi.CANCELLED) else destroyWindow(w);
},
n.Z_KIND_TRAY => Tray.destroy(@ptrCast(@alignCast(p))),
n.Z_KIND_WATCH => Watch.destroy(@ptrCast(@alignCast(p))),
n.Z_KIND_GL => Egl.destroy(@ptrCast(@alignCast(p))),
n.Z_KIND_GL => {
const w: *Window = @ptrCast(@alignCast(p));
if (w.egl) |ctx| Egl.destroy(ctx);
},
else => {},
}
}
export fn z_native_handles(ptr: ?*anyopaque, out: [*c]n.uhdk_native_window) void {
const w: *Window = @ptrCast(@alignCast(ptr.?));
out.* = .{ .struct_size = @sizeOf(n.uhdk_native_window), .backend = n.UHDK_BACKEND_WAYLAND, .primary = instance.?.display, .secondary = w.surface, .value = 0 };
}
export fn z_native_gl(ptr: ?*anyopaque, op: u32, out: ?*anyopaque) u32 {
return Egl.call(ptr, op, out);
if (op == 4) return Egl.call(null, op, out);
const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
return Egl.call(w.egl, op, out);
}
export fn z_native_gl_proc(ptr: ?*anyopaque, name: n.uhdk_text, out: [*c]n.uhdk_gl_proc) u32 {
return Egl.proc(ptr, name, out);
const w: *Window = @ptrCast(@alignCast(ptr orelse return abi.INVALID));
return Egl.proc(w.egl, name, out);
}
export fn z_native_file_init(file: ?*n.uhdk_file, path: n.uhdk_bytes, uri: n.uhdk_text, grant: ?*anyopaque) u32 {
return @import("Files.zig").init(file, path, uri, grant);
}
export fn z_native_watch_prepare(root: ?*n.uhdk_file, handle: ?*n.uhdk_watch, out: *?*anyopaque) u32 {
return Watch.prepare(root, handle, out);
}
export fn z_native_watch_commit(handle: ?*n.uhdk_watch, prepared: *anyopaque) void {
Watch.commit(handle, prepared);
}

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -0,0 +1,110 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*
* Copyright © 2014 Jonas Ådahl
* Copyright © 2015 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface wl_pointer_interface;
extern const struct wl_interface wl_region_interface;
extern const struct wl_interface wl_surface_interface;
extern const struct wl_interface zwp_confined_pointer_v1_interface;
extern const struct wl_interface zwp_locked_pointer_v1_interface;
static const struct wl_interface *pointer_constraints_unstable_v1_types[] = {
NULL,
NULL,
&zwp_locked_pointer_v1_interface,
&wl_surface_interface,
&wl_pointer_interface,
&wl_region_interface,
NULL,
&zwp_confined_pointer_v1_interface,
&wl_surface_interface,
&wl_pointer_interface,
&wl_region_interface,
NULL,
&wl_region_interface,
&wl_region_interface,
};
static const struct wl_message zwp_pointer_constraints_v1_requests[] = {
{ "destroy", "", pointer_constraints_unstable_v1_types + 0 },
{ "lock_pointer", "noo?ou", pointer_constraints_unstable_v1_types + 2 },
{ "confine_pointer", "noo?ou", pointer_constraints_unstable_v1_types + 7 },
};
WL_PRIVATE const struct wl_interface zwp_pointer_constraints_v1_interface = {
"zwp_pointer_constraints_v1", 1,
3, zwp_pointer_constraints_v1_requests,
0, NULL,
};
static const struct wl_message zwp_locked_pointer_v1_requests[] = {
{ "destroy", "", pointer_constraints_unstable_v1_types + 0 },
{ "set_cursor_position_hint", "ff", pointer_constraints_unstable_v1_types + 0 },
{ "set_region", "?o", pointer_constraints_unstable_v1_types + 12 },
};
static const struct wl_message zwp_locked_pointer_v1_events[] = {
{ "locked", "", pointer_constraints_unstable_v1_types + 0 },
{ "unlocked", "", pointer_constraints_unstable_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface zwp_locked_pointer_v1_interface = {
"zwp_locked_pointer_v1", 1,
3, zwp_locked_pointer_v1_requests,
2, zwp_locked_pointer_v1_events,
};
static const struct wl_message zwp_confined_pointer_v1_requests[] = {
{ "destroy", "", pointer_constraints_unstable_v1_types + 0 },
{ "set_region", "?o", pointer_constraints_unstable_v1_types + 13 },
};
static const struct wl_message zwp_confined_pointer_v1_events[] = {
{ "confined", "", pointer_constraints_unstable_v1_types + 0 },
{ "unconfined", "", pointer_constraints_unstable_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface zwp_confined_pointer_v1_interface = {
"zwp_confined_pointer_v1", 1,
2, zwp_confined_pointer_v1_requests,
2, zwp_confined_pointer_v1_events,
};

View File

@ -0,0 +1,662 @@
/* Generated by wayland-scanner 1.24.0 */
#ifndef POINTER_CONSTRAINTS_UNSTABLE_V1_CLIENT_PROTOCOL_H
#define POINTER_CONSTRAINTS_UNSTABLE_V1_CLIENT_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-client.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @page page_pointer_constraints_unstable_v1 The pointer_constraints_unstable_v1 protocol
* protocol for constraining pointer motions
*
* @section page_desc_pointer_constraints_unstable_v1 Description
*
* This protocol specifies a set of interfaces used for adding constraints to
* the motion of a pointer. Possible constraints include confining pointer
* motions to a given region, or locking it to its current position.
*
* In order to constrain the pointer, a client must first bind the global
* interface "wp_pointer_constraints" which, if a compositor supports pointer
* constraints, is exposed by the registry. Using the bound global object, the
* client uses the request that corresponds to the type of constraint it wants
* to make. See wp_pointer_constraints for more details.
*
* Warning! The protocol described in this file is experimental and backward
* incompatible changes may be made. Backward compatible changes may be added
* together with the corresponding interface version bump. Backward
* incompatible changes are done by bumping the version number in the protocol
* and interface names and resetting the interface version. Once the protocol
* is to be declared stable, the 'z' prefix and the version number in the
* protocol and interface names are removed and the interface version number is
* reset.
*
* @section page_ifaces_pointer_constraints_unstable_v1 Interfaces
* - @subpage page_iface_zwp_pointer_constraints_v1 - constrain the movement of a pointer
* - @subpage page_iface_zwp_locked_pointer_v1 - receive relative pointer motion events
* - @subpage page_iface_zwp_confined_pointer_v1 - confined pointer object
* @section page_copyright_pointer_constraints_unstable_v1 Copyright
* <pre>
*
* Copyright © 2014 Jonas Ådahl
* Copyright © 2015 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* </pre>
*/
struct wl_pointer;
struct wl_region;
struct wl_surface;
struct zwp_confined_pointer_v1;
struct zwp_locked_pointer_v1;
struct zwp_pointer_constraints_v1;
#ifndef ZWP_POINTER_CONSTRAINTS_V1_INTERFACE
#define ZWP_POINTER_CONSTRAINTS_V1_INTERFACE
/**
* @page page_iface_zwp_pointer_constraints_v1 zwp_pointer_constraints_v1
* @section page_iface_zwp_pointer_constraints_v1_desc Description
*
* The global interface exposing pointer constraining functionality. It
* exposes two requests: lock_pointer for locking the pointer to its
* position, and confine_pointer for locking the pointer to a region.
*
* The lock_pointer and confine_pointer requests create the objects
* wp_locked_pointer and wp_confined_pointer respectively, and the client can
* use these objects to interact with the lock.
*
* For any surface, only one lock or confinement may be active across all
* wl_pointer objects of the same seat. If a lock or confinement is requested
* when another lock or confinement is active or requested on the same surface
* and with any of the wl_pointer objects of the same seat, an
* 'already_constrained' error will be raised.
* @section page_iface_zwp_pointer_constraints_v1_api API
* See @ref iface_zwp_pointer_constraints_v1.
*/
/**
* @defgroup iface_zwp_pointer_constraints_v1 The zwp_pointer_constraints_v1 interface
*
* The global interface exposing pointer constraining functionality. It
* exposes two requests: lock_pointer for locking the pointer to its
* position, and confine_pointer for locking the pointer to a region.
*
* The lock_pointer and confine_pointer requests create the objects
* wp_locked_pointer and wp_confined_pointer respectively, and the client can
* use these objects to interact with the lock.
*
* For any surface, only one lock or confinement may be active across all
* wl_pointer objects of the same seat. If a lock or confinement is requested
* when another lock or confinement is active or requested on the same surface
* and with any of the wl_pointer objects of the same seat, an
* 'already_constrained' error will be raised.
*/
extern const struct wl_interface zwp_pointer_constraints_v1_interface;
#endif
#ifndef ZWP_LOCKED_POINTER_V1_INTERFACE
#define ZWP_LOCKED_POINTER_V1_INTERFACE
/**
* @page page_iface_zwp_locked_pointer_v1 zwp_locked_pointer_v1
* @section page_iface_zwp_locked_pointer_v1_desc Description
*
* The wp_locked_pointer interface represents a locked pointer state.
*
* While the lock of this object is active, the wl_pointer objects of the
* associated seat will not emit any wl_pointer.motion events.
*
* This object will send the event 'locked' when the lock is activated.
* Whenever the lock is activated, it is guaranteed that the locked surface
* will already have received pointer focus and that the pointer will be
* within the region passed to the request creating this object.
*
* To unlock the pointer, send the destroy request. This will also destroy
* the wp_locked_pointer object.
*
* If the compositor decides to unlock the pointer the unlocked event is
* sent. See wp_locked_pointer.unlock for details.
*
* When unlocking, the compositor may warp the cursor position to the set
* cursor position hint. If it does, it will not result in any relative
* motion events emitted via wp_relative_pointer.
*
* If the surface the lock was requested on is destroyed and the lock is not
* yet activated, the wp_locked_pointer object is now defunct and must be
* destroyed.
* @section page_iface_zwp_locked_pointer_v1_api API
* See @ref iface_zwp_locked_pointer_v1.
*/
/**
* @defgroup iface_zwp_locked_pointer_v1 The zwp_locked_pointer_v1 interface
*
* The wp_locked_pointer interface represents a locked pointer state.
*
* While the lock of this object is active, the wl_pointer objects of the
* associated seat will not emit any wl_pointer.motion events.
*
* This object will send the event 'locked' when the lock is activated.
* Whenever the lock is activated, it is guaranteed that the locked surface
* will already have received pointer focus and that the pointer will be
* within the region passed to the request creating this object.
*
* To unlock the pointer, send the destroy request. This will also destroy
* the wp_locked_pointer object.
*
* If the compositor decides to unlock the pointer the unlocked event is
* sent. See wp_locked_pointer.unlock for details.
*
* When unlocking, the compositor may warp the cursor position to the set
* cursor position hint. If it does, it will not result in any relative
* motion events emitted via wp_relative_pointer.
*
* If the surface the lock was requested on is destroyed and the lock is not
* yet activated, the wp_locked_pointer object is now defunct and must be
* destroyed.
*/
extern const struct wl_interface zwp_locked_pointer_v1_interface;
#endif
#ifndef ZWP_CONFINED_POINTER_V1_INTERFACE
#define ZWP_CONFINED_POINTER_V1_INTERFACE
/**
* @page page_iface_zwp_confined_pointer_v1 zwp_confined_pointer_v1
* @section page_iface_zwp_confined_pointer_v1_desc Description
*
* The wp_confined_pointer interface represents a confined pointer state.
*
* This object will send the event 'confined' when the confinement is
* activated. Whenever the confinement is activated, it is guaranteed that
* the surface the pointer is confined to will already have received pointer
* focus and that the pointer will be within the region passed to the request
* creating this object. It is up to the compositor to decide whether this
* requires some user interaction and if the pointer will warp to within the
* passed region if outside.
*
* To unconfine the pointer, send the destroy request. This will also destroy
* the wp_confined_pointer object.
*
* If the compositor decides to unconfine the pointer the unconfined event is
* sent. The wp_confined_pointer object is at this point defunct and should
* be destroyed.
* @section page_iface_zwp_confined_pointer_v1_api API
* See @ref iface_zwp_confined_pointer_v1.
*/
/**
* @defgroup iface_zwp_confined_pointer_v1 The zwp_confined_pointer_v1 interface
*
* The wp_confined_pointer interface represents a confined pointer state.
*
* This object will send the event 'confined' when the confinement is
* activated. Whenever the confinement is activated, it is guaranteed that
* the surface the pointer is confined to will already have received pointer
* focus and that the pointer will be within the region passed to the request
* creating this object. It is up to the compositor to decide whether this
* requires some user interaction and if the pointer will warp to within the
* passed region if outside.
*
* To unconfine the pointer, send the destroy request. This will also destroy
* the wp_confined_pointer object.
*
* If the compositor decides to unconfine the pointer the unconfined event is
* sent. The wp_confined_pointer object is at this point defunct and should
* be destroyed.
*/
extern const struct wl_interface zwp_confined_pointer_v1_interface;
#endif
#ifndef ZWP_POINTER_CONSTRAINTS_V1_ERROR_ENUM
#define ZWP_POINTER_CONSTRAINTS_V1_ERROR_ENUM
/**
* @ingroup iface_zwp_pointer_constraints_v1
* wp_pointer_constraints error values
*
* These errors can be emitted in response to wp_pointer_constraints
* requests.
*/
enum zwp_pointer_constraints_v1_error {
/**
* pointer constraint already requested on that surface
*/
ZWP_POINTER_CONSTRAINTS_V1_ERROR_ALREADY_CONSTRAINED = 1,
};
#endif /* ZWP_POINTER_CONSTRAINTS_V1_ERROR_ENUM */
#ifndef ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ENUM
#define ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ENUM
/**
* @ingroup iface_zwp_pointer_constraints_v1
* constraint lifetime
*
* These values represent different lifetime semantics. They are passed
* as arguments to the factory requests to specify how the constraint
* lifetimes should be managed.
*/
enum zwp_pointer_constraints_v1_lifetime {
/**
* the pointer constraint is defunct once deactivated
*
* A oneshot pointer constraint will never reactivate once it has
* been deactivated. See the corresponding deactivation event
* (wp_locked_pointer.unlocked and wp_confined_pointer.unconfined)
* for details.
*/
ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT = 1,
/**
* the pointer constraint may reactivate
*
* A persistent pointer constraint may again reactivate once it
* has been deactivated. See the corresponding deactivation event
* (wp_locked_pointer.unlocked and wp_confined_pointer.unconfined)
* for details.
*/
ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT = 2,
};
#endif /* ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ENUM */
#define ZWP_POINTER_CONSTRAINTS_V1_DESTROY 0
#define ZWP_POINTER_CONSTRAINTS_V1_LOCK_POINTER 1
#define ZWP_POINTER_CONSTRAINTS_V1_CONFINE_POINTER 2
/**
* @ingroup iface_zwp_pointer_constraints_v1
*/
#define ZWP_POINTER_CONSTRAINTS_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_zwp_pointer_constraints_v1
*/
#define ZWP_POINTER_CONSTRAINTS_V1_LOCK_POINTER_SINCE_VERSION 1
/**
* @ingroup iface_zwp_pointer_constraints_v1
*/
#define ZWP_POINTER_CONSTRAINTS_V1_CONFINE_POINTER_SINCE_VERSION 1
/** @ingroup iface_zwp_pointer_constraints_v1 */
static inline void
zwp_pointer_constraints_v1_set_user_data(struct zwp_pointer_constraints_v1 *zwp_pointer_constraints_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zwp_pointer_constraints_v1, user_data);
}
/** @ingroup iface_zwp_pointer_constraints_v1 */
static inline void *
zwp_pointer_constraints_v1_get_user_data(struct zwp_pointer_constraints_v1 *zwp_pointer_constraints_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) zwp_pointer_constraints_v1);
}
static inline uint32_t
zwp_pointer_constraints_v1_get_version(struct zwp_pointer_constraints_v1 *zwp_pointer_constraints_v1)
{
return wl_proxy_get_version((struct wl_proxy *) zwp_pointer_constraints_v1);
}
/**
* @ingroup iface_zwp_pointer_constraints_v1
*
* Used by the client to notify the server that it will no longer use this
* pointer constraints object.
*/
static inline void
zwp_pointer_constraints_v1_destroy(struct zwp_pointer_constraints_v1 *zwp_pointer_constraints_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_pointer_constraints_v1,
ZWP_POINTER_CONSTRAINTS_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_pointer_constraints_v1), WL_MARSHAL_FLAG_DESTROY);
}
/**
* @ingroup iface_zwp_pointer_constraints_v1
*
* The lock_pointer request lets the client request to disable movements of
* the virtual pointer (i.e. the cursor), effectively locking the pointer
* to a position. This request may not take effect immediately; in the
* future, when the compositor deems implementation-specific constraints
* are satisfied, the pointer lock will be activated and the compositor
* sends a locked event.
*
* The protocol provides no guarantee that the constraints are ever
* satisfied, and does not require the compositor to send an error if the
* constraints cannot ever be satisfied. It is thus possible to request a
* lock that will never activate.
*
* There may not be another pointer constraint of any kind requested or
* active on the surface for any of the wl_pointer objects of the seat of
* the passed pointer when requesting a lock. If there is, an error will be
* raised. See general pointer lock documentation for more details.
*
* The intersection of the region passed with this request and the input
* region of the surface is used to determine where the pointer must be
* in order for the lock to activate. It is up to the compositor whether to
* warp the pointer or require some kind of user interaction for the lock
* to activate. If the region is null the surface input region is used.
*
* A surface may receive pointer focus without the lock being activated.
*
* The request creates a new object wp_locked_pointer which is used to
* interact with the lock as well as receive updates about its state. See
* the the description of wp_locked_pointer for further information.
*
* Note that while a pointer is locked, the wl_pointer objects of the
* corresponding seat will not emit any wl_pointer.motion events, but
* relative motion events will still be emitted via wp_relative_pointer
* objects of the same seat. wl_pointer.axis and wl_pointer.button events
* are unaffected.
*/
static inline struct zwp_locked_pointer_v1 *
zwp_pointer_constraints_v1_lock_pointer(struct zwp_pointer_constraints_v1 *zwp_pointer_constraints_v1, struct wl_surface *surface, struct wl_pointer *pointer, struct wl_region *region, uint32_t lifetime)
{
struct wl_proxy *id;
id = wl_proxy_marshal_flags((struct wl_proxy *) zwp_pointer_constraints_v1,
ZWP_POINTER_CONSTRAINTS_V1_LOCK_POINTER, &zwp_locked_pointer_v1_interface, wl_proxy_get_version((struct wl_proxy *) zwp_pointer_constraints_v1), 0, NULL, surface, pointer, region, lifetime);
return (struct zwp_locked_pointer_v1 *) id;
}
/**
* @ingroup iface_zwp_pointer_constraints_v1
*
* The confine_pointer request lets the client request to confine the
* pointer cursor to a given region. This request may not take effect
* immediately; in the future, when the compositor deems implementation-
* specific constraints are satisfied, the pointer confinement will be
* activated and the compositor sends a confined event.
*
* The intersection of the region passed with this request and the input
* region of the surface is used to determine where the pointer must be
* in order for the confinement to activate. It is up to the compositor
* whether to warp the pointer or require some kind of user interaction for
* the confinement to activate. If the region is null the surface input
* region is used.
*
* The request will create a new object wp_confined_pointer which is used
* to interact with the confinement as well as receive updates about its
* state. See the the description of wp_confined_pointer for further
* information.
*/
static inline struct zwp_confined_pointer_v1 *
zwp_pointer_constraints_v1_confine_pointer(struct zwp_pointer_constraints_v1 *zwp_pointer_constraints_v1, struct wl_surface *surface, struct wl_pointer *pointer, struct wl_region *region, uint32_t lifetime)
{
struct wl_proxy *id;
id = wl_proxy_marshal_flags((struct wl_proxy *) zwp_pointer_constraints_v1,
ZWP_POINTER_CONSTRAINTS_V1_CONFINE_POINTER, &zwp_confined_pointer_v1_interface, wl_proxy_get_version((struct wl_proxy *) zwp_pointer_constraints_v1), 0, NULL, surface, pointer, region, lifetime);
return (struct zwp_confined_pointer_v1 *) id;
}
/**
* @ingroup iface_zwp_locked_pointer_v1
* @struct zwp_locked_pointer_v1_listener
*/
struct zwp_locked_pointer_v1_listener {
/**
* lock activation event
*
* Notification that the pointer lock of the seat's pointer is
* activated.
*/
void (*locked)(void *data,
struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1);
/**
* lock deactivation event
*
* Notification that the pointer lock of the seat's pointer is no
* longer active. If this is a oneshot pointer lock (see
* wp_pointer_constraints.lifetime) this object is now defunct and
* should be destroyed. If this is a persistent pointer lock (see
* wp_pointer_constraints.lifetime) this pointer lock may again
* reactivate in the future.
*/
void (*unlocked)(void *data,
struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1);
};
/**
* @ingroup iface_zwp_locked_pointer_v1
*/
static inline int
zwp_locked_pointer_v1_add_listener(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1,
const struct zwp_locked_pointer_v1_listener *listener, void *data)
{
return wl_proxy_add_listener((struct wl_proxy *) zwp_locked_pointer_v1,
(void (**)(void)) listener, data);
}
#define ZWP_LOCKED_POINTER_V1_DESTROY 0
#define ZWP_LOCKED_POINTER_V1_SET_CURSOR_POSITION_HINT 1
#define ZWP_LOCKED_POINTER_V1_SET_REGION 2
/**
* @ingroup iface_zwp_locked_pointer_v1
*/
#define ZWP_LOCKED_POINTER_V1_LOCKED_SINCE_VERSION 1
/**
* @ingroup iface_zwp_locked_pointer_v1
*/
#define ZWP_LOCKED_POINTER_V1_UNLOCKED_SINCE_VERSION 1
/**
* @ingroup iface_zwp_locked_pointer_v1
*/
#define ZWP_LOCKED_POINTER_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_zwp_locked_pointer_v1
*/
#define ZWP_LOCKED_POINTER_V1_SET_CURSOR_POSITION_HINT_SINCE_VERSION 1
/**
* @ingroup iface_zwp_locked_pointer_v1
*/
#define ZWP_LOCKED_POINTER_V1_SET_REGION_SINCE_VERSION 1
/** @ingroup iface_zwp_locked_pointer_v1 */
static inline void
zwp_locked_pointer_v1_set_user_data(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zwp_locked_pointer_v1, user_data);
}
/** @ingroup iface_zwp_locked_pointer_v1 */
static inline void *
zwp_locked_pointer_v1_get_user_data(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) zwp_locked_pointer_v1);
}
static inline uint32_t
zwp_locked_pointer_v1_get_version(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1)
{
return wl_proxy_get_version((struct wl_proxy *) zwp_locked_pointer_v1);
}
/**
* @ingroup iface_zwp_locked_pointer_v1
*
* Destroy the locked pointer object. If applicable, the compositor will
* unlock the pointer.
*/
static inline void
zwp_locked_pointer_v1_destroy(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_locked_pointer_v1,
ZWP_LOCKED_POINTER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_locked_pointer_v1), WL_MARSHAL_FLAG_DESTROY);
}
/**
* @ingroup iface_zwp_locked_pointer_v1
*
* Set the cursor position hint relative to the top left corner of the
* surface.
*
* If the client is drawing its own cursor, it should update the position
* hint to the position of its own cursor. A compositor may use this
* information to warp the pointer upon unlock in order to avoid pointer
* jumps.
*
* The cursor position hint is double-buffered state, see
* wl_surface.commit.
*/
static inline void
zwp_locked_pointer_v1_set_cursor_position_hint(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1, wl_fixed_t surface_x, wl_fixed_t surface_y)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_locked_pointer_v1,
ZWP_LOCKED_POINTER_V1_SET_CURSOR_POSITION_HINT, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_locked_pointer_v1), 0, surface_x, surface_y);
}
/**
* @ingroup iface_zwp_locked_pointer_v1
*
* Set a new region used to lock the pointer.
*
* The new lock region is double-buffered, see wl_surface.commit.
*
* For details about the lock region, see wp_locked_pointer.
*/
static inline void
zwp_locked_pointer_v1_set_region(struct zwp_locked_pointer_v1 *zwp_locked_pointer_v1, struct wl_region *region)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_locked_pointer_v1,
ZWP_LOCKED_POINTER_V1_SET_REGION, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_locked_pointer_v1), 0, region);
}
/**
* @ingroup iface_zwp_confined_pointer_v1
* @struct zwp_confined_pointer_v1_listener
*/
struct zwp_confined_pointer_v1_listener {
/**
* pointer confined
*
* Notification that the pointer confinement of the seat's
* pointer is activated.
*/
void (*confined)(void *data,
struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1);
/**
* pointer unconfined
*
* Notification that the pointer confinement of the seat's
* pointer is no longer active. If this is a oneshot pointer
* confinement (see wp_pointer_constraints.lifetime) this object is
* now defunct and should be destroyed. If this is a persistent
* pointer confinement (see wp_pointer_constraints.lifetime) this
* pointer confinement may again reactivate in the future.
*/
void (*unconfined)(void *data,
struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1);
};
/**
* @ingroup iface_zwp_confined_pointer_v1
*/
static inline int
zwp_confined_pointer_v1_add_listener(struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1,
const struct zwp_confined_pointer_v1_listener *listener, void *data)
{
return wl_proxy_add_listener((struct wl_proxy *) zwp_confined_pointer_v1,
(void (**)(void)) listener, data);
}
#define ZWP_CONFINED_POINTER_V1_DESTROY 0
#define ZWP_CONFINED_POINTER_V1_SET_REGION 1
/**
* @ingroup iface_zwp_confined_pointer_v1
*/
#define ZWP_CONFINED_POINTER_V1_CONFINED_SINCE_VERSION 1
/**
* @ingroup iface_zwp_confined_pointer_v1
*/
#define ZWP_CONFINED_POINTER_V1_UNCONFINED_SINCE_VERSION 1
/**
* @ingroup iface_zwp_confined_pointer_v1
*/
#define ZWP_CONFINED_POINTER_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_zwp_confined_pointer_v1
*/
#define ZWP_CONFINED_POINTER_V1_SET_REGION_SINCE_VERSION 1
/** @ingroup iface_zwp_confined_pointer_v1 */
static inline void
zwp_confined_pointer_v1_set_user_data(struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zwp_confined_pointer_v1, user_data);
}
/** @ingroup iface_zwp_confined_pointer_v1 */
static inline void *
zwp_confined_pointer_v1_get_user_data(struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) zwp_confined_pointer_v1);
}
static inline uint32_t
zwp_confined_pointer_v1_get_version(struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1)
{
return wl_proxy_get_version((struct wl_proxy *) zwp_confined_pointer_v1);
}
/**
* @ingroup iface_zwp_confined_pointer_v1
*
* Destroy the confined pointer object. If applicable, the compositor will
* unconfine the pointer.
*/
static inline void
zwp_confined_pointer_v1_destroy(struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_confined_pointer_v1,
ZWP_CONFINED_POINTER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_confined_pointer_v1), WL_MARSHAL_FLAG_DESTROY);
}
/**
* @ingroup iface_zwp_confined_pointer_v1
*
* Set a new region used to confine the pointer.
*
* The new confine region is double-buffered, see wl_surface.commit.
*
* If the confinement is active when the new confinement region is applied
* and the pointer ends up outside of newly applied region, the pointer may
* warped to a position within the new confinement region. If warped, a
* wl_pointer.motion event will be emitted, but no
* wp_relative_pointer.relative_motion event.
*
* The compositor may also, instead of using the new region, unconfine the
* pointer.
*
* For details about the confine region, see wp_confined_pointer.
*/
static inline void
zwp_confined_pointer_v1_set_region(struct zwp_confined_pointer_v1 *zwp_confined_pointer_v1, struct wl_region *region)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_confined_pointer_v1,
ZWP_CONFINED_POINTER_V1_SET_REGION, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_confined_pointer_v1), 0, region);
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -5,6 +5,9 @@
#define wp_cursor_shape_device_v1_interface z_uhdk_wp_cursor_shape_device_v1_interface
#define wp_fractional_scale_manager_v1_interface z_uhdk_wp_fractional_scale_manager_v1_interface
#define wp_fractional_scale_v1_interface z_uhdk_wp_fractional_scale_v1_interface
#define zwp_pointer_constraints_v1_interface z_uhdk_zwp_pointer_constraints_v1_interface
#define zwp_locked_pointer_v1_interface z_uhdk_zwp_locked_pointer_v1_interface
#define zwp_confined_pointer_v1_interface z_uhdk_zwp_confined_pointer_v1_interface
#define zwp_tablet_manager_v2_interface z_uhdk_zwp_tablet_manager_v2_interface
#define zwp_tablet_seat_v2_interface z_uhdk_zwp_tablet_seat_v2_interface
#define zwp_tablet_tool_v2_interface z_uhdk_zwp_tablet_tool_v2_interface

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -1,3 +1,4 @@
#include "private-symbols.h"
/* Generated by wayland-scanner 1.24.0 */
/*

View File

@ -0,0 +1,334 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="pointer_constraints_unstable_v1">
<copyright>
Copyright © 2014 Jonas Ådahl
Copyright © 2015 Red Hat Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<description summary="protocol for constraining pointer motions">
This protocol specifies a set of interfaces used for adding constraints to
the motion of a pointer. Possible constraints include confining pointer
motions to a given region, or locking it to its current position.
In order to constrain the pointer, a client must first bind the global
interface "wp_pointer_constraints" which, if a compositor supports pointer
constraints, is exposed by the registry. Using the bound global object, the
client uses the request that corresponds to the type of constraint it wants
to make. See wp_pointer_constraints for more details.
Warning! The protocol described in this file is experimental and backward
incompatible changes may be made. Backward compatible changes may be added
together with the corresponding interface version bump. Backward
incompatible changes are done by bumping the version number in the protocol
and interface names and resetting the interface version. Once the protocol
is to be declared stable, the 'z' prefix and the version number in the
protocol and interface names are removed and the interface version number is
reset.
</description>
<interface name="zwp_pointer_constraints_v1" version="1">
<description summary="constrain the movement of a pointer">
The global interface exposing pointer constraining functionality. It
exposes two requests: lock_pointer for locking the pointer to its
position, and confine_pointer for locking the pointer to a region.
The lock_pointer and confine_pointer requests create the objects
wp_locked_pointer and wp_confined_pointer respectively, and the client can
use these objects to interact with the lock.
For any surface, only one lock or confinement may be active across all
wl_pointer objects of the same seat. If a lock or confinement is requested
when another lock or confinement is active or requested on the same surface
and with any of the wl_pointer objects of the same seat, an
'already_constrained' error will be raised.
</description>
<enum name="error">
<description summary="wp_pointer_constraints error values">
These errors can be emitted in response to wp_pointer_constraints
requests.
</description>
<entry name="already_constrained" value="1"
summary="pointer constraint already requested on that surface"/>
</enum>
<enum name="lifetime">
<description summary="constraint lifetime">
These values represent different lifetime semantics. They are passed
as arguments to the factory requests to specify how the constraint
lifetimes should be managed.
</description>
<entry name="oneshot" value="1">
<description summary="the pointer constraint is defunct once deactivated">
A oneshot pointer constraint will never reactivate once it has been
deactivated. See the corresponding deactivation event
(wp_locked_pointer.unlocked and wp_confined_pointer.unconfined) for
details.
</description>
</entry>
<entry name="persistent" value="2">
<description summary="the pointer constraint may reactivate">
A persistent pointer constraint may again reactivate once it has
been deactivated. See the corresponding deactivation event
(wp_locked_pointer.unlocked and wp_confined_pointer.unconfined) for
details.
</description>
</entry>
</enum>
<request name="destroy" type="destructor">
<description summary="destroy the pointer constraints manager object">
Used by the client to notify the server that it will no longer use this
pointer constraints object.
</description>
</request>
<request name="lock_pointer">
<description summary="lock pointer to a position">
The lock_pointer request lets the client request to disable movements of
the virtual pointer (i.e. the cursor), effectively locking the pointer
to a position. This request may not take effect immediately; in the
future, when the compositor deems implementation-specific constraints
are satisfied, the pointer lock will be activated and the compositor
sends a locked event.
The protocol provides no guarantee that the constraints are ever
satisfied, and does not require the compositor to send an error if the
constraints cannot ever be satisfied. It is thus possible to request a
lock that will never activate.
There may not be another pointer constraint of any kind requested or
active on the surface for any of the wl_pointer objects of the seat of
the passed pointer when requesting a lock. If there is, an error will be
raised. See general pointer lock documentation for more details.
The intersection of the region passed with this request and the input
region of the surface is used to determine where the pointer must be
in order for the lock to activate. It is up to the compositor whether to
warp the pointer or require some kind of user interaction for the lock
to activate. If the region is null the surface input region is used.
A surface may receive pointer focus without the lock being activated.
The request creates a new object wp_locked_pointer which is used to
interact with the lock as well as receive updates about its state. See
the the description of wp_locked_pointer for further information.
Note that while a pointer is locked, the wl_pointer objects of the
corresponding seat will not emit any wl_pointer.motion events, but
relative motion events will still be emitted via wp_relative_pointer
objects of the same seat. wl_pointer.axis and wl_pointer.button events
are unaffected.
</description>
<arg name="id" type="new_id" interface="zwp_locked_pointer_v1"/>
<arg name="surface" type="object" interface="wl_surface"
summary="surface to lock pointer to"/>
<arg name="pointer" type="object" interface="wl_pointer"
summary="the pointer that should be locked"/>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
<arg name="lifetime" type="uint" enum="lifetime" summary="lock lifetime"/>
</request>
<request name="confine_pointer">
<description summary="confine pointer to a region">
The confine_pointer request lets the client request to confine the
pointer cursor to a given region. This request may not take effect
immediately; in the future, when the compositor deems implementation-
specific constraints are satisfied, the pointer confinement will be
activated and the compositor sends a confined event.
The intersection of the region passed with this request and the input
region of the surface is used to determine where the pointer must be
in order for the confinement to activate. It is up to the compositor
whether to warp the pointer or require some kind of user interaction for
the confinement to activate. If the region is null the surface input
region is used.
The request will create a new object wp_confined_pointer which is used
to interact with the confinement as well as receive updates about its
state. See the the description of wp_confined_pointer for further
information.
</description>
<arg name="id" type="new_id" interface="zwp_confined_pointer_v1"/>
<arg name="surface" type="object" interface="wl_surface"
summary="surface to lock pointer to"/>
<arg name="pointer" type="object" interface="wl_pointer"
summary="the pointer that should be confined"/>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
<arg name="lifetime" type="uint" enum="lifetime" summary="confinement lifetime"/>
</request>
</interface>
<interface name="zwp_locked_pointer_v1" version="1">
<description summary="receive relative pointer motion events">
The wp_locked_pointer interface represents a locked pointer state.
While the lock of this object is active, the wl_pointer objects of the
associated seat will not emit any wl_pointer.motion events.
This object will send the event 'locked' when the lock is activated.
Whenever the lock is activated, it is guaranteed that the locked surface
will already have received pointer focus and that the pointer will be
within the region passed to the request creating this object.
To unlock the pointer, send the destroy request. This will also destroy
the wp_locked_pointer object.
If the compositor decides to unlock the pointer the unlocked event is
sent. See wp_locked_pointer.unlock for details.
When unlocking, the compositor may warp the cursor position to the set
cursor position hint. If it does, it will not result in any relative
motion events emitted via wp_relative_pointer.
If the surface the lock was requested on is destroyed and the lock is not
yet activated, the wp_locked_pointer object is now defunct and must be
destroyed.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the locked pointer object">
Destroy the locked pointer object. If applicable, the compositor will
unlock the pointer.
</description>
</request>
<request name="set_cursor_position_hint">
<description summary="set the pointer cursor position hint">
Set the cursor position hint relative to the top left corner of the
surface.
If the client is drawing its own cursor, it should update the position
hint to the position of its own cursor. A compositor may use this
information to warp the pointer upon unlock in order to avoid pointer
jumps.
The cursor position hint is double-buffered state, see
wl_surface.commit.
</description>
<arg name="surface_x" type="fixed"
summary="surface-local x coordinate"/>
<arg name="surface_y" type="fixed"
summary="surface-local y coordinate"/>
</request>
<request name="set_region">
<description summary="set a new lock region">
Set a new region used to lock the pointer.
The new lock region is double-buffered, see wl_surface.commit.
For details about the lock region, see wp_locked_pointer.
</description>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
</request>
<event name="locked">
<description summary="lock activation event">
Notification that the pointer lock of the seat's pointer is activated.
</description>
</event>
<event name="unlocked">
<description summary="lock deactivation event">
Notification that the pointer lock of the seat's pointer is no longer
active. If this is a oneshot pointer lock (see
wp_pointer_constraints.lifetime) this object is now defunct and should
be destroyed. If this is a persistent pointer lock (see
wp_pointer_constraints.lifetime) this pointer lock may again
reactivate in the future.
</description>
</event>
</interface>
<interface name="zwp_confined_pointer_v1" version="1">
<description summary="confined pointer object">
The wp_confined_pointer interface represents a confined pointer state.
This object will send the event 'confined' when the confinement is
activated. Whenever the confinement is activated, it is guaranteed that
the surface the pointer is confined to will already have received pointer
focus and that the pointer will be within the region passed to the request
creating this object. It is up to the compositor to decide whether this
requires some user interaction and if the pointer will warp to within the
passed region if outside.
To unconfine the pointer, send the destroy request. This will also destroy
the wp_confined_pointer object.
If the compositor decides to unconfine the pointer the unconfined event is
sent. The wp_confined_pointer object is at this point defunct and should
be destroyed.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the confined pointer object">
Destroy the confined pointer object. If applicable, the compositor will
unconfine the pointer.
</description>
</request>
<request name="set_region">
<description summary="set a new confine region">
Set a new region used to confine the pointer.
The new confine region is double-buffered, see wl_surface.commit.
If the confinement is active when the new confinement region is applied
and the pointer ends up outside of newly applied region, the pointer may
warped to a position within the new confinement region. If warped, a
wl_pointer.motion event will be emitted, but no
wp_relative_pointer.relative_motion event.
The compositor may also, instead of using the new region, unconfine the
pointer.
For details about the confine region, see wp_confined_pointer.
</description>
<arg name="region" type="object" interface="wl_region" allow-null="true"
summary="region of surface"/>
</request>
<event name="confined">
<description summary="pointer confined">
Notification that the pointer confinement of the seat's pointer is
activated.
</description>
</event>
<event name="unconfined">
<description summary="pointer unconfined">
Notification that the pointer confinement of the seat's pointer is no
longer active. If this is a oneshot pointer confinement (see
wp_pointer_constraints.lifetime) this object is now defunct and should
be destroyed. If this is a persistent pointer confinement (see
wp_pointer_constraints.lifetime) this pointer confinement may again
reactivate in the future.
</description>
</event>
</interface>
</protocol>

View File

@ -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)

View File

@ -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)

View File

@ -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('<busconfig><type>session</type><listen>unix:tmpdir=/tmp</listen><auth>EXTERNAL</auth><policy context="default"><allow send_destination="*"/><allow receive_sender="*"/><allow own="*"/></policy></busconfig>')
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())))

View File

@ -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]))

View File

@ -1,159 +0,0 @@
/* Included by the service harness: all desktop traffic uses private fixtures. */
#define OPEN_ID UINT64_C(0x1234567800000065)
static void menu_phase(uhdk_app *app, uhdk_window *w, const char *phase) {
uint64_t id;
OK(uhdk_window_set_title_async(w, text(phase), &id));
OK(wait_result(app, id).status);
}
static void menus(uhdk_app *app) {
wait_capability(app, UHDK_CAP_APP_MENU);
assert(!uhdk_app_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_app_set_menu_async(app, root, &id));
OK(wait_result(app, id).status);
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_async(b, override, &id));
OK(wait_result(app, id).status);
uhdk_menu_release(override); // The attachment must keep its model alive.
OK(uhdk_window_set_text_input_async(a, 1, &id));
OK(wait_result(app, id).status);
OK(uhdk_menu_popup_async(root, a, (uhdk_point){0, 0}, &id));
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_app_get_time_ns(app) < end) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &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_async(root, 10, UHDK_MENU_DISABLED, &id));
OK(wait_result(app, id).status);
OK(uhdk_menu_set_item_flags_async(root, 102, 0, &id));
OK(wait_result(app, id).status);
menu_phase(app, a, "flags-ready");
} else if (stage == 2) {
assert(raw_o >= 2);
OK(uhdk_menu_set_item_flags_async(root, 10, 0, &id));
OK(wait_result(app, id).status);
OK(uhdk_window_set_menu_async(b, NULL, &id));
OK(wait_result(app, id).status);
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_async(b, override, &id));
OK(wait_result(app, id).status);
uhdk_menu_release(override);
OK(uhdk_app_set_menu_async(app, NULL, &id));
OK(wait_result(app, id).status);
uhdk_menu_release(root);
uhdk_window_destroy(a);
menu_phase(app, b, "detached-ready");
}
}
assert(stage == 4);
assert(!uhdk_app_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_app *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));
uint64_t id;
OK(uhdk_app_set_menu_async(app, menu, &id));
assert(
wait_result(app, id).status == (no_bus ? UHDK_STATUS_UNAVAILABLE : UHDK_STATUS_UNSUPPORTED)
);
OK(uhdk_window_set_menu_async(w, menu, &id));
assert(
wait_result(app, id).status == (no_bus ? UHDK_STATUS_UNAVAILABLE : UHDK_STATUS_UNSUPPORTED)
);
assert(!uhdk_app_has_capability(app, UHDK_CAP_APP_MENU));
OK(uhdk_menu_set_item_flags_async(menu, 1, UHDK_MENU_CHECKED, &id));
OK(wait_result(app, id).status);
OK(uhdk_app_set_menu_async(app, NULL, &id));
OK(wait_result(app, id).status);
uhdk_menu_release(menu);
uhdk_window_destroy(w);
puts("Unavailable menu protocol/session bus: PASS");
}

View File

@ -1,245 +0,0 @@
#define UHDK_ENABLE_OPENGL
#define UHDK_ENABLE_NATIVE
#include "uhdk.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OK(expression) \
do { \
uhdk_status status = (expression); \
if (status != UHDK_STATUS_OK) { \
fprintf(stderr, "%s:%d: %s returned %u\n", __FILE__, __LINE__, #expression, status); \
abort(); \
} \
} while (0)
static uhdk_text text(const char *s) {
return (uhdk_text){s, strlen(s)};
}
static int entered;
static uhdk_request_result wait_request(uhdk_app *app, uint64_t id) {
uint64_t deadline = uhdk_app_get_time_ns(app) + 10000000000ull;
while (uhdk_app_get_time_ns(app) < deadline) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 100000000ull, &events));
for (uint64_t i = 0; i < events.len; ++i) {
const uhdk_event *event = &events.ptr[i];
if (event->type == UHDK_EVENT_REQUEST_DONE) {
const uhdk_request_result *result = event->data;
assert(result->id == id);
return *result;
}
}
}
fputs("Timed out awaiting request\n", stderr);
abort();
}
static uhdk_window_metrics metrics(uhdk_window *w) {
uhdk_window_metrics m = {0};
m.struct_size = sizeof(m);
OK(uhdk_window_get_metrics(w, &m));
return m;
}
static void wait_metrics(uhdk_app *app, uhdk_window *w, int visible, int width) {
uint64_t deadline = uhdk_app_get_time_ns(app) + 10000000000ull;
while (uhdk_app_get_time_ns(app) < deadline) {
uhdk_window_metrics m = metrics(w);
if (m.visible == visible && m.logical_size.width == width)
return;
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 100000000ull, &events));
}
fputs("Timed out awaiting metrics\n", stderr);
abort();
}
static uhdk_window_desc descriptor(void) {
uhdk_window_desc desc = {0};
desc.struct_size = sizeof(desc);
desc.title = text("UHDK Linux lifecycle test");
desc.flags = UHDK_WINDOW_OPENGL | UHDK_WINDOW_DECORATED | UHDK_WINDOW_RESIZABLE;
desc.content_size = (uhdk_size){320, 240};
return desc;
}
static uhdk_window *create_window(uhdk_app *app) {
uhdk_window_desc desc = descriptor();
uint64_t id;
OK(uhdk_window_create_async(app, &desc, &id));
uhdk_request_result result = wait_request(app, id);
OK(result.status);
return ((const uhdk_window_result *)result.data)->window;
}
static void test_main(uhdk_app *app, void *user) {
++entered;
assert(uhdk_app_get_backend(app) == UHDK_BACKEND_WAYLAND);
assert(!uhdk_app_has_capability(app, UHDK_CAP_FILE_DIALOGS));
uhdk_event_list ready;
OK(uhdk_app_poll_events(app, 0, &ready));
assert(ready.len > 0 && ready.ptr[0].type == UHDK_EVENT_READY);
// Cancellation must complete exactly once even before the first configure.
uint64_t id;
uhdk_window_desc desc = descriptor();
OK(uhdk_window_create_async(app, &desc, &id));
OK(uhdk_request_cancel(app, id));
uhdk_request_result cancelled = wait_request(app, id);
assert(cancelled.status == UHDK_STATUS_CANCELLED || cancelled.status == UHDK_STATUS_OK);
if (cancelled.status == UHDK_STATUS_OK)
uhdk_window_destroy(((const uhdk_window_result *)cancelled.data)->window);
// Destroying a parent must also complete a child still awaiting configure.
uhdk_window *parent = create_window(app);
desc.parent = parent;
OK(uhdk_window_create_async(app, &desc, &id));
uhdk_window_destroy(parent);
uhdk_request_result child = wait_request(app, id);
assert(child.status == UHDK_STATUS_CANCELLED || child.status == UHDK_STATUS_OK);
desc.parent = NULL;
uhdk_window *w = create_window(app);
assert(metrics(w).visible == 0);
uhdk_native_window native = {0};
native.struct_size = sizeof(native);
OK(uhdk_window_get_native(w, &native));
assert(native.backend == UHDK_BACKEND_WAYLAND && native.primary && native.secondary);
const uint8_t path[] = "/tmp/uhdk file-%\xff";
uhdk_file *file;
OK(uhdk_file_create_from_native_path(app, (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);
if (!user) {
assert(uhdk_app_has_capability(app, UHDK_CAP_OPENGL));
OK(uhdk_gl_context_create_async(w, &id));
uhdk_request_result gl_result = wait_request(app, id);
OK(gl_result.status);
uhdk_gl_context *gl = ((const uhdk_gl_context_result *)gl_result.data)->gl_context;
OK(uhdk_gl_context_begin_frame(gl));
assert(uhdk_gl_context_begin_frame(gl) == UHDK_STATUS_BUSY);
uint32_t major, minor;
OK(uhdk_gl_context_get_version(gl, &major, &minor));
assert(major > 3 || (major == 3 && minor >= 3));
fprintf(stderr, "Linux context: OpenGL %u.%u\n", major, minor);
OK(uhdk_gl_clear_current(app));
assert(uhdk_gl_context_get_version(gl, &major, &minor) == UHDK_STATUS_BUSY);
OK(uhdk_gl_context_make_current(gl));
uhdk_gl_proc address;
OK(uhdk_gl_context_get_proc(gl, text("glClearColor"), &address));
PFNGLCLEARCOLORPROC clear_color = (PFNGLCLEARCOLORPROC)address;
OK(uhdk_gl_context_get_proc(gl, text("glClear"), &address));
PFNGLCLEARPROC clear = (PFNGLCLEARPROC)address;
OK(uhdk_gl_context_get_proc(gl, text("glReadPixels"), &address));
PFNGLREADPIXELSPROC read_pixels = (PFNGLREADPIXELSPROC)address;
OK(uhdk_gl_context_set_swap_interval(gl, 1));
assert(uhdk_gl_context_swap_buffers(gl) == UHDK_STATUS_UNAVAILABLE);
OK(uhdk_gl_context_end_frame(gl));
for (int pass = 0; pass < 3; ++pass) {
int width = 320 + pass * 20;
OK(uhdk_window_set_size_async(w, (uhdk_size){width, 240}, &id));
OK(wait_request(app, id).status);
OK(uhdk_window_set_visible_async(w, 1, &id));
OK(wait_request(app, id).status);
wait_metrics(app, w, 1, width);
for (int frame = 0; frame < 4; ++frame) {
OK(uhdk_gl_context_begin_frame(gl));
clear_color(0.25f, 0.5f, 0.75f, 1.0f);
clear(GL_COLOR_BUFFER_BIT);
unsigned char pixel[4] = {0};
read_pixels(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_gl_context_swap_buffers(gl));
OK(uhdk_gl_context_end_frame(gl));
}
OK(uhdk_window_set_visible_async(w, 0, &id));
OK(wait_request(app, id).status);
wait_metrics(app, w, 0, width);
}
uhdk_gl_context_destroy(gl);
// Destroying a context releases its reservation on the window.
OK(uhdk_gl_context_create_async(w, &id));
gl_result = wait_request(app, id);
OK(gl_result.status);
uhdk_gl_context_destroy(((const uhdk_gl_context_result *)gl_result.data)->gl_context);
}
uhdk_window_destroy(w);
// Returning with a queued creation must cancel/drain it before native teardown.
OK(uhdk_window_create_async(app, &desc, &id));
}
static void disconnect_main(uhdk_app *app, void *user) {
(void)user;
++entered;
puts("connected");
fflush(stdout);
uint64_t deadline = uhdk_app_get_time_ns(app) + 5000000000ull;
int quit_seen = 0;
while (uhdk_app_get_time_ns(app) < deadline) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 100000000ull, &events));
for (uint64_t i = 0; i < events.len; ++i) {
if (events.ptr[i].type == UHDK_EVENT_QUIT_REQUESTED)
quit_seen = 1;
if (events.ptr[i].type == UHDK_EVENT_STOPPED) {
assert(quit_seen);
return;
}
}
}
abort();
}
static void should_not_run(uhdk_app *app, void *user) {
(void)app;
(void)user;
abort();
}
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;
int passes = disconnect ? 1 : 2;
for (int pass = 0; pass < passes; ++pass) {
uhdk_app_desc desc = {0};
desc.struct_size = sizeof(desc);
desc.abi_version = UHDK_ABI_VERSION;
desc.display_name = text("UHDK Linux test");
char app_id[] = "org.uhdk.LifecycleTest";
desc.application_id = text(app_id);
uhdk_app *app = NULL;
desc.preferred_backend = UHDK_BACKEND_X11;
assert(uhdk_app_create(&desc, &app) == UHDK_STATUS_UNSUPPORTED);
desc.preferred_backend = UHDK_BACKEND_AUTO;
OK(uhdk_app_create(&desc, &app));
memset(app_id, 'x', sizeof(app_id) - 1); // Descriptor bytes are copied.
assert(uhdk_app_get_backend(app) == UHDK_BACKEND_AUTO);
assert(!uhdk_app_has_capability(app, UHDK_CAP_OPENGL));
if (failure) {
assert(uhdk_app_run(app, should_not_run, NULL) != UHDK_STATUS_OK);
assert(uhdk_app_get_backend(app) == UHDK_BACKEND_AUTO);
} else if (disconnect) {
OK(uhdk_app_run(app, disconnect_main, NULL));
} else
OK(uhdk_app_run(app, test_main, windows_only ? &windows_only : NULL));
uhdk_app_destroy(app);
}
assert(entered == (failure ? 0 : passes));
fputs("Linux lifecycle: PASS\n", stderr);
return 0;
}

View File

@ -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')

View File

@ -1,113 +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_app *app) {
uhdk_window *w = window(app);
wait_capability(app, UHDK_CAP_CONTEXT_MENU);
assert(!uhdk_app_has_capability(app, UHDK_CAP_APP_MENU));
uint64_t id;
OK(uhdk_window_set_visible_async(w, 1, &id));
OK(wait_result(app, id).status);
OK(uhdk_window_set_text_input_async(w, 1, &id));
OK(wait_result(app, id).status);
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));
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_async(w, text(title), &id));
// Do not discard the input event that may arrive with title completion.
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_app_get_time_ns(app) < end) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 20000000, &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));
started = uhdk_app_get_time_ns(app);
if (stage == 0)
OK(uhdk_menu_popup_async(menu, w, p->position, &busy));
}
} 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->id == 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->id == 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_app_get_time_ns(app) - started > 100000000ull) {
if (stage == 5)
OK(uhdk_request_cancel(app, popup));
if (stage == 6) {
OK(uhdk_menu_set_item_flags_async(root, POPUP_OPEN, UHDK_MENU_DISABLED, &id));
OK(uhdk_menu_set_item_flags_async(root, 103, 0, &id));
}
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

View File

@ -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())))

View File

@ -1,532 +0,0 @@
#define _GNU_SOURCE
#include "uhdk.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#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_app *app) {
return uhdk_app_get_time_ns(app) + 8000000000ull;
}
static uhdk_request_result wait_result(uhdk_app *app, uint64_t id) {
uint64_t end = deadline(app);
while (uhdk_app_get_time_ns(app) < end) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &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->id == id)
return *r;
}
}
fprintf(stderr, "request %lu timed out\n", (unsigned long)id);
abort();
}
static uhdk_window *window(uhdk_app *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.flags = UHDK_WINDOW_DECORATED | UHDK_WINDOW_RESIZABLE;
uint64_t id;
OK(uhdk_window_create_async(app, &desc, &id));
uhdk_request_result r = wait_result(app, id);
OK(r.status);
return ((const uhdk_window_result *)r.data)->window;
}
static void wait_capability(uhdk_app *app, uint32_t cap) {
uint64_t end = deadline(app);
while (!uhdk_app_has_capability(app, cap) && uhdk_app_get_time_ns(app) < end) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &events));
}
assert(uhdk_app_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_app *app, uhdk_watch *watch, uint32_t flag) {
uint64_t end = deadline(app);
while (uhdk_app_get_time_ns(app) < end) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &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_app *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));
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_app *app) {
wait_capability(app, UHDK_CAP_FILE_DIALOGS);
uhdk_preferences prefs = {0};
prefs.struct_size = sizeof(prefs);
OK(uhdk_app_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.stride_bytes = 8;
image.pixels = (uhdk_bytes){rgba, sizeof(rgba)};
uint64_t id;
OK(uhdk_app_set_icon_async(app, &image, &id));
OK(wait_result(app, id).status);
// A hidden, unfocused window must not commandeer a later user's keystroke.
OK(uhdk_clipboard_write_text_async(app, text("must not replace clipboard"), &id));
assert(wait_result(app, id).status == UHDK_STATUS_UNAVAILABLE);
uhdk_window_destroy(w);
}
static void portals(uhdk_app *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));
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_app_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));
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));
// Allow method submission, then cancel while the mock withholds its reply.
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 100000000, &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));
OK(wait_result(app, id).status);
OK(uhdk_app_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));
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));
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));
assert(wait_result(app, id).status == UHDK_STATUS_CANCELLED);
puts("portal results/cancellation/parent/restart: PASS");
}
static void window_observations(uhdk_app *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);
uint64_t request;
OK(uhdk_window_set_state_async(w, UHDK_WINDOW_MINIMIZED, &request));
assert(wait_result(app, request).status == UHDK_STATUS_UNSUPPORTED);
OK(uhdk_window_set_state_async(w, UHDK_WINDOW_FULLSCREEN, &request));
assert(wait_result(app, request).status == UHDK_STATUS_UNSUPPORTED);
for (int phase = 0; phase < 2; ++phase) {
OK(uhdk_window_set_title_async(
w, text(phase ? "fixture:resume" : "fixture:suspend"), &request
));
int matched = 0, completed = 0;
uint64_t end = deadline(app);
while (uhdk_app_get_time_ns(app) < end && !(matched && completed)) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &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_REQUEST_DONE) {
const uhdk_request_result *r = events.ptr[i].data;
if (r->id == request) {
OK(r->status);
completed = 1;
}
}
}
}
assert(matched && completed);
}
OK(uhdk_window_set_state_async(w, UHDK_WINDOW_MINIMIZED, &request));
OK(wait_result(app, request).status);
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_app *app) {
uhdk_window *w = window(app);
uint64_t request;
OK(uhdk_window_set_text_input_async(w, 1, &request));
OK(wait_result(app, request).status);
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_async(w, text(title), &request));
int released = 0, completed = 0;
unsigned commands = 0;
uint64_t end = deadline(app);
while (uhdk_app_get_time_ns(app) < end && !(released && completed)) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &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_REQUEST_DONE) {
const uhdk_request_result *r = event->data;
if (r->id == request) {
OK(r->status);
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_app *app) {
uhdk_window *w = window(app);
uint64_t id;
OK(uhdk_window_set_text_input_async(w, 1, &id));
OK(wait_result(app, id).status);
OK(uhdk_window_set_drop_enabled_async(w, 1, &id));
OK(wait_result(app, id).status);
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, capture_request = 0;
int published = 0;
uint64_t end = deadline(app);
while (uhdk_app_get_time_ns(app) < end &&
!(key && repeat && commit >= 2 && preedit && pointer && scroll && dropped && copy &&
compose && captured && released)) {
uhdk_event_list events;
OK(uhdk_app_poll_events(app, 50000000, &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_async(
w, UHDK_POINTER_CAPTURE, &capture_request
));
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_REQUEST_DONE:
if (((const uhdk_request_result *)e->data)->id == capture_request)
OK(((const uhdk_request_result *)e->data)->status);
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));
assert(wait_result(app, id).status == UHDK_STATUS_BUFFER_TOO_SMALL);
OK(uhdk_clipboard_read_text_async(app, 100, &id));
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));
uhdk_event_list pause;
OK(uhdk_app_poll_events(app, 100000000, &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));
assert(wait_result(app, id).status == UHDK_STATUS_INVALID_ARGUMENT);
OK(uhdk_clipboard_read_text_async(app, 0, &id));
r = wait_result(app, id);
OK(r.status);
assert(((const uhdk_text *)r.data)->len == 0);
OK(uhdk_clipboard_write_text_async(app, text("local copy"), &id));
OK(wait_result(app, id).status);
OK(uhdk_window_request_focus_async(w, &id));
OK(wait_result(app, id).status);
uhdk_window_destroy(w);
puts("input/IME/clipboard/drop/activation: PASS");
}
#include "menus.c"
#include "popups.c"
static void run(uhdk_app *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_app_desc desc = {0};
desc.struct_size = sizeof(desc);
desc.abi_version = UHDK_ABI_VERSION;
desc.display_name = text("UHDK service tests");
desc.application_id = text("org.uhdk.ServiceTests");
uhdk_app *app;
OK(uhdk_app_create(&desc, &app));
OK(uhdk_app_run(app, run, argv[1]));
uhdk_app_destroy(app);
return 0;
}

View File

@ -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)')

View File

@ -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')

View File

@ -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)

View File

@ -32,10 +32,10 @@ def generate(manifest, font_path):
# Explicit variation axes: regular weight and normal width, in font order.
axes = font.get_variation_axes()
font.set_variation_by_axes([400 if a['name'] == b'Weight' else 100 if a['name'] == b'Width' else a['default'] for a in axes])
codepoints = sorted(set(range(32, 127)) | set(range(160, 256)) | set(map(ord, '–—‘’“”…•€←↑→↓<EFBFBD>')))
header_size = 8 + len(codepoints) * 16
records, pixels = bytearray(), bytearray()
for cp in codepoints:
codepoints = list(range(32, 127))
records = bytearray(12 * len(codepoints))
streams = bytearray()
for index, cp in enumerate(codepoints):
character = chr(cp)
x, y, right, bottom = font.getbbox(character, anchor='ls')
width, height = right - x, bottom - y
@ -43,9 +43,33 @@ def generate(manifest, font_path):
if width and height:
ImageDraw.Draw(image).text((-x, -y), character, font=font, fill=255, anchor='ls')
advance = int(font.getlength(character) + .5)
records += struct.pack('<IIBBbbB3x', cp, header_size + len(pixels), width, height, x, y, advance)
pixels += image.tobytes()
return b'UF16' + struct.pack('<I', len(codepoints)) + records + pixels
samples = [(value + 8) // 17 for value in image.tobytes()]
samples += [0] * (len(samples) % 2)
nibbles = bytes(samples[i] | samples[i + 1] << 4 for i in range(0, len(samples), 2))
encoded = zero_rle(nibbles)
offset = 8 + len(records) + len(streams)
assert offset <= 0xffff and len(encoded) <= 0xffff
struct.pack_into('<HHHBBbbBB', records, index * 12, cp, offset, len(encoded), width, height, x, y, advance, 0)
streams += encoded
fallback = codepoints.index(ord('?'))
result = b'FAP1' + struct.pack('<HH', len(codepoints), fallback) + records + streams
assert len(result) <= 0xffff
return result
def zero_rle(data):
result = bytearray()
index = 0
while index < len(data):
zero = data[index] == 0
length = 1
while index + length < len(data) and (data[index + length] == 0) == zero and length < 128:
length += 1
result.append((0x80 if zero else 0) | (length - 1))
if not zero:
result += data[index:index + length]
index += length
return result
def main():
@ -60,10 +84,10 @@ def main():
if args.regenerate or args.verify_generation:
data = generate(manifest, args.font)
if args.verify_generation:
assert data == (ROOT / 'roboto-16.bin').read_bytes(), 'Generated bitmap differs'
assert data == (ROOT / 'roboto-16.fontatlas').read_bytes(), 'Generated bitmap differs'
else:
(ROOT / 'roboto-16.bin').write_bytes(data)
manifest['generated'] = {'roboto-16.bin': digest(data)}
(ROOT / 'roboto-16.fontatlas').write_bytes(data)
manifest['generated'] = {'roboto-16.fontatlas': digest(data)}
(ROOT / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
for filename, checksum in manifest['generated'].items():
assert digest((ROOT / filename).read_bytes()) == checksum, filename

View File

@ -47,7 +47,12 @@ def generate(root, version):
name = interface.attrib['name'] + '_interface'
symbols.append(f'#define {name} z_uhdk_{name}')
for mode, suffix in [('client-header', '.h'), ('private-code', '.c')]:
subprocess.run(['wayland-scanner', mode, str(xml), str(output / (('wayland-client-protocol' if xml.stem == 'wayland' and mode == 'client-header' else xml.stem) + suffix))], check=True)
target = output / (('wayland-client-protocol' if xml.stem == 'wayland' and mode == 'client-header' else xml.stem) + suffix)
subprocess.run(['wayland-scanner', mode, str(xml), str(target)], check=True)
if mode == 'private-code':
# Rename the descriptors before the scanner's definitions; a -include flag cannot
# name this file because Zig 0.17 build scripts cannot resolve absolute paths.
target.write_text('#include "private-symbols.h"\n' + target.read_text())
(output / 'private-symbols.h').write_text('\n'.join(symbols) + '\n')

48
src/linux/tray.xml Normal file
View File

@ -0,0 +1,48 @@
<!-- UHDK StatusNotifierItem introspection. -->
<node>
<interface name="org.kde.StatusNotifierItem">
<property name="Category" type="s" access="read" />
<property name="Id" type="s" access="read" />
<property name="Title" type="s" access="read" />
<property name="Status" type="s" access="read" />
<property name="WindowId" type="i" access="read" />
<property name="IconName" type="s" access="read" />
<property name="IconPixmap" type="a(iiay)" access="read" />
<property name="OverlayIconName" type="s" access="read" />
<property name="OverlayIconPixmap" type="a(iiay)" access="read" />
<property name="AttentionIconName" type="s" access="read" />
<property name="AttentionIconPixmap" type="a(iiay)" access="read" />
<property name="AttentionMovieName" type="s" access="read" />
<property name="IconThemePath" type="s" access="read" />
<property name="ToolTip" type="(sa(iiay)ss)" access="read" />
<property name="ItemIsMenu" type="b" access="read" />
<property name="Menu" type="o" access="read" />
<method name="Activate">
<arg type="i" direction="in" />
<arg type="i" direction="in" />
</method>
<method name="SecondaryActivate">
<arg type="i" direction="in" />
<arg type="i" direction="in" />
</method>
<method name="ContextMenu">
<arg type="i" direction="in" />
<arg type="i" direction="in" />
</method>
<method name="Scroll">
<arg type="i" direction="in" />
<arg type="s" direction="in" />
</method>
<method name="ProvideXdgActivationToken"><arg type="s" direction="in" /></method>
<signal name="NewTitle" />
<signal name="NewIcon" />
<signal name="NewToolTip" />
</interface>
<interface name="org.freedesktop.DBus.Properties">
<method name="Get"><arg type="s" direction="in" /><arg type="s" direction="in" /><arg type="v" direction="out" /></method>
<method name="GetAll"><arg type="s" direction="in" /><arg type="a{sv}" direction="out" /></method>
<signal name="PropertiesChanged"><arg type="s" /><arg type="a{sv}" /><arg type="as" /></signal>
</interface>
<interface name="org.freedesktop.DBus.Introspectable"><method name="Introspect"><arg type="s" direction="out" /></method></interface>
<interface name="org.freedesktop.DBus.Peer"><method name="Ping" /></interface>
</node>

View File

@ -9,7 +9,7 @@ per-file digests, and the scanner version.
`wayland/COPYING` and individual file notices.
- wayland-protocols 1.45: xdg-shell, xdg-decoration, viewporter, fractional-scale,
cursor-shape, tablet descriptors, text-input-v3, xdg-foreign-v2, activation,
and toplevel icons.
toplevel icons, and pointer-constraints-v1.
License in `wayland-protocols/COPYING` and each XML's copyright element.
- plasma-wayland-protocols revision `382dfabda886d3f2f5c067b22e5a22376685ba78`:
KDE appmenu surface association; MIT license in `plasma-wayland-protocols/MIT.txt`.

View File

@ -30,7 +30,8 @@
"unstable/text-input/text-input-unstable-v3.xml": "protocols/xml/text-input-unstable-v3.xml",
"unstable/xdg-foreign/xdg-foreign-unstable-v2.xml": "protocols/xml/xdg-foreign-unstable-v2.xml",
"staging/xdg-activation/xdg-activation-v1.xml": "protocols/xml/xdg-activation-v1.xml",
"staging/xdg-toplevel-icon/xdg-toplevel-icon-v1.xml": "protocols/xml/xdg-toplevel-icon-v1.xml"
"staging/xdg-toplevel-icon/xdg-toplevel-icon-v1.xml": "protocols/xml/xdg-toplevel-icon-v1.xml",
"unstable/pointer-constraints/pointer-constraints-unstable-v1.xml": "protocols/xml/pointer-constraints-unstable-v1.xml"
}
},
{
@ -158,35 +159,38 @@
"protocols/xml/xdg-toplevel-icon-v1.xml": "791dbfed89280c1b8031689955a03e9b2da55601be3c5854a6198e38cea4978f",
"vendor/xkbcommon/xkbcommon-compat.h": "fb0384a704897c0dcfcc49f021ad38fadbbedc3307d5390f4f0d1019e3d1a4d9",
"protocols/xml/appmenu.xml": "7d0251ee00d3d4bc7ee41e3cd1161beaf68a0c18c4f56f48ff1907a475846022",
"vendor/plasma-wayland-protocols/MIT.txt": "8f25018489d6fe0dec34a352314c38dc146247b7de65735790f4398a92afa84b"
"vendor/plasma-wayland-protocols/MIT.txt": "8f25018489d6fe0dec34a352314c38dc146247b7de65735790f4398a92afa84b",
"protocols/xml/pointer-constraints-unstable-v1.xml": "f980fac900ba1dcfbbe97f588fc17b893926bd2b57624563653a1bfe4d035948"
},
"generated": {
"protocols/generated/appmenu.c": "4705014be761bdc059357f1731e9d68004531b1ec3db1469f4b2f823d0a4bc97",
"protocols/generated/appmenu.c": "666f8b38bd8c2b904ba2853aefe653bdc64d8050390eeb4a8f91cfe88fb710e1",
"protocols/generated/appmenu.h": "9627af04a4dd8f057f06e79761401ced0c4f10191a107510764dc8e57371ea0a",
"protocols/generated/cursor-shape-v1.c": "6027922a5c0a8e0d70ee6948e32aa8231b23cd3f82d323875186b29d36881f78",
"protocols/generated/cursor-shape-v1.c": "1d03922d9d51641a6148af2b41d171d9eff85b9ff209977a8da158318ef8d60b",
"protocols/generated/cursor-shape-v1.h": "87edf9719e935db05a0f5545e20d8bdf67f2c2557676f9d1e697b83cc98d6529",
"protocols/generated/dbus/dbus-arch-deps.h": "87a896df22f7b5e6ec5367cc9b3ed7c77c65b54405a50fd3c7133cd4c6fc3281",
"protocols/generated/fractional-scale-v1.c": "fb40e729ee05acafe996d1261367424b47722be02dbee65c90b3f4972f259dca",
"protocols/generated/fractional-scale-v1.c": "17ccf68784364bdd29578ea137012e5f4944955d7abba1839d586e1abf96647a",
"protocols/generated/fractional-scale-v1.h": "9243e57b2ce11317f6aaa2cd76c0a9f999fb54ced38b880d81891a6ee5dd27df",
"protocols/generated/private-symbols.h": "a1c6d71c84c40c8ea0d2023ec650f219227c8059009f915497f07f06acd9161e",
"protocols/generated/tablet-v2.c": "6ce7899f31da919e1f04a8bd44038df5095b58a98b1178f9aa0a84d0835424c0",
"protocols/generated/pointer-constraints-unstable-v1.c": "8febb7cca002300dd0ddb4e0f509ba1cc6a30599693879c2c2319c0f11648485",
"protocols/generated/pointer-constraints-unstable-v1.h": "ccb950e475f81762a0db3d360c3d9745b18e90c55774688f2ee2628a82fae97e",
"protocols/generated/private-symbols.h": "1a660e3638924ae5eff914b489793f4d3a03962b8665282763844e0574fa04fa",
"protocols/generated/tablet-v2.c": "223972955bc3ba6dfe06af5a222adfde94287840aa01d944564a98f33c92506e",
"protocols/generated/tablet-v2.h": "eff5398428ff21523ae6c745d57081f3bd5c18509c4bf5b18de75d89d58d18cd",
"protocols/generated/text-input-unstable-v3.c": "5de60647b6e122860802d59b547632d4bcf838a443cebeb04429bbb17b5c971b",
"protocols/generated/text-input-unstable-v3.c": "932e28cf368b78196a92e16418737bbb03f641c0d43e8727b79d6f043d34b511",
"protocols/generated/text-input-unstable-v3.h": "051057bc8292414f82c46fb854455616fd212cfffb95222aa5af1e2e2cde3067",
"protocols/generated/viewporter.c": "ee3b669764240a69b4436e8cc7cb2e4d42dc872752df3f34df98851bbcb51d11",
"protocols/generated/viewporter.c": "f19e7c4395ee2254e71455d22c4edd4eefc5c2bfff451c700328f2e4e292a288",
"protocols/generated/viewporter.h": "dbb68745babf07d3d5587b3f3b83a7cb46848f03885bde4b9cd5e71d19114458",
"protocols/generated/wayland-client-protocol.h": "3643fd6aca2f52abcb92a125a0f659c3697268435608a7d3a54e0b614e150f83",
"protocols/generated/wayland-version.h": "9ba722d91f4ae3f2820757785f66247868571bc7014f7a679a22f729daaac79f",
"protocols/generated/wayland.c": "9a3a273b8d007ff2f40906d36734034a0967a67796965d46e0a5873ff0045315",
"protocols/generated/xdg-activation-v1.c": "6cb4f16e1cf504c86f5424c7b9f80c5bd41e446552c34c575808848ac4086c16",
"protocols/generated/wayland.c": "e1b24bad341ec17a0b1bbbcf37324e5960d9e4bb350a08bebe4d3dca5a364028",
"protocols/generated/xdg-activation-v1.c": "849c43a721c77cc61f501ea7a41406c27e5b086affe1e0335c654aa4fffb7502",
"protocols/generated/xdg-activation-v1.h": "c7d669611bcbdd68fea255c102a91f7a686cdb53f58bcbf2b97473edf2221a26",
"protocols/generated/xdg-decoration-unstable-v1.c": "a6cafd5ed52a70e30eacc91e6e230eb8cbed6a6cf790cdcb732acb7e19e51579",
"protocols/generated/xdg-decoration-unstable-v1.c": "ab99cc3a9e7774b69ad24f8e365b4cde1d42d1aa6feccb820b4d451f084795dc",
"protocols/generated/xdg-decoration-unstable-v1.h": "fa1d17dbdfad9e13f35a0d807906926a054edb18cef836cc39063a586d5f6dd4",
"protocols/generated/xdg-foreign-unstable-v2.c": "8f9da32a90206a500a8bf5ea1414f19be5422aa729b3ed0e5eb373a89af15b7c",
"protocols/generated/xdg-foreign-unstable-v2.c": "89b80bcfdc24f6d4d60f040cde3f0d483f0a932c98d876f17315f3db39aaab1c",
"protocols/generated/xdg-foreign-unstable-v2.h": "f384a4e83ce05ccdc0101cb3bb98b8a36496d6c5a34d921a4b448b14d07e0761",
"protocols/generated/xdg-shell.c": "7788ec2e1e8774e4f069d361c450048ccb7e907a204d4ca2d74a64fab7bf7be5",
"protocols/generated/xdg-shell.c": "c39c3fd324a97c921813487f8a0a870b46fec9da6cf3e33c3d5234885d1e74ae",
"protocols/generated/xdg-shell.h": "4b472982e483e37f9e28a1b655aabb5718a6e6a54023dac90fee45bad316ecc9",
"protocols/generated/xdg-toplevel-icon-v1.c": "f6947ef5b94fa2eeae192b857287d676d6c8bfc094594bd2d9bdf8a56b28babc",
"protocols/generated/xdg-toplevel-icon-v1.c": "445221aa349c1d15eb80156848a0b348f891fd55c16be568c6ae2bd067e2f0ab",
"protocols/generated/xdg-toplevel-icon-v1.h": "aa7939d3a1b64c280dd73ed5a4d765a838175fbf6e4ef6eada6750c4826e22b6"
}
}

View File

@ -1,5 +1,6 @@
#import <Cocoa/Cocoa.h>
#import <CoreServices/CoreServices.h>
#import <CoreVideo/CoreVideo.h>
#import <OpenGL/gl3.h>
#include <dlfcn.h>
#include <string.h>
@ -7,6 +8,7 @@
#include <errno.h>
#include <sys/stat.h>
#include <limits.h>
#include <pthread.h>
#include "native.h"
static NSString *str(uhdk_text t) {
@ -28,10 +30,11 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) {
((f & NSEventModifierFlagCommand) ? UHDK_MOD_SUPER : 0) |
((f & NSEventModifierFlagCapsLock) ? UHDK_MOD_CAPS_LOCK : 0);
}
@class ZWindow, ZView, ZGL;
@class ZWindow, ZView, ZGL, ZTray;
@interface ZHost : NSObject <NSApplicationDelegate>
@property(nonatomic) uhdk_app *app;
@property(nonatomic) uhdk_session *app;
@property(nonatomic, strong) NSMutableArray<ZWindow *> *windows;
@property(nonatomic, strong) NSMutableArray<ZTray *> *trays;
@property(nonatomic, strong) NSMutableArray *observers;
@property(nonatomic, strong) NSTimer *workTimer;
@property(nonatomic, strong) NSMenu *fallbackMenu;
@ -45,9 +48,31 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) {
- (void)refreshMenus;
- (void)preferences;
@end
@interface ZGL : NSObject
@interface ZTray : NSObject
@property(nonatomic) uhdk_tray *handle;
@property(nonatomic, strong) NSStatusItem *item;
@property(nonatomic, strong) NSMenu *menu;
- (void)invoke:(id)sender;
- (void)refreshMenu;
@end
typedef struct ZDisplayPacer {
pthread_mutex_t mutex;
pthread_cond_t condition;
uint64_t tick;
} ZDisplayPacer;
@interface ZGL : NSObject {
ZDisplayPacer *_pacer;
uhdk_status _displayLinkStatus;
uint64_t _presentedTick;
}
@property(nonatomic, strong) NSOpenGLContext *context;
@property(nonatomic, weak) ZWindow *owner;
@property(nonatomic) CVDisplayLinkRef displayLink;
@property(nonatomic) GLint swapInterval;
- (uhdk_status)startDisplayLink;
- (void)updateDisplayLink;
- (void)stopDisplayLink;
- (uhdk_status)waitForRefresh;
@end
@interface ZWindow : NSObject <NSWindowDelegate>
@property(nonatomic) uhdk_window *handle;
@ -56,6 +81,7 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) {
@property(nonatomic, strong) ZGL *gl;
@property(nonatomic) uhdk_menu *menu;
@property(nonatomic) uint32_t flags;
@property(nonatomic) uhdk_window_style style;
@property(nonatomic) BOOL resizing;
@property(nonatomic) BOOL fullscreenTransition;
@property(nonatomic) BOOL hasPendingState;
@ -90,7 +116,7 @@ static ZHost *host;
static CFRunLoopSourceRef source;
static void sourcePerform(void *info) {
@autoreleasepool {
z_tick(info);
z_dispatch(info);
}
}
static NSRange safeRange(NSRange r, NSUInteger length) {
@ -132,7 +158,8 @@ static uint32_t physical(unsigned short k) {
[98] = 64, [99] = 60, [100] = 65, [101] = 66, [103] = 68, [105] = 104, [106] = 107,
[107] = 105, [109] = 67, [111] = 69, [113] = 106, [114] = 73, [115] = 74, [116] = 75,
[117] = 76, [118] = 61, [119] = 77, [120] = 59, [121] = 78, [122] = 58, [123] = 80,
[124] = 79, [125] = 81, [126] = 82};
[124] = 79, [125] = 81, [126] = 82
};
return k < 128 ? map[k] : 0;
}
static uhdk_key logical(NSEvent *e) {
@ -180,7 +207,116 @@ static uhdk_key logical(NSEvent *e) {
return CFStringGetLongCharacterForSurrogatePair(hi, [s characterAtIndex:1]);
return hi;
}
static CVReturn displayLinkTick(
CVDisplayLinkRef link,
const CVTimeStamp *now,
const CVTimeStamp *output,
CVOptionFlags flags,
CVOptionFlags *outFlags,
void *user
) {
(void)link;
(void)now;
(void)output;
(void)flags;
(void)outFlags;
// No AppKit, GL calls, or Objective-C ownership on the display-link thread.
ZDisplayPacer *pacer = user;
pthread_mutex_lock(&pacer->mutex);
++pacer->tick;
pthread_cond_signal(&pacer->condition);
pthread_mutex_unlock(&pacer->mutex);
return kCVReturnSuccess;
}
@implementation ZGL
- (uhdk_status)startDisplayLink {
ZDisplayPacer *pacer = calloc(1, sizeof(*pacer));
if (!pacer)
return UHDK_STATUS_OUT_OF_MEMORY;
if (pthread_mutex_init(&pacer->mutex, NULL) != 0) {
free(pacer);
return UHDK_STATUS_OS_ERROR;
}
if (pthread_cond_init(&pacer->condition, NULL) != 0) {
pthread_mutex_destroy(&pacer->mutex);
free(pacer);
return UHDK_STATUS_OS_ERROR;
}
_pacer = pacer;
// A main-run-loop display link would require pumping events inside a frame.
if (CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink) != kCVReturnSuccess ||
CVDisplayLinkSetOutputCallback(_displayLink, displayLinkTick, _pacer) != kCVReturnSuccess)
return UHDK_STATUS_OS_ERROR;
[self updateDisplayLink];
if (_displayLinkStatus != UHDK_STATUS_OK ||
CVDisplayLinkStart(_displayLink) != kCVReturnSuccess)
return UHDK_STATUS_OS_ERROR;
return UHDK_STATUS_OK;
}
- (void)updateDisplayLink {
if (!_displayLink)
return;
NSScreen *screen = self.owner.window.screen;
CGDirectDisplayID display =
screen ? [screen.deviceDescription[@"NSScreenNumber"] unsignedIntValue] : CGMainDisplayID();
if (display == CVDisplayLinkGetCurrentCGDisplay(_displayLink)) {
_displayLinkStatus = UHDK_STATUS_OK;
return;
}
_displayLinkStatus = CVDisplayLinkSetCurrentCGDisplay(_displayLink, display) == kCVReturnSuccess
? UHDK_STATUS_OK
: UHDK_STATUS_OS_ERROR;
}
- (uhdk_status)waitForRefresh {
if (!self.swapInterval)
return UHDK_STATUS_OK;
if (_displayLinkStatus != UHDK_STATUS_OK)
return _displayLinkStatus;
// Use one monotonic deadline so spurious wakeups cannot extend the timeout.
// A sleeping/disconnected display must not leave the main thread blocked.
int64_t deadline = z_io_now(1) + INT64_C(100000000);
pthread_mutex_lock(&_pacer->mutex);
uhdk_status status = UHDK_STATUS_OK;
// Wait only while no refresh has passed since the previous present. The GL driver
// can already have held this frame until a refresh; waiting for yet another tick
// would then show every such frame one refresh late.
while (_pacer->tick == _presentedTick) {
int64_t remaining = deadline - z_io_now(1);
if (remaining <= 0)
break;
struct timespec timeout = {
remaining / INT64_C(1000000000), remaining % INT64_C(1000000000)
};
int error =
pthread_cond_timedwait_relative_np(&_pacer->condition, &_pacer->mutex, &timeout);
if (error == ETIMEDOUT)
break;
if (error != 0) {
status = UHDK_STATUS_OS_ERROR;
break;
}
}
_presentedTick = _pacer->tick;
pthread_mutex_unlock(&_pacer->mutex);
return status;
}
- (void)stopDisplayLink {
// Stop without holding the callback's mutex, before freeing its userdata.
if (_displayLink) {
CVDisplayLinkStop(_displayLink);
CVDisplayLinkRelease(_displayLink);
_displayLink = NULL;
}
if (_pacer) {
pthread_cond_destroy(&_pacer->condition);
pthread_mutex_destroy(&_pacer->mutex);
free(_pacer);
_pacer = NULL;
}
}
- (void)dealloc {
[self stopDisplayLink];
}
@end
@implementation ZView
- (instancetype)initWithFrame:(NSRect)frame {
@ -704,8 +840,9 @@ static uhdk_key logical(NSEvent *e) {
NSUInteger n = 0;
for (NSURL *url in urls) {
const char *path = url.fileSystemRepresentation;
uhdk_file *f = z_file_from_url(host.app, (uhdk_bytes){(const uint8_t *)path, strlen(path)},
(__bridge void *)url);
uhdk_file *f = z_file_from_url(
host.app, (uhdk_bytes){(const uint8_t *)path, strlen(path)}, (__bridge void *)url
);
if (f)
files[n++] = f;
}
@ -752,6 +889,7 @@ static uhdk_key logical(NSEvent *e) {
CGLLockContext(gl);
[self.gl.context update];
CGLUnlockContext(gl);
[self.gl updateDisplayLink];
}
NSRect bounds = self.view.bounds, pixels = [self.view convertRectToBacking:bounds];
uhdk_window_metrics m = {
@ -793,6 +931,10 @@ static uhdk_key logical(NSEvent *e) {
(void)n;
[self metrics];
}
- (void)windowDidChangeScreen:(NSNotification *)n {
(void)n;
[self metrics];
}
- (void)windowDidBecomeKey:(NSNotification *)n {
(void)n;
[host refreshMenus];
@ -808,6 +950,7 @@ static uhdk_key logical(NSEvent *e) {
self.view.capture = NO;
z_event e = {.type = UHDK_EVENT_POINTER_MODE_CHANGED, .window = self.handle};
e.data.pointer_mode = UHDK_POINTER_NORMAL;
e.cycle_end_reason = UHDK_CYCLE_FOCUS_LOST;
z_emit(host.app, &e);
}
[host refreshMenus];
@ -853,6 +996,7 @@ static uhdk_key logical(NSEvent *e) {
@end
@interface ZMenuAction : NSObject
@property(nonatomic) uint64_t command;
@property(nonatomic) uhdk_tray *tray;
@property(nonatomic) uint32_t role;
@property(nonatomic, weak) ZWindow *window;
- (void)invoke:(id)sender;
@ -860,6 +1004,13 @@ static uhdk_key logical(NSEvent *e) {
@implementation ZMenuAction
- (void)invoke:(id)sender {
(void)sender;
if (self.tray) {
uhdk_menu_item item = {0};
item.command_id = self.command;
item.role = self.role;
z_tray_command(self.tray, &item);
return;
}
host.popupSelected = YES;
ZWindow *w = self.window;
if (!w)
@ -924,7 +1075,7 @@ static NSString *shortcut(uhdk_key key) {
encoding:NSUTF32LittleEndianStringEncoding];
return @"";
}
static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
static NSMenu *makeMenuFor(uhdk_menu *menu, ZWindow *window, uhdk_tray *tray) {
NSMenu *native = [[NSMenu alloc] initWithTitle:@""];
native.autoenablesItems = NO;
uint64_t len = 0;
@ -955,14 +1106,19 @@ static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
target.command = item->command_id;
target.role = item->role;
target.window = window;
target.tray = tray;
entry.target = target;
entry.representedObject = target;
if (item->submenu)
entry.submenu = makeMenu(item->submenu, window);
entry.submenu = makeMenuFor(item->submenu, window, tray);
[native addItem:entry];
}
return native;
}
static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
return makeMenuFor(menu, window, NULL);
}
#include "tray.inc"
@implementation ZHost
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
(void)sender;
@ -1012,6 +1168,8 @@ static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
}
uhdk_menu *menu = selected.menu ?: self.appMenu;
NSApp.mainMenu = menu ? makeMenu(menu, selected) : self.fallbackMenu;
for (ZTray *tray in self.trays)
[tray refreshMenu];
}
- (void)preferences {
NSAppearanceName appearance = [NSApp.effectiveAppearance
@ -1021,7 +1179,8 @@ static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
.appearance = [appearance isEqualToString:NSAppearanceNameDarkAqua] ? UHDK_APPEARANCE_DARK
: UHDK_APPEARANCE_LIGHT,
.reduced_motion = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion,
.high_contrast = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast};
.high_contrast = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast
};
z_preferences(self.app, &p);
}
- (void)observeValueForKeyPath:(NSString *)keyPath
@ -1072,9 +1231,13 @@ uhdk_status z_native_file_init(uhdk_file *file, uhdk_bytes path, uhdk_text uri,
g.scoped = [g.url startAccessingSecurityScopedResource];
}
void *owned = g ? (__bridge_retained void *)g : NULL;
uhdk_status status =
z_file_init(file, (uhdk_bytes){(const uint8_t *)native, strlen(native)},
utf8(url.absoluteString), utf8(url.lastPathComponent), owned);
uhdk_status status = z_file_init(
file,
(uhdk_bytes){(const uint8_t *)native, strlen(native)},
utf8(url.absoluteString),
utf8(url.lastPathComponent),
owned
);
if (status != UHDK_STATUS_OK && owned) {
id unused = CFBridgingRelease(owned);
(void)unused;
@ -1107,8 +1270,14 @@ static NSURL *fileURL(uhdk_file *file) {
}
}
@end
static void watchEvents(ConstFSEventStreamRef stream, void *info, size_t count, void *paths,
const FSEventStreamEventFlags flags[], const FSEventStreamEventId ids[]) {
static void watchEvents(
ConstFSEventStreamRef stream,
void *info,
size_t count,
void *paths,
const FSEventStreamEventFlags flags[],
const FSEventStreamEventId ids[]
) {
(void)stream;
(void)ids;
ZWatch *watch = (__bridge ZWatch *)info;
@ -1150,8 +1319,9 @@ static void watchEvents(ConstFSEventStreamRef stream, void *info, size_t count,
if (match && ![path isEqualToString:watch.path]) {
const char *raw = path.fileSystemRepresentation;
if (raw)
child = z_file_from_url(host.app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)},
NULL);
child = z_file_from_url(
host.app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)}, NULL
);
if (child)
e.data.watch.file = child;
}
@ -1160,39 +1330,51 @@ static void watchEvents(ConstFSEventStreamRef stream, void *info, size_t count,
uhdk_file_release(child);
}
}
static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
NSURL *url = fileURL(root);
struct stat st;
if (stat(url.fileSystemRepresentation, &st) != 0)
return errno == ENOENT ? UHDK_STATUS_NOT_FOUND
: errno == EACCES ? UHDK_STATUS_PERMISSION_DENIED
: UHDK_STATUS_OS_ERROR;
char resolved[PATH_MAX];
if (!realpath(url.fileSystemRepresentation, resolved))
return UHDK_STATUS_OS_ERROR;
ZWatch *watch = [ZWatch new];
watch.root = root;
watch.handle = handle;
watch.path = [NSFileManager.defaultManager stringWithFileSystemRepresentation:resolved
length:strlen(resolved)];
watch.directory = S_ISDIR(st.st_mode);
watch.observed = watch.directory ? watch.path : watch.path.stringByDeletingLastPathComponent;
FSEventStreamContext context = {0, (__bridge void *)watch, NULL, NULL, NULL};
watch.stream = FSEventStreamCreate(
NULL, watchEvents, &context, (__bridge CFArrayRef) @[ watch.observed ],
kFSEventStreamEventIdSinceNow, 0.05,
kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes |
kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagNoDefer);
if (!watch.stream)
return UHDK_STATUS_OS_ERROR;
FSEventStreamSetDispatchQueue(watch.stream, dispatch_get_main_queue());
if (!FSEventStreamStart(watch.stream))
return UHDK_STATUS_OS_ERROR;
z_object_set_native(handle, (__bridge_retained void *)watch);
return UHDK_STATUS_OK;
uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **out) {
@autoreleasepool {
NSURL *url = fileURL(root);
struct stat st;
if (stat(url.fileSystemRepresentation, &st) != 0)
return errno == ENOENT ? UHDK_STATUS_NOT_FOUND
: errno == EACCES ? UHDK_STATUS_PERMISSION_DENIED
: UHDK_STATUS_OS_ERROR;
char resolved[PATH_MAX];
if (!realpath(url.fileSystemRepresentation, resolved))
return UHDK_STATUS_OS_ERROR;
ZWatch *watch = [ZWatch new];
watch.root = root;
watch.handle = handle;
watch.path =
[NSFileManager.defaultManager stringWithFileSystemRepresentation:resolved
length:strlen(resolved)];
watch.directory = S_ISDIR(st.st_mode);
watch.observed =
watch.directory ? watch.path : watch.path.stringByDeletingLastPathComponent;
FSEventStreamContext context = {0, (__bridge void *)watch, NULL, NULL, NULL};
watch.stream = FSEventStreamCreate(
NULL,
watchEvents,
&context,
(__bridge CFArrayRef) @[ watch.observed ],
kFSEventStreamEventIdSinceNow,
0.05,
kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes |
kFSEventStreamCreateFlagWatchRoot | kFSEventStreamCreateFlagNoDefer
);
if (!watch.stream)
return UHDK_STATUS_OS_ERROR;
FSEventStreamSetDispatchQueue(watch.stream, dispatch_get_main_queue());
if (!FSEventStreamStart(watch.stream))
return UHDK_STATUS_OS_ERROR;
*out = (__bridge_retained void *)watch;
return UHDK_STATUS_OK;
}
}
void z_native_watch_commit(uhdk_watch *handle, void *prepared) {
z_object_set_native(handle, prepared);
}
static uhdk_status showPanel(uhdk_app *app, const uhdk_file_dialog_desc *d, uint64_t request) {
static uhdk_status showPanel(uhdk_session *app, const uhdk_file_dialog_desc *d, uint64_t request) {
if (host.panel)
return UHDK_STATUS_BUSY;
NSSavePanel *panel;
@ -1244,15 +1426,17 @@ static uhdk_status showPanel(uhdk_app *app, const uhdk_file_dialog_desc *d, uint
NSUInteger n = 0;
for (NSURL *url in urls) {
const char *raw = url.fileSystemRepresentation;
uhdk_file *f = z_file_from_url(app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)},
(__bridge void *)url);
uhdk_file *f = z_file_from_url(
app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)}, (__bridge void *)url
);
if (f)
files[n++] = f;
}
z_request_result result = {0};
result.value.files = (uhdk_file_list){files, n};
z_complete(app, request, n == urls.count ? UHDK_STATUS_OK : UHDK_STATUS_OUT_OF_MEMORY,
&result);
z_complete(
app, request, n == urls.count ? UHDK_STATUS_OK : UHDK_STATUS_OUT_OF_MEMORY, &result
);
for (NSUInteger i = 0; i < n; i++)
uhdk_file_release(files[i]);
};
@ -1263,13 +1447,14 @@ static uhdk_status showPanel(uhdk_app *app, const uhdk_file_dialog_desc *d, uint
[panel beginWithCompletionHandler:completion];
return Z_DEFERRED;
}
uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
uhdk_status z_native_start(uhdk_session *app, uhdk_text name) {
@autoreleasepool {
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
host = [ZHost new];
host.app = app;
host.windows = [NSMutableArray array];
host.trays = [NSMutableArray array];
host.observers = [NSMutableArray array];
NSMenu *menu = [NSMenu new];
NSMenuItem *item = [NSMenuItem new];
@ -1302,46 +1487,63 @@ uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
}]];
[NSApp addObserver:host forKeyPath:@"effectiveAppearance" options:0 context:NULL];
[host preferences];
// Prevent AppKit from interpreting process arguments as document-open requests.
[NSUserDefaults.standardUserDefaults registerDefaults:@{
@"NSTreatUnknownArgumentsAsOpen" : @NO
}];
[NSApp finishLaunching];
return UHDK_STATUS_OK;
}
}
void z_native_run(void) {
void z_native_pump(uint64_t timeout_ns) {
@autoreleasepool {
[NSApp run];
NSDate *until = timeout_ns == UINT64_MAX
? [NSDate distantFuture]
: [NSDate dateWithTimeIntervalSinceNow:(double)timeout_ns / 1e9];
for (unsigned i = 0; i < 64; ++i) {
NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny
untilDate:i == 0 ? until : [NSDate distantPast]
inMode:NSDefaultRunLoopMode
dequeue:YES];
if (!event)
break;
[NSApp sendEvent:event];
}
[NSApp updateWindows];
}
}
void z_native_wake(void) {
if (source) {
CFRunLoopSourceSignal(source);
CFRunLoopWakeUp(CFRunLoopGetMain());
@autoreleasepool {
if (source) {
CFRunLoopSourceSignal(source);
CFRunLoopWakeUp(CFRunLoopGetMain());
// A source can run without nextEvent returning. Post an event as well so
// caller-owned polling observes worker completions promptly.
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
location:NSZeroPoint
modifierFlags:0
timestamp:0
windowNumber:0
context:nil
subtype:0
data1:0
data2:0]
atStart:NO];
}
}
}
void z_native_again(void) {
if (host.workTimer)
if (!host || host.workTimer)
return;
host.workTimer = [NSTimer timerWithTimeInterval:0.001
repeats:NO
block:^(NSTimer *timer) {
(void)timer;
host.workTimer = nil;
z_tick(host.app);
z_dispatch(host.app);
}];
[NSRunLoop.mainRunLoop addTimer:host.workTimer forMode:NSRunLoopCommonModes];
}
void z_native_stop(void) {
[NSApp stop:nil];
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
location:NSZeroPoint
modifierFlags:0
timestamp:0
windowNumber:0
context:nil
subtype:0
data1:0
data2:0]
atStart:YES];
}
void z_native_finish(void) {
@autoreleasepool {
[host.workTimer invalidate];
@ -1384,8 +1586,16 @@ void z_native_destroy(uint32_t kind, void *native) {
if (!native)
return;
@autoreleasepool {
id value = CFBridgingRelease(native);
if (kind == Z_KIND_WINDOW) {
id value = kind == Z_KIND_GL ? (__bridge id)native : CFBridgingRelease(native);
if (kind == Z_KIND_TRAY) {
ZTray *tray = value;
[tray.menu cancelTracking];
tray.item.menu = nil;
tray.item.button.target = nil;
[NSStatusBar.systemStatusBar removeStatusItem:tray.item];
tray.item = nil;
[host.trays removeObject:tray];
} else if (kind == Z_KIND_WINDOW) {
ZWindow *w = value;
if (w.menu) {
uhdk_menu_release(w.menu);
@ -1398,27 +1608,29 @@ void z_native_destroy(uint32_t kind, void *native) {
[host.windows removeObject:w];
[host refreshMenus];
} else if (kind == Z_KIND_GL) {
ZGL *gl = value;
ZWindow *w = value;
ZGL *gl = w.gl;
if (!gl)
return;
[gl stopDisplayLink];
CGLLockContext(gl.context.CGLContextObj);
[gl.context clearDrawable];
CGLUnlockContext(gl.context.CGLContextObj);
gl.owner.gl = nil;
w.gl = nil;
}
}
}
extern void *objc_autoreleasePoolPush(void);
extern void objc_autoreleasePoolPop(void *);
void *z_native_pool_push(void) {
return objc_autoreleasePoolPush();
}
void z_native_pool_pop(void *p) {
objc_autoreleasePoolPop(p);
}
int z_native_is_main_thread(void) {
return NSThread.isMainThread;
}
uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t request,
z_request_result *result) {
uhdk_status z_native_execute(
uhdk_session *app,
const z_command *cmd,
uint64_t request,
z_request_result *result
) {
@autoreleasepool {
@try {
ZWindow *w = cmd->target && z_object_kind(cmd->target) == Z_KIND_WINDOW
@ -1429,14 +1641,16 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
w = [ZWindow new];
w.handle = cmd->target;
w.flags = cmd->window.flags;
w.style = cmd->window.style;
NSWindowStyleMask style = 0;
if (w.flags & UHDK_WINDOW_DECORATED)
if (w.style.decorated)
style |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable;
if (w.flags & UHDK_WINDOW_RESIZABLE)
if (w.style.resizable)
style |= NSWindowStyleMaskResizable;
NSRect rect = NSMakeRect(0, 0, cmd->window.content_size.width,
cmd->window.content_size.height);
NSRect rect = NSMakeRect(
0, 0, cmd->window.content_size.width, cmd->window.content_size.height
);
w.window = [[NSWindow alloc] initWithContentRect:rect
styleMask:style
backing:NSBackingStoreBuffered
@ -1453,8 +1667,10 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
w.window.delegate = w;
w.window.contentMinSize =
NSMakeSize(cmd->window.min_size.width, cmd->window.min_size.height);
w.window.contentMaxSize = NSMakeSize(cmd->window.max_size.width ?: CGFLOAT_MAX,
cmd->window.max_size.height ?: CGFLOAT_MAX);
w.window.contentMaxSize = NSMakeSize(
cmd->window.max_size.width ?: CGFLOAT_MAX,
cmd->window.max_size.height ?: CGFLOAT_MAX
);
if (cmd->window.parent) {
ZWindow *parent = (__bridge ZWindow *)z_object_native(cmd->window.parent);
[parent.window addChildWindow:w.window ordered:NSWindowAbove];
@ -1463,7 +1679,6 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
[w.window makeFirstResponder:w.view];
[host.windows addObject:w];
z_object_set_native(cmd->target, (__bridge_retained void *)w);
result->value.window = cmd->target;
[w metrics];
break;
}
@ -1486,28 +1701,47 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
[w.window orderOut:nil];
[w metrics];
break;
case Z_STYLE: {
NSWindowStyleMask mask = w.window.styleMask;
mask &=
~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable);
if (cmd->style.decorated)
mask |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable;
if (cmd->style.resizable)
mask |= NSWindowStyleMaskResizable;
w.window.styleMask = mask;
w.style = cmd->style;
[w metrics];
break;
}
case Z_FOCUS:
[w.window makeKeyAndOrderFront:nil];
[NSApp activateIgnoringOtherApps:YES];
[w metrics];
break;
case Z_GL: {
if (!(w.flags & UHDK_WINDOW_OPENGL))
if (!(w.flags & Z_WINDOW_OPENGL))
return UHDK_STATUS_INVALID_ARGUMENT;
NSOpenGLPixelFormatAttribute attrs[] = {NSOpenGLPFAOpenGLProfile,
NSOpenGLProfileVersion4_1Core,
NSOpenGLPFAColorSize,
24,
NSOpenGLPFAAlphaSize,
8,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAAccelerated,
0};
NSOpenGLPixelFormatAttribute attrs[] = {
NSOpenGLPFAOpenGLProfile,
NSOpenGLProfileVersion4_1Core,
NSOpenGLPFAColorSize,
24,
NSOpenGLPFAAlphaSize,
8,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAAccelerated,
0
};
NSOpenGLPixelFormat *format =
[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
if (!format)
return UHDK_STATUS_UNSUPPORTED;
ZGL *gl = [ZGL new];
if (!gl)
return UHDK_STATUS_OUT_OF_MEMORY;
gl.context = [[NSOpenGLContext alloc] initWithFormat:format shareContext:nil];
if (!gl.context)
return UHDK_STATUS_OS_ERROR;
@ -1526,9 +1760,14 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
if (major < 3 || (major == 3 && minor < 3) ||
!(profile & GL_CONTEXT_CORE_PROFILE_BIT))
return UHDK_STATUS_UNSUPPORTED;
// Layer-backed windows do not reliably block in flushBuffer.
// Pace with the display link only; never combine two vsync waits.
GLint interval = 0;
[gl.context setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval];
uhdk_status status = [gl startDisplayLink];
if (status != UHDK_STATUS_OK)
return status;
w.gl = gl;
z_object_set_native(cmd->other, (__bridge_retained void *)gl);
result->value.gl_context = cmd->other;
[w metrics];
break;
}
@ -1575,13 +1814,21 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
break;
}
case Z_POINTER:
if (cmd->number == UHDK_POINTER_CONFINED)
return UHDK_STATUS_UNSUPPORTED;
if (w.view.capture == (cmd->number == UHDK_POINTER_CAPTURE))
break;
w.view.capture = cmd->number != 0;
{
z_event e = {.type = UHDK_EVENT_POINTER_MODE_CHANGED, .window = w.handle};
e.data.pointer_mode = (uint32_t)cmd->number;
e.cycle_end_reason = UHDK_CYCLE_CAPTURE_RELEASED;
z_emit(app, &e);
}
break;
case Z_FUNCTION_KEYS:
// This policy controls the Windows native window fallback only.
break;
case Z_TEXT_ENABLE:
w.view.textEnabled = cmd->number != 0;
if (!cmd->number) {
@ -1649,7 +1896,7 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
host.popup = menu;
host.popupID = request;
host.popupSelected = NO;
// Run outside z_tick: tracking runs a nested loop and must service cancellation.
// Run outside z_dispatch: tracking runs a nested loop and must service cancellation.
NSPoint point = NSMakePoint(cmd->point.x, cmd->point.y);
CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{
if (host.popupID != request)
@ -1664,6 +1911,18 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
z_native_wake();
});
CFRunLoopWakeUp(CFRunLoopGetMain());
// A source can run without nextEvent returning. Post an event as well so
// caller-owned polling observes worker completions promptly.
[NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
location:NSZeroPoint
modifierFlags:0
timestamp:0
windowNumber:0
context:nil
subtype:0
data1:0
data2:0]
atStart:NO];
return Z_DEFERRED;
}
case Z_ICON: {
@ -1683,8 +1942,11 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
if (!rep)
return UHDK_STATUS_OUT_OF_MEMORY;
for (uint32_t y = 0; y < i->height; y++)
memcpy(rep.bitmapData + (size_t)y * rep.bytesPerRow,
i->pixels.ptr + y * i->stride_bytes, (size_t)i->width * 4);
memcpy(
rep.bitmapData + (size_t)y * rep.bytesPerRow,
i->pixels.ptr + (size_t)y * i->width * 4,
(size_t)i->width * 4
);
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(i->width, i->height)];
[image addRepresentation:rep];
NSApp.applicationIconImage = image;
@ -1698,12 +1960,6 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
return UHDK_STATUS_OS_ERROR;
break;
}
case Z_WATCH: {
uhdk_status status = createWatch(cmd->target, cmd->other);
if (status == UHDK_STATUS_OK)
result->value.watch = cmd->other;
return status;
}
case Z_DESTROY: {
uint32_t kind = z_object_kind(cmd->target);
void *native = z_object_native(cmd->target);
@ -1728,11 +1984,12 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
}
uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
@autoreleasepool {
ZGL *gl = (__bridge ZGL *)native;
if (op == 4) {
[NSOpenGLContext clearCurrentContext];
return UHDK_STATUS_OK;
}
ZWindow *w = (__bridge ZWindow *)native;
ZGL *gl = w.gl;
if (!gl)
return UHDK_STATUS_UNAVAILABLE;
if (op == 1) {
@ -1746,29 +2003,23 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
CGLUnlockContext(gl.context.CGLContextObj);
return UHDK_STATUS_OK;
}
if (op == 3) {
[gl.context makeCurrentContext];
return UHDK_STATUS_OK;
}
if (NSOpenGLContext.currentContext != gl.context)
return UHDK_STATUS_UNAVAILABLE;
if (op == 5) {
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
((uint32_t *)out)[0] = major;
((uint32_t *)out)[1] = minor;
} else if (op == 6)
if (op == 6) {
uhdk_status status = [gl waitForRefresh];
if (status != UHDK_STATUS_OK)
return status;
[gl.context flushBuffer];
else if (op == 7)
[gl.context setValues:out forParameter:NSOpenGLContextParameterSwapInterval];
} else if (op == 7)
gl.swapInterval = *(GLint *)out;
else
return UHDK_STATUS_INVALID_ARGUMENT;
return UHDK_STATUS_OK;
}
}
uhdk_status z_native_gl_proc(void *native, uhdk_text name, uhdk_gl_proc *out) {
ZGL *gl = (__bridge ZGL *)native;
ZWindow *w = (__bridge ZWindow *)native;
ZGL *gl = w.gl;
if (NSOpenGLContext.currentContext != gl.context)
return UHDK_STATUS_UNAVAILABLE;
char symbol[256];

79
src/macos/tray.inc Normal file
View File

@ -0,0 +1,79 @@
/* AppKit status items share the library's retained menu model and event queue. */
@implementation ZTray
- (void)refreshMenu {
const uhdk_tray_desc *desc = z_tray_desc(self.handle);
[self.menu cancelTracking];
self.menu = desc->menu ? makeMenuFor(desc->menu, nil, self.handle) : nil;
self.item.menu = desc->menu_on_primary ? self.menu : nil;
}
- (void)invoke:(id)sender {
(void)sender;
if (NSApp.currentEvent.type == NSEventTypeRightMouseUp) {
if (self.menu)
[self.menu popUpMenuPositioningItem:nil
atLocation:NSMakePoint(0, self.item.button.bounds.size.height)
inView:self.item.button];
} else {
z_tray_activate(
self.handle,
NSApp.currentEvent.type == NSEventTypeOtherMouseUp ? UHDK_TRAY_ACTIVATE_SECONDARY
: UHDK_TRAY_ACTIVATE_PRIMARY
);
}
}
@end
uhdk_status z_native_tray_update(uhdk_tray *handle, const uhdk_tray_desc *desc) {
@autoreleasepool {
const uhdk_image *i = &desc->icon;
NSBitmapImageRep *rep =
[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:i->width
pixelsHigh:i->height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bitmapFormat:NSBitmapFormatAlphaNonpremultiplied
bytesPerRow:i->width * 4
bitsPerPixel:32];
if (!rep)
return UHDK_STATUS_OUT_OF_MEMORY;
for (uint32_t y = 0; y < i->height; y++)
memcpy(
rep.bitmapData + (size_t)y * rep.bytesPerRow,
i->pixels.ptr + (size_t)y * i->width * 4,
(size_t)i->width * 4
);
CGFloat height = 18;
NSSize size = NSMakeSize(height * i->width / i->height, height);
rep.size = size;
NSImage *image = [[NSImage alloc] initWithSize:size];
[image addRepresentation:rep];
image.template = desc->template_image != 0;
ZTray *tray = (__bridge ZTray *)z_object_native(handle);
if (!tray) {
tray = [ZTray new];
tray.handle = handle;
tray.item =
[NSStatusBar.systemStatusBar statusItemWithLength:NSVariableStatusItemLength];
if (!tray.item)
return UHDK_STATUS_UNAVAILABLE;
tray.item.autosaveName = str(desc->id);
tray.item.button.target = tray;
tray.item.button.action = @selector(invoke:);
[tray.item.button sendActionOn:NSEventMaskLeftMouseUp | NSEventMaskRightMouseUp |
NSEventMaskOtherMouseUp];
[host.trays addObject:tray];
z_object_set_native(handle, (__bridge_retained void *)tray);
}
tray.item.button.image = image;
tray.item.button.toolTip = str(desc->tooltip.len ? desc->tooltip : desc->title);
[tray.item.button setAccessibilityLabel:str(desc->title)];
[tray refreshMenu];
tray.item.visible = !desc->hidden;
z_tray_state(handle, (uhdk_bool)tray.item.visible, UHDK_STATUS_OK);
return UHDK_STATUS_OK;
}
}

View File

@ -1,20 +1,36 @@
#ifndef UHDK_PRIVATE_NATIVE_H
#define UHDK_PRIVATE_NATIVE_H
/* z_ = Zig bridge. This prefix identifies private bridge functions, types,
* and helpers connecting the Zig runtime with native platform code.
* Public C API symbols use uhdk_ instead. */
#define UHDK_ENABLE_NATIVE
#include "uhdk.h"
#include <stddef.h>
#include "edit_keys.h"
#include "function_keys.h"
enum {
Z_WINDOW_OPENGL = 1u << 3
};
typedef struct z_window_desc {
uint32_t struct_size;
uint32_t flags;
uhdk_window_style style;
uhdk_text title;
uhdk_size content_size;
uhdk_size min_size;
uhdk_size max_size;
uhdk_window *parent;
} z_window_desc;
int32_t z_gl_load(void *context, uhdk_gl_functions *functions);
/* Private producer storage. Converted to public pointer payloads at poll. */
typedef struct z_request_result {
uhdk_request_id id;
uint64_t tag;
uhdk_request_kind kind;
uhdk_status status;
uhdk_text diagnostic; /* Optional; for humans, never parse for logic. */
union {
uhdk_file_list files; /* FILE_DIALOG */
uhdk_text text; /* CLIPBOARD_TEXT */
uhdk_window *window;
uhdk_gl_context *gl_context;
uhdk_watch *watch;
uhdk_bytes bytes;
uhdk_file_info info;
@ -26,6 +42,8 @@ typedef struct z_event {
uhdk_event_type type;
uint64_t time_ns;
uint64_t input_id; /* Correlates raw key and native edit/text; zero for non-input. */
uint64_t cycle_id; /* Assigned by the shared event pipeline. */
uhdk_cycle_end_reason cycle_end_reason; /* Native cause for capture release/loss. */
uhdk_window *window;
union {
uhdk_bool active;
@ -40,8 +58,11 @@ typedef struct z_event {
uhdk_edit_event edit;
uhdk_drop_files_event drop_files;
uhdk_menu_event menu;
uhdk_tray_event tray;
uhdk_tray_state_event tray_state;
uhdk_watch_event watch;
z_request_result request;
uhdk_cycle_end_event cycle_end;
} data;
} z_event;
@ -58,10 +79,12 @@ enum {
Z_SIZE,
Z_STATE,
Z_VISIBLE,
Z_STYLE,
Z_FOCUS,
Z_GL,
Z_CURSOR,
Z_POINTER,
Z_FUNCTION_KEYS,
Z_TEXT_ENABLE,
Z_TEXT_STATE,
Z_TEXT_CANCEL,
@ -81,10 +104,12 @@ enum {
};
enum {
Z_KIND_WINDOW = 1,
/* Native-only discriminator for destroying a window's GL state. */
Z_KIND_GL,
Z_KIND_FILE,
Z_KIND_MENU,
Z_KIND_WATCH
Z_KIND_WATCH,
Z_KIND_TRAY
};
#define Z_DEFERRED UINT32_MAX
/* Generic command storage is private, never exposed to consumers. */
@ -98,40 +123,94 @@ typedef struct z_command {
uhdk_bytes bytes;
uhdk_size size;
uhdk_point point;
uhdk_window_desc window;
z_window_desc window;
uhdk_window_style style;
uhdk_text_state text_state;
uhdk_file_dialog_desc dialog;
uhdk_image image;
} z_command;
uhdk_status z_native_start(uhdk_app *, uhdk_text name);
void z_native_run(void);
uhdk_status z_native_start(uhdk_session *, uhdk_text name);
void z_native_pump(uint64_t timeout_ns);
/* File-worker preparation; native registration is committed on platform main. */
uhdk_status z_native_watch_prepare(uhdk_file *, uhdk_watch *, void **out);
void z_native_watch_commit(uhdk_watch *, void *prepared);
void z_native_wake(void);
void z_native_again(void);
void z_native_stop(void);
void z_native_finish(void);
uhdk_status z_native_execute(uhdk_app *, const z_command *, uint64_t, z_request_result *);
uhdk_status z_native_execute(uhdk_session *, const z_command *, uint64_t, z_request_result *);
void z_native_cancel(uint64_t);
void z_native_destroy(uint32_t kind, void *native);
void *z_native_pool_push(void);
void z_native_pool_pop(void *);
uhdk_status z_native_gl(void *context, uint32_t op, void *out);
uhdk_status z_native_gl_proc(void *context, uhdk_text, uhdk_gl_proc *);
void z_native_handles(void *, uhdk_native_window *);
uhdk_status z_native_tray_update(uhdk_tray *, const uhdk_tray_desc *);
const uhdk_tray_desc *z_tray_desc(uhdk_tray *);
void z_tray_state(uhdk_tray *, uhdk_bool available, uhdk_status);
void z_tray_activate(uhdk_tray *, uhdk_tray_activation);
void z_tray_command(uhdk_tray *, const uhdk_menu_item *);
/* Pure path conversions (no file access); copied synchronously by z_file_init. */
uhdk_status z_native_file_init(uhdk_file *, uhdk_bytes path, uhdk_text uri, void *grant);
/* Minimal blocking runtime used by the Zig scheduler. */
int64_t z_io_now(uint32_t clock);
void z_io_wait(const uint32_t *address, uint32_t expected, uint64_t timeout_ns, uhdk_bool timed);
void z_io_wake(const uint32_t *address, uint32_t max_waiters);
enum {
Z_FILE_OK,
Z_FILE_NOT_FOUND,
Z_FILE_ACCESS_DENIED,
Z_FILE_NOT_REGULAR,
Z_FILE_INVALID_PATH,
Z_FILE_OUT_OF_MEMORY,
Z_FILE_OS_ERROR
};
enum {
Z_FILE_TYPE_REGULAR,
Z_FILE_TYPE_DIRECTORY,
Z_FILE_TYPE_OTHER
};
typedef struct z_file_metadata {
uint64_t size;
int64_t modified_ns;
uint32_t type;
} z_file_metadata;
uint32_t z_file_metadata_read(uhdk_bytes path, uhdk_bool follow, z_file_metadata *out);
uint32_t z_file_reader_open(uhdk_bytes path, void **out);
uint32_t z_file_reader_read(
void *reader,
uint64_t offset,
void *buffer,
size_t capacity,
size_t *out
);
void z_file_reader_close(void *reader);
uint32_t z_file_writer_open(uhdk_bytes path, void **out);
uint32_t z_file_writer_write(
void *writer,
uint64_t offset,
const void *buffer,
size_t length,
size_t *out
);
uint32_t z_file_writer_commit(void *writer);
void z_file_writer_close(void *writer);
/* Zig callbacks, always return before native temporary spans expire. */
void z_tick(uhdk_app *);
void z_emit(uhdk_app *, const z_event *);
void z_complete(uhdk_app *, uint64_t, uhdk_status, const z_request_result *);
void z_dispatch(uhdk_session *);
void z_emit(uhdk_session *, const z_event *);
void z_complete(uhdk_session *, uint64_t, uhdk_status, const z_request_result *);
void *z_object_native(void *);
void z_object_set_native(void *, void *);
uint32_t z_object_kind(void *);
uhdk_app *z_object_app(void *);
uhdk_file *z_file_from_url(uhdk_app *, uhdk_bytes path, void *grant);
uhdk_session *z_object_app(void *);
uhdk_file *z_file_from_url(uhdk_session *, uhdk_bytes path, void *grant);
uhdk_status z_file_init(uhdk_file *, uhdk_bytes, uhdk_text uri, uhdk_text display, void *grant);
uhdk_bytes z_file_path(uhdk_file *);
const uhdk_menu_item *z_menu_items(uhdk_menu *, uint64_t *len);
void z_metrics(uhdk_window *, const uhdk_window_metrics *);
void z_preferences(uhdk_app *, const uhdk_preferences *);
void z_preferences(uhdk_session *, const uhdk_preferences *);
int z_native_is_main_thread(void);
/* Wake application polls on a fatal native-loop error. */
void z_native_failed(uhdk_session *app, uhdk_status status);
#endif

684
src/platform_io.c Normal file
View File

@ -0,0 +1,684 @@
#ifndef _WIN32
#define _GNU_SOURCE
#define _DARWIN_C_SOURCE
#endif
#include "native.h"
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
typedef struct z_file_reader {
HANDLE handle;
} z_file_reader;
typedef struct z_file_writer {
HANDLE handle;
WCHAR *target;
WCHAR *temporary;
} z_file_writer;
static volatile LONG temporary_id;
static WCHAR *wide_path(uhdk_bytes path) {
if (path.len > INT_MAX || (path.len != 0 && !path.ptr))
return NULL;
int count = MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, (const char *)path.ptr, (int)path.len, NULL, 0
);
if (count <= 0)
return NULL;
WCHAR *result = malloc(((size_t)count + 1) * sizeof(*result));
if (!result) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return NULL;
}
if (MultiByteToWideChar(
CP_UTF8, MB_ERR_INVALID_CHARS, (const char *)path.ptr, (int)path.len, result, count
) != count) {
free(result);
return NULL;
}
result[count] = 0;
return result;
}
static uint32_t windows_error(DWORD error) {
switch (error) {
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_INVALID_NAME:
return Z_FILE_NOT_FOUND;
case ERROR_NO_UNICODE_TRANSLATION:
return Z_FILE_INVALID_PATH;
case ERROR_ACCESS_DENIED:
case ERROR_SHARING_VIOLATION:
case ERROR_WRITE_PROTECT:
return Z_FILE_ACCESS_DENIED;
case ERROR_NOT_ENOUGH_MEMORY:
case ERROR_OUTOFMEMORY:
return Z_FILE_OUT_OF_MEMORY;
default:
return Z_FILE_OS_ERROR;
}
}
static int metadata_from_handle(HANDLE handle, z_file_metadata *out) {
BY_HANDLE_FILE_INFORMATION info;
if (!GetFileInformationByHandle(handle, &info))
return 0;
ULARGE_INTEGER size = {.LowPart = info.nFileSizeLow, .HighPart = info.nFileSizeHigh};
ULARGE_INTEGER modified = {
.LowPart = info.ftLastWriteTime.dwLowDateTime,
.HighPart = info.ftLastWriteTime.dwHighDateTime
};
const uint64_t epoch_100ns = UINT64_C(116444736000000000);
out->size = size.QuadPart;
out->modified_ns =
modified.QuadPart >= epoch_100ns ? (int64_t)((modified.QuadPart - epoch_100ns) * 100) : 0;
out->type = (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? Z_FILE_TYPE_DIRECTORY
: Z_FILE_TYPE_REGULAR;
return 1;
}
int64_t z_io_now(uint32_t clock) {
if (clock == 3 || clock == 4) {
FILETIME created, exited, kernel, user;
BOOL ok = clock == 3
? GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)
: GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user);
if (!ok)
return 0;
ULARGE_INTEGER k = {.LowPart = kernel.dwLowDateTime, .HighPart = kernel.dwHighDateTime};
ULARGE_INTEGER u = {.LowPart = user.dwLowDateTime, .HighPart = user.dwHighDateTime};
return (int64_t)((k.QuadPart + u.QuadPart) * 100);
}
if (clock == 0) {
FILETIME value;
GetSystemTimePreciseAsFileTime(&value);
ULARGE_INTEGER ticks = {.LowPart = value.dwLowDateTime, .HighPart = value.dwHighDateTime};
return (int64_t)((ticks.QuadPart - UINT64_C(116444736000000000)) * 100);
}
LARGE_INTEGER frequency, counter;
if (!QueryPerformanceFrequency(&frequency) || !QueryPerformanceCounter(&counter))
return 0;
uint64_t seconds = (uint64_t)counter.QuadPart / (uint64_t)frequency.QuadPart;
uint64_t remainder = (uint64_t)counter.QuadPart % (uint64_t)frequency.QuadPart;
return (int64_t)(seconds * UINT64_C(1000000000) +
remainder * UINT64_C(1000000000) / (uint64_t)frequency.QuadPart);
}
void z_io_wait(const uint32_t *address, uint32_t expected, uint64_t timeout_ns, uhdk_bool timed) {
DWORD timeout = INFINITE;
if (timed) {
uint64_t milliseconds = (timeout_ns + UINT64_C(999999)) / UINT64_C(1000000);
timeout = milliseconds >= INFINITE ? INFINITE - 1 : (DWORD)milliseconds;
}
(void)WaitOnAddress((volatile VOID *)address, &expected, sizeof(expected), timeout);
}
void z_io_wake(const uint32_t *address, uint32_t max_waiters) {
if (max_waiters == 1)
WakeByAddressSingle((PVOID)address);
else
WakeByAddressAll((PVOID)address);
}
uint32_t z_file_metadata_read(uhdk_bytes path, uhdk_bool follow, z_file_metadata *out) {
WCHAR *wide = wide_path(path);
if (!wide)
return windows_error(GetLastError());
DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
if (!follow)
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
HANDLE handle = CreateFileW(
wide,
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
flags,
NULL
);
free(wide);
if (handle == INVALID_HANDLE_VALUE)
return windows_error(GetLastError());
BY_HANDLE_FILE_INFORMATION raw;
uint32_t status = Z_FILE_OK;
if (!GetFileInformationByHandle(handle, &raw))
status = windows_error(GetLastError());
else if (!follow && (raw.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
status = Z_FILE_NOT_REGULAR;
else if (!metadata_from_handle(handle, out))
status = windows_error(GetLastError());
CloseHandle(handle);
return status;
}
uint32_t z_file_reader_open(uhdk_bytes path, void **out) {
*out = NULL;
WCHAR *wide = wide_path(path);
if (!wide)
return windows_error(GetLastError());
HANDLE handle = CreateFileW(
wide,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
NULL
);
free(wide);
if (handle == INVALID_HANDLE_VALUE)
return windows_error(GetLastError());
BY_HANDLE_FILE_INFORMATION info;
if (!GetFileInformationByHandle(handle, &info)) {
uint32_t status = windows_error(GetLastError());
CloseHandle(handle);
return status;
}
if ((info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != 0) {
CloseHandle(handle);
return Z_FILE_NOT_REGULAR;
}
z_file_reader *reader = malloc(sizeof(*reader));
if (!reader) {
CloseHandle(handle);
return Z_FILE_OUT_OF_MEMORY;
}
reader->handle = handle;
*out = reader;
return Z_FILE_OK;
}
uint32_t z_file_reader_read(
void *opaque,
uint64_t offset,
void *buffer,
size_t capacity,
size_t *out
) {
z_file_reader *reader = opaque;
LARGE_INTEGER position;
position.QuadPart = (LONGLONG)offset;
if (!SetFilePointerEx(reader->handle, position, NULL, FILE_BEGIN))
return windows_error(GetLastError());
DWORD count = 0;
DWORD amount = capacity > MAXDWORD ? MAXDWORD : (DWORD)capacity;
if (!ReadFile(reader->handle, buffer, amount, &count, NULL)) {
DWORD error = GetLastError();
if (error != ERROR_HANDLE_EOF)
return windows_error(error);
}
*out = count;
return Z_FILE_OK;
}
void z_file_reader_close(void *opaque) {
if (!opaque)
return;
z_file_reader *reader = opaque;
CloseHandle(reader->handle);
free(reader);
}
uint32_t z_file_writer_open(uhdk_bytes path, void **out) {
*out = NULL;
WCHAR *target = wide_path(path);
if (!target)
return windows_error(GetLastError());
DWORD attributes = GetFileAttributesW(target);
if (attributes != INVALID_FILE_ATTRIBUTES) {
if (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) {
free(target);
return Z_FILE_NOT_REGULAR;
}
if (attributes & FILE_ATTRIBUTE_READONLY) {
free(target);
return Z_FILE_ACCESS_DENIED;
}
} else if (GetLastError() != ERROR_FILE_NOT_FOUND && GetLastError() != ERROR_PATH_NOT_FOUND) {
uint32_t status = windows_error(GetLastError());
free(target);
return status;
}
size_t target_len = wcslen(target);
WCHAR *temporary = malloc((target_len + 48) * sizeof(*temporary));
z_file_writer *writer = malloc(sizeof(*writer));
if (!temporary || !writer) {
free(temporary);
free(writer);
free(target);
return Z_FILE_OUT_OF_MEMORY;
}
HANDLE handle = INVALID_HANDLE_VALUE;
for (unsigned attempt = 0; attempt < 128; ++attempt) {
LONG id = InterlockedIncrement(&temporary_id);
_snwprintf(
temporary,
target_len + 48,
L"%ls.uhdk-%lu-%ld",
target,
(unsigned long)GetCurrentProcessId(),
(long)id
);
temporary[target_len + 47] = 0;
handle = CreateFileW(
temporary, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL
);
if (handle != INVALID_HANDLE_VALUE || GetLastError() != ERROR_FILE_EXISTS)
break;
}
if (handle == INVALID_HANDLE_VALUE) {
uint32_t status = windows_error(GetLastError());
free(temporary);
free(writer);
free(target);
return status;
}
writer->handle = handle;
writer->target = target;
writer->temporary = temporary;
*out = writer;
return Z_FILE_OK;
}
uint32_t z_file_writer_write(
void *opaque,
uint64_t offset,
const void *buffer,
size_t length,
size_t *out
) {
z_file_writer *writer = opaque;
LARGE_INTEGER position;
position.QuadPart = (LONGLONG)offset;
if (!SetFilePointerEx(writer->handle, position, NULL, FILE_BEGIN))
return windows_error(GetLastError());
DWORD count = 0;
DWORD amount = length > MAXDWORD ? MAXDWORD : (DWORD)length;
if (!WriteFile(writer->handle, buffer, amount, &count, NULL))
return windows_error(GetLastError());
*out = count;
return Z_FILE_OK;
}
uint32_t z_file_writer_commit(void *opaque) {
z_file_writer *writer = opaque;
if (!FlushFileBuffers(writer->handle))
return windows_error(GetLastError());
CloseHandle(writer->handle);
writer->handle = INVALID_HANDLE_VALUE;
if (!MoveFileExW(
writer->temporary, writer->target, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH
))
return windows_error(GetLastError());
free(writer->temporary);
free(writer->target);
free(writer);
return Z_FILE_OK;
}
void z_file_writer_close(void *opaque) {
if (!opaque)
return;
z_file_writer *writer = opaque;
if (writer->handle != INVALID_HANDLE_VALUE)
CloseHandle(writer->handle);
DeleteFileW(writer->temporary);
free(writer->temporary);
free(writer->target);
free(writer);
}
#else
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdatomic.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#ifdef __linux__
#include <linux/futex.h>
#include <sys/syscall.h>
#endif
typedef struct z_file_reader {
int fd;
} z_file_reader;
typedef struct z_file_writer {
int fd;
char *target;
char *temporary;
} z_file_writer;
static _Atomic uint64_t temporary_id;
#ifdef __APPLE__
#define WAIT_BUCKETS 64
typedef struct wait_bucket {
pthread_mutex_t mutex;
pthread_cond_t condition;
} wait_bucket;
static wait_bucket wait_buckets[WAIT_BUCKETS];
static pthread_once_t wait_once = PTHREAD_ONCE_INIT;
static void initialize_wait_buckets(void) {
for (size_t i = 0; i < WAIT_BUCKETS; ++i) {
pthread_mutex_init(&wait_buckets[i].mutex, NULL);
pthread_cond_init(&wait_buckets[i].condition, NULL);
}
}
static wait_bucket *bucket_for(const uint32_t *address) {
pthread_once(&wait_once, initialize_wait_buckets);
return &wait_buckets[((uintptr_t)address >> 2) % WAIT_BUCKETS];
}
#endif
static char *narrow_path(uhdk_bytes path) {
if ((path.len != 0 && !path.ptr) || path.len > SIZE_MAX - 1 ||
memchr(path.ptr, 0, (size_t)path.len)) {
errno = EINVAL;
return NULL;
}
char *result = malloc((size_t)path.len + 1);
if (!result) {
errno = ENOMEM;
return NULL;
}
memcpy(result, path.ptr, (size_t)path.len);
result[path.len] = 0;
return result;
}
static uint32_t posix_error(int error) {
switch (error) {
case ENOENT:
case ENOTDIR:
return Z_FILE_NOT_FOUND;
case EACCES:
case EPERM:
case EROFS:
return Z_FILE_ACCESS_DENIED;
case ELOOP:
return Z_FILE_NOT_REGULAR;
case ENAMETOOLONG:
case EINVAL:
return Z_FILE_INVALID_PATH;
case ENOMEM:
return Z_FILE_OUT_OF_MEMORY;
default:
return Z_FILE_OS_ERROR;
}
}
static void metadata_from_stat(const struct stat *info, z_file_metadata *out) {
out->size = info->st_size < 0 ? 0 : (uint64_t)info->st_size;
#ifdef __APPLE__
out->modified_ns =
(int64_t)info->st_mtimespec.tv_sec * INT64_C(1000000000) + info->st_mtimespec.tv_nsec;
#else
out->modified_ns = (int64_t)info->st_mtim.tv_sec * INT64_C(1000000000) + info->st_mtim.tv_nsec;
#endif
out->type = S_ISREG(info->st_mode) ? Z_FILE_TYPE_REGULAR
: S_ISDIR(info->st_mode) ? Z_FILE_TYPE_DIRECTORY
: Z_FILE_TYPE_OTHER;
}
int64_t z_io_now(uint32_t clock) {
clockid_t id;
switch (clock) {
case 0:
id = CLOCK_REALTIME;
break;
case 3:
id = CLOCK_PROCESS_CPUTIME_ID;
break;
case 4:
id = CLOCK_THREAD_CPUTIME_ID;
break;
default:
id = CLOCK_MONOTONIC;
break;
}
struct timespec value;
if (clock_gettime(id, &value) != 0)
return 0;
return (int64_t)value.tv_sec * INT64_C(1000000000) + value.tv_nsec;
}
void z_io_wait(const uint32_t *address, uint32_t expected, uint64_t timeout_ns, uhdk_bool timed) {
#ifdef __linux__
struct timespec timeout;
struct timespec *timeout_ptr = NULL;
if (timed) {
timeout.tv_sec = (time_t)(timeout_ns / UINT64_C(1000000000));
timeout.tv_nsec = (long)(timeout_ns % UINT64_C(1000000000));
timeout_ptr = &timeout;
}
(void)syscall(SYS_futex, address, FUTEX_WAIT_PRIVATE, expected, timeout_ptr, NULL, 0);
#else
wait_bucket *bucket = bucket_for(address);
pthread_mutex_lock(&bucket->mutex);
if (atomic_load_explicit((const _Atomic uint32_t *)address, memory_order_acquire) == expected) {
if (!timed) {
(void)pthread_cond_wait(&bucket->condition, &bucket->mutex);
} else {
struct timespec deadline;
clock_gettime(CLOCK_REALTIME, &deadline);
uint64_t ns = (uint64_t)deadline.tv_nsec + timeout_ns;
deadline.tv_sec += (time_t)(ns / UINT64_C(1000000000));
deadline.tv_nsec = (long)(ns % UINT64_C(1000000000));
(void)pthread_cond_timedwait(&bucket->condition, &bucket->mutex, &deadline);
}
}
pthread_mutex_unlock(&bucket->mutex);
#endif
}
void z_io_wake(const uint32_t *address, uint32_t max_waiters) {
#ifdef __linux__
int count = max_waiters > INT_MAX ? INT_MAX : (int)max_waiters;
(void)syscall(SYS_futex, address, FUTEX_WAKE_PRIVATE, count, NULL, NULL, 0);
#else
wait_bucket *bucket = bucket_for(address);
pthread_mutex_lock(&bucket->mutex);
if (max_waiters == 1)
pthread_cond_signal(&bucket->condition);
else
pthread_cond_broadcast(&bucket->condition);
pthread_mutex_unlock(&bucket->mutex);
#endif
}
uint32_t z_file_metadata_read(uhdk_bytes path, uhdk_bool follow, z_file_metadata *out) {
char *name = narrow_path(path);
if (!name)
return posix_error(errno);
struct stat info;
int rc = follow ? stat(name, &info) : lstat(name, &info);
free(name);
if (rc != 0)
return posix_error(errno);
metadata_from_stat(&info, out);
return Z_FILE_OK;
}
uint32_t z_file_reader_open(uhdk_bytes path, void **out) {
*out = NULL;
char *name = narrow_path(path);
if (!name)
return posix_error(errno);
int fd = open(name, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
free(name);
if (fd < 0)
return posix_error(errno);
struct stat info;
if (fstat(fd, &info) != 0) {
uint32_t status = posix_error(errno);
close(fd);
return status;
}
if (!S_ISREG(info.st_mode)) {
close(fd);
return Z_FILE_NOT_REGULAR;
}
z_file_reader *reader = malloc(sizeof(*reader));
if (!reader) {
close(fd);
return Z_FILE_OUT_OF_MEMORY;
}
reader->fd = fd;
*out = reader;
return Z_FILE_OK;
}
uint32_t z_file_reader_read(
void *opaque,
uint64_t offset,
void *buffer,
size_t capacity,
size_t *out
) {
z_file_reader *reader = opaque;
ssize_t count;
do {
count = pread(reader->fd, buffer, capacity, (off_t)offset);
} while (count < 0 && errno == EINTR);
if (count < 0)
return posix_error(errno);
*out = (size_t)count;
return Z_FILE_OK;
}
void z_file_reader_close(void *opaque) {
if (!opaque)
return;
z_file_reader *reader = opaque;
close(reader->fd);
free(reader);
}
uint32_t z_file_writer_open(uhdk_bytes path, void **out) {
*out = NULL;
char *target = narrow_path(path);
if (!target)
return posix_error(errno);
struct stat existing;
mode_t mode = 0600;
if (lstat(target, &existing) == 0) {
if (!S_ISREG(existing.st_mode)) {
free(target);
return Z_FILE_NOT_REGULAR;
}
mode = existing.st_mode & 0777;
} else if (errno != ENOENT) {
uint32_t status = posix_error(errno);
free(target);
return status;
}
size_t target_len = strlen(target);
char *temporary = malloc(target_len + 64);
z_file_writer *writer = malloc(sizeof(*writer));
if (!temporary || !writer) {
free(temporary);
free(writer);
free(target);
return Z_FILE_OUT_OF_MEMORY;
}
int fd = -1;
for (unsigned attempt = 0; attempt < 128; ++attempt) {
uint64_t id = atomic_fetch_add_explicit(&temporary_id, 1, memory_order_relaxed) + 1;
snprintf(
temporary,
target_len + 64,
"%s.uhdk-%ld-%llu",
target,
(long)getpid(),
(unsigned long long)id
);
fd = open(temporary, O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC | O_NOFOLLOW, mode);
if (fd >= 0 || errno != EEXIST)
break;
}
if (fd < 0) {
uint32_t status = posix_error(errno);
free(temporary);
free(writer);
free(target);
return status;
}
if (fchmod(fd, mode) != 0) {
uint32_t status = posix_error(errno);
close(fd);
unlink(temporary);
free(temporary);
free(writer);
free(target);
return status;
}
writer->fd = fd;
writer->target = target;
writer->temporary = temporary;
*out = writer;
return Z_FILE_OK;
}
uint32_t z_file_writer_write(
void *opaque,
uint64_t offset,
const void *buffer,
size_t length,
size_t *out
) {
z_file_writer *writer = opaque;
ssize_t count;
do {
count = pwrite(writer->fd, buffer, length, (off_t)offset);
} while (count < 0 && errno == EINTR);
if (count < 0)
return posix_error(errno);
*out = (size_t)count;
return Z_FILE_OK;
}
uint32_t z_file_writer_commit(void *opaque) {
z_file_writer *writer = opaque;
if (fsync(writer->fd) != 0)
return posix_error(errno);
if (close(writer->fd) != 0) {
writer->fd = -1;
return posix_error(errno);
}
writer->fd = -1;
if (rename(writer->temporary, writer->target) != 0)
return posix_error(errno);
free(writer->temporary);
free(writer->target);
free(writer);
return Z_FILE_OK;
}
void z_file_writer_close(void *opaque) {
if (!opaque)
return;
z_file_writer *writer = opaque;
if (writer->fd >= 0)
close(writer->fd);
unlink(writer->temporary);
free(writer->temporary);
free(writer->target);
free(writer);
}
#endif

View File

@ -4,12 +4,13 @@ const c = @import("native");
comptime {
checkExports(@import("api/app.zig"));
checkExports(@import("api/session.zig"));
checkExports(@import("api/windows.zig"));
checkExports(@import("api/graphics.zig"));
checkExports(@import("api/input.zig"));
checkExports(@import("api/files.zig"));
checkExports(@import("api/menus.zig"));
checkExports(@import("api/desktop.zig"));
checkExports(@import("api/tray.zig"));
_ = @import("callbacks.zig");
if (@import("builtin").os.tag == .linux) _ = @import("linux/native.zig");
}
@ -17,7 +18,9 @@ comptime {
test {
std.testing.refAllDecls(@import("abi.zig"));
std.testing.refAllDecls(@import("FileOperation.zig"));
std.testing.refAllDecls(@import("MinimalIo.zig"));
_ = @import("core_tests.zig");
_ = @import("Cycles.zig");
_ = @import("arenas.zig");
if (@import("builtin").os.tag == .linux) {
_ = @import("linux/Files.zig");
@ -30,9 +33,9 @@ test {
}
fn checkExports(comptime module: type) void {
for (@typeInfo(module).@"struct".decls) |declaration| {
if (!std.mem.startsWith(u8, declaration.name, "uhdk_")) continue;
if (@TypeOf(@field(module, declaration.name)) != @TypeOf(@field(c, declaration.name))) {
for (@typeInfo(module).@"struct".decl_names) |declaration| {
if (!std.mem.startsWith(u8, declaration, "uhdk_")) continue;
if (@TypeOf(@field(module, declaration)) != @TypeOf(@field(c, declaration))) {
@compileError("C signature mismatch: " ++ declaration.name);
}
}
@ -41,7 +44,7 @@ fn checkExports(comptime module: type) void {
comptime {
std.debug.assert(@sizeOf(c.uhdk_bool) == 1);
std.debug.assert(@sizeOf(c.uhdk_status) == 4);
std.debug.assert(@sizeOf(c.uhdk_request_id) == 8);
std.debug.assert(@sizeOf(c.uhdk_request_tag) == 8);
std.debug.assert(@sizeOf(@FieldType(c.uhdk_point, "x")) == 4);
std.debug.assert(@sizeOf(c.uhdk_event) == c.Z_EVENT_SIZE);
std.debug.assert(@alignOf(c.uhdk_event) == c.Z_EVENT_ALIGNMENT);

View File

@ -9,7 +9,7 @@ const Resource = @import("Resource.zig");
const Application = @import("Application.zig");
const FileOperation = @import("FileOperation.zig");
pub fn fromAppHandle(handle: ?*c.uhdk_app) *Application {
pub fn fromAppHandle(handle: ?*c.uhdk_session) *Application {
return @ptrCast(@alignCast(if (@typeInfo(@TypeOf(handle)) == .optional) handle.? else handle));
}
@ -17,7 +17,7 @@ pub fn fromObjectHandle(handle: anytype) *Resource {
return @ptrCast(@alignCast(if (@typeInfo(@TypeOf(handle)) == .optional) handle.? else handle));
}
pub fn toAppHandle(application: *Application) *c.uhdk_app {
pub fn toAppHandle(application: *Application) *c.uhdk_session {
return @ptrCast(application);
}
@ -33,13 +33,16 @@ pub fn threadCpuTime(io: std.Io) u64 {
return @intCast(@max(0, std.Io.Timestamp.now(io, .cpu_thread).nanoseconds));
}
pub fn checkThread(application: *Application) abi.Status {
return if (application.running and std.Thread.getCurrentId() == application.worker_id) abi.OK else c.UHDK_STATUS_WRONG_THREAD;
pub fn validateMainThreadSessionReady(application: *Application) abi.Status {
application.lock();
defer application.unlock();
return if (application.running and std.Thread.getCurrentId() == application.main_thread) abi.OK else c.UHDK_STATUS_WRONG_THREAD;
}
pub fn checkObject(object: *Resource, kind: u32) abi.Status {
if (checkThread(object.app) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return if (object.kind() == kind and object.alive) abi.OK else abi.UNAVAILABLE;
pub fn validateMainThreadObjectReady(object: *Resource, kind: u32) abi.Status {
const status = validateMainThreadSessionReady(object.app);
if (status != abi.OK) return status;
return if (object.kind() == kind and object.alive and object.ready) abi.OK else abi.UNAVAILABLE;
}
pub fn createObject(application: *Application, kind: u32) !*Resource {
@ -69,20 +72,24 @@ pub fn release(object: *Resource) void {
application.unlock();
return;
}
var link = &application.objects;
while (link.*) |resource| {
if (resource == object) {
link.* = resource.next;
break;
}
link = &resource.next;
}
application.unlock();
if (object.payload == .menu and object.payload.menu.owns_submenus) {
for (object.payload.menu.items) |item| {
if (item.submenu) |submenu| release(fromObjectHandle(submenu));
}
}
if (object.native) |native| c.z_native_destroy(object.kind(), native);
const gpa = object.gpa;
object.arena.deinit();
@ -125,6 +132,7 @@ pub fn cloneFiles(node: *Event, files: c.uhdk_file_list) !c.uhdk_file_list {
f.* = files.ptr[i];
try pin(&node.pins, fromObjectHandle(f.*));
}
return .{ .ptr = out.ptr, .len = out.len };
}
@ -152,27 +160,6 @@ pub fn copyPayload(node: *Event) !void {
}
}
// Reserve READY before native initialization, but expose it only after startup
// succeeds. Initial preferences/open-file events may arrive during that call.
pub fn prepareReady(application: *Application) !*Event {
const node = try application.gpa.create(Event);
node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) };
node.event.type = c.UHDK_EVENT_READY;
node.event.struct_size = @sizeOf(c.z_event);
node.event.time_ns = now(application.io) - application.epoch;
return node;
}
pub fn publishReady(application: *Application, node: *Event) void {
std.debug.assert(node.event.type == c.UHDK_EVENT_READY);
application.lock();
defer application.unlock();
node.next = application.pending_head;
application.pending_head = node;
if (application.pending_tail == null) application.pending_tail = node;
application.notify();
}
pub fn simpleEvent(application: *Application, typ: u32) void {
var event = std.mem.zeroes(c.z_event);
event.type = typ;
@ -183,6 +170,7 @@ pub fn createCommand(application: *Application, op: u32, target: ?*Resource) !*R
const node = try application.gpa.create(Event);
node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) };
errdefer destroyEvent(node);
const command = try application.gpa.create(Request);
command.* = .{ .node = node, .gpa = application.gpa, .arena = .init(application.gpa) };
errdefer command.gpa.destroy(command);
@ -212,12 +200,8 @@ fn discardCreation(command: *Request) void {
c.Z_WINDOW => if (command.data.target) |target| {
fromObjectHandle(target).alive = false;
},
c.Z_GL => if (command.data.other) |other| {
const object = fromObjectHandle(other);
object.alive = false;
if (object.payload.gl.owner) |window| {
if (window.payload.window.context == object) window.payload.window.context = null;
}
c.Z_GL => if (command.data.target) |target| {
fromObjectHandle(target).payload.window.gl_requested = false;
},
c.Z_WATCH => if (command.data.other) |other| {
const object = fromObjectHandle(other);
@ -229,20 +213,51 @@ fn discardCreation(command: *Request) void {
}
}
pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.Status {
if (out == null or checkThread(application) != abi.OK) {
pub fn submit(application: *Application, command: *Request, tag: u64) abi.Status {
if ((command.completion == .request and tag == 0) or validateMainThreadSessionReady(application) != abi.OK) {
const status: abi.Status = if (command.completion == .request and tag == 0) abi.INVALID else c.UHDK_STATUS_WRONG_THREAD;
abandon(command);
return if (out == null) abi.INVALID else c.UHDK_STATUS_WRONG_THREAD;
return status;
}
application.lock();
if (application.stopping or application.next_id == std.math.maxInt(u64)) {
application.unlock();
abandon(command);
return abi.UNAVAILABLE;
}
if (command.completion == .request) {
var request = application.requests;
while (request) |pending| : (request = pending.next) {
if (pending.completion == .request and pending.tag == tag) {
application.unlock();
abandon(command);
return c.UHDK_STATUS_BUSY;
}
}
// A finished request still owns its tag until its event is delivered.
var event = application.pending_head;
while (event) |pending| : (event = pending.next) {
if (pending.event.type == c.UHDK_EVENT_REQUEST_DONE and pending.event.data.request.tag == tag) {
application.unlock();
abandon(command);
return c.UHDK_STATUS_BUSY;
}
}
}
if ((command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) and application.io_pending >= 64) {
application.unlock();
abandon(command);
return c.UHDK_STATUS_BUSY;
}
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending += 1;
command.id = application.next_id;
application.next_id += 1;
out.* = command.id;
command.tag = tag;
command.next = application.requests;
application.requests = command;
if (application.queue_tail) |tail| tail.queued_next = command else application.queue_head = command;
@ -252,6 +267,16 @@ pub fn submit(application: *Application, command: *Request, out: [*c]u64) abi.St
return abi.OK;
}
pub fn submitResource(application: *Application, command: *Request) abi.Status {
command.completion = .resource;
return submit(application, command, 0);
}
pub fn submitCommand(application: *Application, command: *Request) abi.Status {
command.completion = .discard;
return submit(application, command, 0);
}
pub fn notifyCommand(object: *Resource, op: u32) void {
const command = createCommand(object.app, op, object) catch {
object.app.lock();
@ -260,6 +285,7 @@ pub fn notifyCommand(object: *Resource, op: u32) void {
object.app.unlock();
return;
};
object.app.lock();
if (object.app.queue_tail) |tail| tail.queued_next = command else object.app.queue_head = command;
object.app.queue_tail = command;
@ -283,52 +309,132 @@ pub fn finish(
abandon(command);
return;
}
if (status == abi.OK and command.data.op == c.Z_WINDOW)
fromObjectHandle(command.data.target).ready = true;
if (command.data.op == c.Z_GL) {
const window = fromObjectHandle(command.data.target);
window.payload.window.gl_status = status;
window.payload.window.gl_ready = true;
}
const redraw = command.completion == .resource and status == abi.OK and command.data.op == c.Z_GL;
const redraw_window = if (redraw) fromObjectHandle(command.data.target) else null;
if (command.completion == .resource) {
if (command.data.op == c.Z_WINDOW)
fromObjectHandle(command.data.target).creation_status = status;
}
if (status != abi.OK) discardCreation(command);
const node = command.node;
node.event.type = c.UHDK_EVENT_REQUEST_DONE;
if (value) |v| node.event.data.request = v.*;
node.event.data.request.id = command.id;
node.event.data.request.kind = command.kind;
node.event.data.request.status = status;
copyPayload(node) catch {
node.event.data.request.status = abi.OOM;
node.event.data.request.value = std.mem.zeroes(@TypeOf(node.event.data.request.value));
node.event.data.request.diagnostic = .{ .ptr = null, .len = 0 };
const publish = switch (command.completion) {
.request => request: {
node.event.type = c.UHDK_EVENT_REQUEST_DONE;
if (value) |v| node.event.data.request = v.*;
node.event.data.request.tag = command.tag;
node.event.data.request.kind = command.kind;
node.event.data.request.status = status;
copyPayload(node) catch {
node.event.data.request.status = abi.OOM;
node.event.data.request.value = std.mem.zeroes(@TypeOf(node.event.data.request.value));
node.event.data.request.diagnostic = .{ .ptr = null, .len = 0 };
};
break :request true;
},
.resource => false,
.discard => false,
};
application.lock();
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) application.io_pending -= 1;
var link = &application.requests;
while (link.*) |request| {
if (request == command) {
link.* = request.next;
break;
}
link = &request.next;
}
publishLocked(application, node);
if (publish) publishLocked(application, node);
application.unlock();
if (!publish) destroyEvent(node);
if (redraw_window) |window| notifyCommand(window, c.Z_REDRAW);
if (command.completion == .resource and status == abi.OK) c.z_native_wake();
destroyCommand(command);
}
pub fn applicationMain(application: *Application) void {
profile.thread("UHDK application/render");
const pool = c.z_native_pool_push();
defer c.z_native_pool_pop(pool);
pub fn hasFrame(application: *Application) bool {
application.lock();
application.worker_id = std.Thread.getCurrentId();
application.unlock();
application.entry.?(toAppHandle(application), application.user);
if (@import("builtin").os.tag == .windows or @import("builtin").os.tag == .linux) _ = c.z_native_gl(null, 4, null);
application.lock();
application.stopping = true;
application.worker_done = true;
application.unlock();
c.z_native_wake();
defer application.unlock();
var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.payload == .window and object.payload.window.bracket) return true;
}
return false;
}
/// Execute file operations without touching native resources or publishing user
/// events. The platform dispatcher owns completion and request retirement.
pub fn ioMain(application: *Application) void {
profile.thread("UHDK file I/O");
while (true) {
application.lock();
const command = application.io_head orelse {
const done = application.io_exit;
application.io_available.reset();
application.unlock();
if (done) return;
application.io_available.waitUncancelable(application.io);
continue;
};
application.io_head = command.queued_next;
if (application.io_head == null) application.io_tail = null;
command.queued_next = null;
application.io_active = command;
application.unlock();
if (comptime @import("builtin").is_test) {
if (application.io_test_hook) |hook| hook.before(hook.context);
}
if (command.data.op == c.Z_WATCH) {
if (isCancelled(application, command)) {
command.io_status = abi.CANCELLED;
} else {
command.io_status = c.z_native_watch_prepare(@ptrCast(command.data.target), @ptrCast(command.data.other), &command.io_prepared);
command.io_result.value.watch = @ptrCast(command.data.other);
}
} else while (!fileStep(application, command)) {}
// Close OS file handles on the worker, before result retirement on main.
// Read results remain owned by FileOperation until main copies them.
if (command.file_operation) |*operation| operation.close();
application.lock();
application.io_active = null;
if (application.io_completed_tail) |tail| tail.queued_next = command else application.io_completed_head = command;
application.io_completed_tail = command;
application.unlock();
c.z_native_wake();
}
}
fn finishIo(command: *Request, status: abi.Status, value: ?*const c.z_request_result) void {
command.io_status = status;
if (value) |v| command.io_result = v.*;
}
pub fn createObjectCommand(handle: anytype, kind: u32, op: u32) !*Request {
if (handle == null) return error.Invalid;
const object = fromObjectHandle(handle);
if (checkThread(object.app) != abi.OK) return error.WrongThread;
if (validateMainThreadSessionReady(object.app) != abi.OK) return error.WrongThread;
if (object.kind() != kind) return error.Invalid;
if (!object.alive) return error.Unavailable;
return createCommand(object.app, op, object);
@ -343,37 +449,26 @@ pub fn objectError(err: anyerror) abi.Status {
};
}
pub fn scalarCommand(
handle: ?*c.uhdk_window,
kind: u32,
op: u32,
value: u64,
out: [*c]u64,
) abi.Status {
pub fn scalarCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, value: u64) abi.Status {
const command = createObjectCommand(handle, kind, op) catch |err| return objectError(err);
command.data.number = value;
return submit(fromObjectHandle(handle).app, command, out);
return submitCommand(fromObjectHandle(handle).app, command);
}
pub fn textCommand(
handle: ?*c.uhdk_window,
kind: u32,
op: u32,
text: c.uhdk_text,
out: [*c]u64,
) abi.Status {
pub fn textCommandValue(handle: ?*c.uhdk_window, kind: u32, op: u32, text: c.uhdk_text) abi.Status {
if (!abi.validText(text, true)) return abi.INVALID;
const command = createObjectCommand(handle, kind, op) catch |err| return objectError(err);
command.data.text = abi.copyText(command.arena.allocator(), text) catch {
abandon(command);
return abi.OOM;
};
return submit(fromObjectHandle(handle).app, command, out);
return submitCommand(fromObjectHandle(handle).app, command);
}
pub fn createAppCommand(handle: ?*c.uhdk_app, op: u32) !*Request {
pub fn createAppCommand(handle: ?*c.uhdk_session, op: u32) !*Request {
if (handle == null) return error.Invalid;
if (checkThread(fromAppHandle(handle)) != abi.OK) return error.WrongThread;
if (validateMainThreadSessionReady(fromAppHandle(handle)) != abi.OK) return error.WrongThread;
return createCommand(fromAppHandle(handle), op, null);
}
@ -387,20 +482,20 @@ pub fn applicationError(err: anyerror) abi.Status {
pub fn destroyObject(object: *Resource) void {
if (!object.alive) return;
std.debug.assert(checkThread(object.app) == abi.OK);
if (object.payload == .gl) {
std.debug.assert(!object.payload.gl.bracket);
std.debug.assert(validateMainThreadSessionReady(object.app) == abi.OK);
if (object.payload == .window and object.payload.window.gl_ready and object.payload.window.gl_status == abi.OK) {
std.debug.assert(!object.payload.window.bracket);
if ((@import("builtin").os.tag == .windows or @import("builtin").os.tag == .linux) and object.native != null)
_ = c.z_native_gl(object.native, 8, null);
c.z_native_destroy(c.Z_KIND_GL, object.native);
object.payload.window.gl_ready = false;
}
if (object.payload == .window) if (object.payload.window.context) |ctx| {
destroyObject(ctx);
object.payload.window.context = null;
};
// Find one child under the registry lock, then recurse without the lock.
// Files can be released concurrently by the other thread.
while (true) {
object.app.lock();
var cursor = object.app.objects;
const child: ?*Resource = while (cursor) |candidate| : (cursor = candidate.next) {
if (candidate.payload == .window and
@ -412,25 +507,30 @@ pub fn destroyObject(object: *Resource) void {
object.app.unlock();
if (child) |resource| destroyObject(resource) else break;
}
object.app.lock();
object.alive = false;
var req = object.app.requests;
while (req) |request| : (req = request.next) {
if (request.data.target == castHandle(?*anyopaque, object) or
request.data.other == castHandle(?*anyopaque, object) or
(request.data.op == c.Z_DIALOG and request.data.dialog.parent == castHandle(?*c.uhdk_window, object))) request.cancelled = true;
}
object.app.unlock();
notifyCommand(object, c.Z_DESTROY);
}
pub fn glCall(handle: ?*c.uhdk_gl_context, op: u32, out: ?*anyopaque) abi.Status {
pub fn glCall(handle: ?*c.uhdk_window, op: u32, out: ?*anyopaque) abi.Status {
if (handle == null) return abi.INVALID;
const object = fromObjectHandle(handle);
const status = checkObject(object, c.Z_KIND_GL);
const status = validateMainThreadObjectReady(object, c.Z_KIND_WINDOW);
if (status != abi.OK) return status;
if (object.native == null) return abi.UNAVAILABLE;
if (op != 1 and !object.payload.gl.bracket) return c.UHDK_STATUS_BUSY;
if (!object.payload.window.gl_ready or object.payload.window.gl_status != abi.OK) return abi.UNAVAILABLE;
if (op != 1 and !object.payload.window.bracket) return c.UHDK_STATUS_BUSY;
return c.z_native_gl(object.native, op, out);
}
@ -442,6 +542,7 @@ pub fn copyDialog(command: *Request) !void {
d.suggested_name = try abi.copyText(arena, d.suggested_name);
if (d.parent) |handle| try pin(&command.pins, fromObjectHandle(handle));
if (d.initial_directory) |f| try pin(&command.pins, fromObjectHandle(f));
const filters = try arena.alloc(c.uhdk_file_filter, @intCast(d.filters_len));
for (filters, 0..) |*f, i| {
f.* = d.filters[i];
@ -449,15 +550,22 @@ pub fn copyDialog(command: *Request) !void {
!abi.validSpan(f.extensions.ptr, f.extensions.len) or
f.extensions.len > 256) return error.Invalid;
f.label = try abi.copyText(arena, f.label);
const extensions = try arena.alloc(c.uhdk_text, @intCast(f.extensions.len));
for (extensions, 0..) |*ext, j| {
const event = f.extensions.ptr[j];
if (!abi.validText(event, true) or
std.mem.findAny(u8, abi.textBytes(event), "/\\.") != null) return error.Invalid;
if (!abi.validText(event, true)) return error.Invalid;
const value = abi.textBytes(event);
if (value.len == 0 or value[0] == '.' or value[value.len - 1] == '.')
return error.Invalid;
if (std.mem.indexOf(u8, value, "..") != null) return error.Invalid;
if (std.mem.findAny(u8, value, "/\\") != null) return error.Invalid;
ext.* = try abi.copyText(arena, event);
}
f.extensions.ptr = extensions.ptr;
}
d.filters = filters.ptr;
}
@ -477,13 +585,13 @@ pub fn fileStep(application: *Application, command: *Request) bool {
const zone = profile.begin(@src(), "UHDK file operation batch");
defer zone.end();
if (isCancelled(application, command)) {
finish(application, command, abi.CANCELLED, null);
finishIo(command, abi.CANCELLED, null);
return true;
}
if (command.file_operation == null) {
command.file_operation = FileOperation.init(
application.gpa,
application.io,
switch (command.data.op) {
abi.IO_READ => .read,
abi.IO_WRITE => .write,
@ -495,10 +603,12 @@ pub fn fileStep(application: *Application, command: *Request) bool {
command.data.limit,
);
}
const result = command.file_operation.?.step() catch |err| {
finish(application, command, fileError(err), null);
finishIo(command, fileError(err), null);
return true;
};
var value = std.mem.zeroes(c.z_request_result);
switch (result) {
.pending => return false,
@ -506,7 +616,7 @@ pub fn fileStep(application: *Application, command: *Request) bool {
.bytes => |contents| value.value.bytes = .{ .ptr = contents.ptr, .len = contents.len },
.info => |info| value.value.info = .{
.size_bytes = info.size,
.modified_time_ns = std.math.lossyCast(i64, info.mtime.nanoseconds),
.modified_time_ns = info.modified_ns,
.type = switch (info.kind) {
.file => c.UHDK_FILE_REGULAR,
.directory => c.UHDK_FILE_DIRECTORY,
@ -515,26 +625,28 @@ pub fn fileStep(application: *Application, command: *Request) bool {
.reserved = 0,
},
}
finish(application, command, abi.OK, &value);
finishIo(command, abi.OK, &value);
return true;
}
pub fn validateMenu(object: *Resource, ids: *std.AutoHashMap(u64, void), depth: usize) !void {
if (depth > 16) return error.Invalid;
for (object.payload.menu.items) |item| {
if (item.command_id != 0) {
const entry = try ids.getOrPut(item.command_id);
if (entry.found_existing) return error.Invalid;
}
if (item.submenu) |sub| try validateMenu(fromObjectHandle(sub), ids, depth + 1);
}
}
pub fn attachMenu(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
w: ?*c.uhdk_window,
menu: ?*c.uhdk_menu,
out: [*c]u64,
) abi.Status {
if (handle == null or
(menu != null and (fromObjectHandle(menu).app != fromAppHandle(handle) or
@ -545,12 +657,14 @@ pub fn attachMenu(
abandon(command);
return abi.UNAVAILABLE;
}
command.data.target = fromObjectHandle(w);
pin(&command.pins, fromObjectHandle(w)) catch {
abandon(command);
return abi.OOM;
};
}
if (menu) |m| {
command.data.other = fromObjectHandle(m);
pin(&command.pins, fromObjectHandle(m)) catch {
@ -558,24 +672,45 @@ pub fn attachMenu(
return abi.OOM;
};
}
return submit(fromAppHandle(handle), command, out);
return submitCommand(fromAppHandle(handle), command);
}
pub fn setMenuFlags(object: *Resource, id: u64, flags: u32) bool {
for (object.payload.menu.items) |*item| {
if (item.command_id == id) {
if (item.flags & c.UHDK_MENU_SEPARATOR != 0) return false;
item.flags = flags;
return true;
}
if (item.submenu) |sub| {
if (setMenuFlags(fromObjectHandle(sub), id, flags)) return true;
}
}
return false;
}
pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void {
fn publishCycleEnds(application: *Application, window: *c.uhdk_window, ended: @import("Cycles.zig").Ended) void {
for (ended.ids[0..ended.len], ended.reasons[0..ended.len]) |id, reason| {
const node = application.gpa.create(Event) catch {
application.event_error = abi.OOM;
application.notify();
return;
};
node.* = .{ .gpa = application.gpa, .arena = .init(application.gpa) };
node.event.type = c.UHDK_EVENT_CYCLE_END;
node.event.window = window;
node.event.cycle_id = id;
node.event.data.cycle_end.reason = reason;
publishLocked(application, node);
}
}
pub fn emit(handle: ?*c.uhdk_session, event: [*c]const c.z_event) void {
const application = fromAppHandle(handle);
const node = application.gpa.create(Event) catch {
application.lock();
@ -584,6 +719,7 @@ pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void {
application.unlock();
return;
};
node.* = .{ .event = event.*, .gpa = application.gpa, .arena = .init(application.gpa) };
copyPayload(node) catch {
destroyEvent(node);
@ -593,6 +729,7 @@ pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void {
application.unlock();
return;
};
application.lock();
defer application.unlock();
if (application.stopped_sent or (node.event.window != null and !fromObjectHandle(node.event.window).alive)) {
@ -601,6 +738,7 @@ pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void {
application.lock();
return;
}
// Redraw and wake have no payload; coalesce only while still pending.
if (event.*.type == c.UHDK_EVENT_WINDOW_REDRAW or event.*.type == c.UHDK_EVENT_WAKE) {
var cursor = application.pending_head;
@ -613,17 +751,44 @@ pub fn emit(handle: ?*c.uhdk_app, event: [*c]const c.z_event) void {
}
}
}
publishLocked(application, node);
if (node.event.window) |window| {
const ended = fromObjectHandle(window).payload.window.cycles.apply(&application.next_cycle, &node.event) catch {
application.event_error = abi.UNAVAILABLE;
application.notify();
application.unlock();
destroyEvent(node);
application.lock();
return;
};
publishLocked(application, node);
publishCycleEnds(application, window, ended);
} else {
// Session deactivation and normal shutdown retire every active window cycle.
if ((node.event.type == c.UHDK_EVENT_APP_ACTIVATION and node.event.data.active == 0) or
node.event.type == c.UHDK_EVENT_STOPPED)
{
var cursor = application.objects;
while (cursor) |object| : (cursor = object.next) {
if (object.alive and object.payload == .window)
publishCycleEnds(application, castHandle(*c.uhdk_window, object), object.payload.window.cycles.endAll(if (node.event.type == c.UHDK_EVENT_STOPPED) c.UHDK_CYCLE_SHUTDOWN else c.UHDK_CYCLE_FOCUS_LOST));
}
}
publishLocked(application, node);
}
}
pub fn complete(
handle: ?*c.uhdk_app,
handle: ?*c.uhdk_session,
id: u64,
status: abi.Status,
result: [*c]const c.z_request_result,
) void {
const application = fromAppHandle(handle);
application.lock();
var cursor = application.requests;
while (cursor) |command| : (cursor = command.next) {
if (command.id == id) {
@ -632,25 +797,54 @@ pub fn complete(
return;
}
}
application.unlock();
}
pub fn tick(handle: ?*c.uhdk_app) void {
pub fn dispatch(handle: ?*c.uhdk_session) void {
const zone = profile.begin(@src(), "UHDK platform dispatch");
defer zone.end();
const application = fromAppHandle(handle);
// Native tracking loops can reenter the run loop; never reenter application command.
if (application.in_tick) return;
application.in_tick = true;
defer application.in_tick = false;
if (application.in_dispatch) return;
application.in_dispatch = true;
defer application.in_dispatch = false;
while (true) {
application.lock();
const completed = application.io_completed_head orelse {
application.unlock();
break;
};
application.io_completed_head = completed.queued_next;
if (application.io_completed_head == null) application.io_completed_tail = null;
application.unlock();
if (completed.io_prepared) |prepared| {
const object = fromObjectHandle(completed.data.other);
c.z_native_watch_commit(@ptrCast(object), prepared);
if (isCancelled(application, completed) or !object.alive) {
c.z_native_destroy(c.Z_KIND_WATCH, prepared);
object.native = null;
completed.io_status = abi.CANCELLED;
}
}
finish(application, completed, completed.io_status, &completed.io_result);
}
const start = now(application.io);
var count: usize = 0;
var blocked_on_resource = false;
while (count < 64 and now(application.io) - start < 2_000_000) : (count += 1) {
application.lock();
const command = application.queue_head orelse {
application.unlock();
break;
};
application.queue_head = command.queued_next;
if (application.queue_head == null) application.queue_tail = null;
command.queued_next = null;
@ -659,18 +853,37 @@ pub fn tick(handle: ?*c.uhdk_app) void {
finish(application, command, abi.CANCELLED, null);
continue;
}
if (command.data.target != null and !fromObjectHandle(command.data.target).alive and command.data.op != c.Z_DESTROY) {
finish(application, command, abi.CANCELLED, null);
continue;
}
if (command.data.op >= abi.IO_READ) {
if (command.data.op != c.Z_WINDOW and command.data.op != c.Z_DESTROY and command.data.target != null and
!fromObjectHandle(command.data.target).ready)
{
application.lock();
command.queued_next = application.queue_head;
application.queue_head = command;
if (application.queue_tail == null) application.queue_tail = command;
application.unlock();
blocked_on_resource = true;
break;
}
if (command.data.op >= abi.IO_READ or command.data.op == c.Z_WATCH) {
application.lock();
if (application.io_tail) |tail| tail.queued_next = command else application.io_head = command;
application.io_tail = command;
application.io_available.set(application.io);
application.unlock();
continue;
}
var result = std.mem.zeroes(c.z_request_result);
if (command.data.op == c.Z_MENU_FLAGS) {
application.lock();
const found = setMenuFlags(fromObjectHandle(command.data.target), command.data.number, @intCast(command.data.limit));
application.unlock();
if (!found) {
@ -678,32 +891,28 @@ pub fn tick(handle: ?*c.uhdk_app) void {
continue;
}
}
// Mark before entering native code: a backend may complete inline.
command.native_deferred = true;
const status = c.z_native_execute(handle, &command.data, command.id, &result);
if (status != c.Z_DEFERRED and command.data.op == c.Z_DESTROY) {
const resource = fromObjectHandle(command.data.target);
if (resource.payload == .tray) @import("api/tray.zig").clear(resource);
if (resource.payload == .watch) {
if (resource.payload.watch.owner) |root| release(root);
resource.payload.watch.owner = null;
}
}
if (status != c.Z_DEFERRED) {
finish(application, command, status, &result);
}
}
if (application.io_active == null) {
if (application.io_head) |command| {
application.io_head = command.queued_next;
if (application.io_head == null) application.io_tail = null;
application.io_active = command;
}
}
if (application.io_active) |command| {
if (fileStep(application, command)) application.io_active = null;
}
// Only operations dispatched to native code need native cancellation hooks.
application.lock();
var cursor = application.requests;
var ids: [64]u64 = undefined;
var node: usize = 0;
@ -715,9 +924,11 @@ pub fn tick(handle: ?*c.uhdk_app) void {
node += 1;
}
}
application.unlock();
for (ids[0..node]) |id| c.z_native_cancel(id);
application.lock();
const empty = application.requests == null and application.queue_head == null and application.io_active == null and application.io_head == null;
if (application.stopping and empty and !application.stopped_sent) {
application.unlock();
@ -725,8 +936,8 @@ pub fn tick(handle: ?*c.uhdk_app) void {
application.lock();
application.stopped_sent = true;
}
const done = application.worker_done and empty;
const again = application.queue_head != null or application.io_head != null or application.io_active != null or node == ids.len;
const again = (!blocked_on_resource and application.queue_head != null) or application.io_completed_head != null or node == ids.len;
application.unlock();
if (done) c.z_native_stop() else if (again) c.z_native_again();
if (again) c.z_native_again();
}

16
src/test_frame.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef UHDK_TEST_FRAME_H
#define UHDK_TEST_FRAME_H
#include "uhdk.h"
/* Native tests consume event batches through complete application iterations.
* Their sessions use continuous mode, so visible primary windows never wait.
* Event storage remains borrowed after end_frame, until the next iteration. */
static uhdk_status test_frame_events(uhdk_session *session, uhdk_event_list *out) {
uhdk_frame frame;
if (!uhdk_next_frame(session, &frame)) {
uhdk_status status = uhdk_get_status(session);
return status == UHDK_STATUS_OK ? UHDK_STATUS_UNAVAILABLE : status;
}
*out = frame.events;
return uhdk_end_frame(session);
}
#endif

View File

@ -1,5 +1,5 @@
/* Win32 bridge. Queues, handles, ownership and bounded file I/O remain in Zig.
* Cross-compiled implementation: native Windows runtime validation is pending. */
* Platform requirements and validation scope are documented in ../../README.md. */
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
@ -51,10 +51,14 @@ typedef struct Graphics {
uint32_t major, minor;
} Graphics;
struct Window {
uhdk_pointer_mode pointer_mode;
uhdk_function_key_policy function_key_policy;
z_function_keys function_keys;
Window *next;
HWND hwnd;
uhdk_window *handle;
uint32_t flags;
uhdk_window_style style;
uhdk_size min_size, max_size;
float scale;
BOOL text_enabled, tracking, fullscreen, composing, suppress_char, resizing;
@ -64,6 +68,7 @@ struct Window {
uhdk_point pointer;
HCURSOR cursor;
HMENU menu;
Graphics *graphics;
uhdk_menu *menu_source;
WINDOWPLACEMENT placement;
LONG_PTR saved_style;
@ -78,7 +83,7 @@ struct Watch {
BOOL pending;
};
static struct {
uhdk_app *app;
uhdk_session *app;
HWND dispatch;
Window *windows;
Watch *watches;
@ -119,9 +124,10 @@ static uhdk_status osError(void) {
static WCHAR *wide(uhdk_text text) {
if (text.len > INT_MAX)
return NULL;
int n = text.len ? MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.ptr, (int)text.len,
NULL, 0)
: 0;
int n =
text.len
? MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.ptr, (int)text.len, NULL, 0)
: 0;
if (text.len && !n)
return NULL;
WCHAR *s = profileCalloc((size_t)n + 1, sizeof(WCHAR));
@ -153,6 +159,47 @@ static void emit(Window *w, uint32_t type) {
e.window = w ? w->handle : NULL;
z_emit(host.app, &e);
}
static void pointerModeEvent(Window *w, uhdk_pointer_mode mode, uhdk_cycle_end_reason reason) {
w->pointer_mode = mode;
z_event e = {0};
e.type = UHDK_EVENT_POINTER_MODE_CHANGED;
e.window = w->handle;
e.data.pointer_mode = mode;
e.cycle_end_reason = reason;
z_emit(host.app, &e);
}
static void releasePointer(Window *w, uhdk_cycle_end_reason reason) {
uhdk_pointer_mode previous = w->pointer_mode;
if (previous == UHDK_POINTER_NORMAL)
return;
/* Clear first: ReleaseCapture synchronously sends WM_CAPTURECHANGED. */
w->pointer_mode = UHDK_POINTER_NORMAL;
if (previous == UHDK_POINTER_CONFINED)
ClipCursor(NULL);
if (previous == UHDK_POINTER_CAPTURE && GetCapture() == w->hwnd)
ReleaseCapture();
pointerModeEvent(w, UHDK_POINTER_NORMAL, reason);
}
static BOOL confinementRect(Window *w, RECT *rect) {
if (!GetClientRect(w->hwnd, rect) || rect->right <= 0 || rect->bottom <= 0)
return FALSE;
POINT origin = {0, 0};
if (!ClientToScreen(w->hwnd, &origin))
return FALSE;
OffsetRect(rect, origin.x, origin.y);
return TRUE;
}
static void updateConfinement(Window *w) {
if (w->pointer_mode != UHDK_POINTER_CONFINED)
return;
RECT rect;
if (!IsWindowVisible(w->hwnd) || IsIconic(w->hwnd))
releasePointer(w, UHDK_CYCLE_HIDDEN);
else if (GetFocus() != w->hwnd || GetForegroundWindow() != w->hwnd)
releasePointer(w, UHDK_CYCLE_FOCUS_LOST);
else if (!confinementRect(w, &rect) || !ClipCursor(&rect))
releasePointer(w, UHDK_CYCLE_CAPTURE_LOST);
}
static uint32_t modifiers(void) {
uint32_t m = 0;
if (GetKeyState(VK_SHIFT) & 0x8000)
@ -198,9 +245,15 @@ static void preferences(void) {
uhdk_preferences p = {0};
p.struct_size = sizeof(p);
DWORD light = 1, size = sizeof(light);
RegGetValueW(HKEY_CURRENT_USER,
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
L"AppsUseLightTheme", RRF_RT_REG_DWORD, NULL, &light, &size);
RegGetValueW(
HKEY_CURRENT_USER,
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
L"AppsUseLightTheme",
RRF_RT_REG_DWORD,
NULL,
&light,
&size
);
p.appearance = light ? UHDK_APPEARANCE_LIGHT : UHDK_APPEARANCE_DARK;
HIGHCONTRASTW contrast = {sizeof(contrast), 0, NULL};
SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0);
@ -331,7 +384,8 @@ static uint32_t physicalKey(LPARAM param) {
[57] = 44, [58] = 57, [59] = 58, [60] = 59, [61] = 60, [62] = 61, [63] = 62, [64] = 63,
[65] = 64, [66] = 65, [67] = 66, [68] = 67, [69] = 83, [70] = 71, [71] = 95, [72] = 96,
[73] = 97, [74] = 86, [75] = 92, [76] = 93, [77] = 94, [78] = 87, [79] = 89, [80] = 90,
[81] = 91, [82] = 98, [83] = 99, [86] = 100, [87] = 68, [88] = 69};
[81] = 91, [82] = 98, [83] = 99, [86] = 100, [87] = 68, [88] = 69
};
unsigned scan = (unsigned)(param >> 16) & 127;
if (param & (1 << 24))
switch (scan) {
@ -378,8 +432,10 @@ static void imePosition(Window *w) {
HIMC ime = ImmGetContext(w->hwnd);
if (!ime)
return;
POINT point = {(LONG)(w->text_state.caret.x * w->scale),
(LONG)((w->text_state.caret.y + w->text_state.caret.height) * w->scale)};
POINT point = {
(LONG)(w->text_state.caret.x * w->scale),
(LONG)((w->text_state.caret.y + w->text_state.caret.height) * w->scale)
};
COMPOSITIONFORM composition = {0};
composition.dwStyle = CFS_POINT;
composition.ptCurrentPos = point;
@ -454,7 +510,7 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
if (hwnd == host.dispatch) {
switch (msg) {
case Z_WAKE:
z_tick(host.app);
z_dispatch(host.app);
return 0;
case Z_DIALOG_MESSAGE:
showDialog();
@ -483,6 +539,7 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
case WM_ERASEBKGND:
return 1;
case WM_ENTERSIZEMOVE:
releasePointer(w, UHDK_CYCLE_CAPTURE_LOST);
w->resizing = TRUE;
metrics(w);
break;
@ -492,18 +549,28 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
break;
case WM_SIZE:
case WM_SHOWWINDOW:
if ((msg == WM_SIZE && wp == SIZE_MINIMIZED) || (msg == WM_SHOWWINDOW && !wp))
releasePointer(w, UHDK_CYCLE_HIDDEN);
updateConfinement(w);
metrics(w);
break;
case WM_WINDOWPOSCHANGED:
updateConfinement(w);
break;
case WM_SETFOCUS:
metrics(w);
break;
case WM_KILLFOCUS:
w->high_surrogate = 0;
if (GetCapture() == hwnd)
ReleaseCapture();
w->function_keys = (z_function_keys){0};
releasePointer(w, UHDK_CYCLE_FOCUS_LOST);
metrics(w);
break;
case WM_ACTIVATEAPP: {
if (!wp) {
w->function_keys = (z_function_keys){0};
releasePointer(w, UHDK_CYCLE_FOCUS_LOST);
}
z_event e = {0};
e.type = UHDK_EVENT_APP_ACTIVATION;
e.data.active = !!wp;
@ -516,8 +583,15 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
case WM_DPICHANGED: {
RECT *r = (RECT *)lp;
w->scale = (float)HIWORD(wp) / 96.0f;
SetWindowPos(hwnd, NULL, r->left, r->top, r->right - r->left, r->bottom - r->top,
SWP_NOZORDER | SWP_NOACTIVATE);
SetWindowPos(
hwnd,
NULL,
r->left,
r->top,
r->right - r->left,
r->bottom - r->top,
SWP_NOZORDER | SWP_NOACTIVATE
);
metrics(w);
imePosition(w);
return 0;
@ -531,8 +605,13 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
uhdk_size sizes[] = {w->min_size, w->max_size};
for (unsigned i = 0; i < 2; ++i) {
RECT r = {0, 0, (LONG)(sizes[i].width * scale), (LONG)(sizes[i].height * scale)};
AdjustWindowRectExForDpi(&r, (DWORD)GetWindowLongPtrW(hwnd, GWL_STYLE),
GetMenu(hwnd) != NULL, 0, dpi ? dpi : 96);
AdjustWindowRectExForDpi(
&r,
(DWORD)GetWindowLongPtrW(hwnd, GWL_STYLE),
GetMenu(hwnd) != NULL,
0,
dpi ? dpi : 96
);
POINT *p = i ? &m->ptMaxTrackSize : &m->ptMinTrackSize;
if (sizes[i].width > 0)
p->x = r.right - r.left;
@ -606,16 +685,12 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
return 0;
}
case WM_CAPTURECHANGED: {
z_event e = {0};
e.type = UHDK_EVENT_POINTER_MODE_CHANGED;
e.window = w->handle;
e.data.pointer_mode = UHDK_POINTER_NORMAL;
z_emit(host.app, &e);
if (w->pointer_mode == UHDK_POINTER_CAPTURE)
releasePointer(w, UHDK_CYCLE_CAPTURE_LOST);
return 0;
}
case WM_CANCELMODE:
if (GetCapture() == hwnd)
ReleaseCapture();
releasePointer(w, UHDK_CYCLE_CAPTURE_LOST);
break;
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL: {
@ -646,6 +721,8 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
BOOL down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;
uint32_t mods = modifiers();
uint32_t key = logicalKey(wp);
BOOL suppress_default =
z_function_key_suppress(&w->function_keys, w->function_key_policy, key, mods, down);
if (down) {
w->suppress_char = FALSE;
const uhdk_menu_item *item =
@ -666,6 +743,8 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
e.data.key.pressed = down;
e.data.key.repeat = down && !!(lp & (1u << 30));
z_emit(host.app, &e);
if (suppress_default)
return 0;
if (down && w->text_enabled && !w->composing) {
uint32_t command = z_edit_key(key, mods);
if (command) {
@ -809,10 +888,14 @@ uhdk_status z_native_file_init(uhdk_file *file, uhdk_bytes path, uhdk_text uri,
if ((*p == L'\\' || *p == L'/') && p[1])
leaf = p + 1;
char *display = utf8(leaf, (int)wcslen(leaf), &display_len);
uhdk_status status =
display ? z_file_init(file, (uhdk_bytes){(uint8_t *)name, n * 2},
(uhdk_text){url8, uri_len}, (uhdk_text){display, display_len}, NULL)
: UHDK_STATUS_OS_ERROR;
uhdk_status status = display ? z_file_init(
file,
(uhdk_bytes){(uint8_t *)name, n * 2},
(uhdk_text){url8, uri_len},
(uhdk_text){display, display_len},
NULL
)
: UHDK_STATUS_OS_ERROR;
profileFree(display);
profileFree(url8);
profileFree(url);
@ -827,8 +910,8 @@ static PROC glProc(const char *name) {
p = GetProcAddress(GetModuleHandleW(L"opengl32.dll"), name);
return p;
}
static uhdk_status createGraphics(Window *w, void *handle) {
if (!(w->flags & UHDK_WINDOW_OPENGL))
static uhdk_status createGraphics(Window *w) {
if (!(w->flags & Z_WINDOW_OPENGL))
return UHDK_STATUS_INVALID_ARGUMENT;
Graphics *g = profileCalloc(1, sizeof(*g));
if (!g)
@ -893,7 +976,7 @@ static uhdk_status createGraphics(Window *w, void *handle) {
g->major = (uint32_t)major;
g->minor = (uint32_t)minor;
InitializeCriticalSection(&g->lock);
z_object_set_native(handle, g);
w->graphics = g;
return UHDK_STATUS_OK;
failed:
if (g->rc)
@ -903,9 +986,10 @@ failed:
return UHDK_STATUS_UNSUPPORTED;
}
uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
Graphics *g = native;
if (op == 4)
return wglMakeCurrent(NULL, NULL) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
Window *w = native;
Graphics *g = w ? w->graphics : NULL;
if (!g)
return UHDK_STATUS_UNAVAILABLE;
if (op == 8)
@ -923,15 +1007,8 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
LeaveCriticalSection(&g->lock);
return ok ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
}
if (op == 3)
return wglMakeCurrent(g->dc, g->rc) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
if (wglGetCurrentContext() != g->rc)
return UHDK_STATUS_UNAVAILABLE;
if (op == 5) {
((uint32_t *)out)[0] = g->major;
((uint32_t *)out)[1] = g->minor;
return UHDK_STATUS_OK;
}
if (op == 6)
return SwapBuffers(g->dc) ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
if (op == 7) {
@ -944,7 +1021,8 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) {
return UHDK_STATUS_INVALID_ARGUMENT;
}
uhdk_status z_native_gl_proc(void *native, uhdk_text name, uhdk_gl_proc *out) {
Graphics *g = native;
Window *w = native;
Graphics *g = w ? w->graphics : NULL;
if (!g || wglGetCurrentContext() != g->rc)
return UHDK_STATUS_UNAVAILABLE;
if (name.len > 255)
@ -1058,12 +1136,14 @@ static void showDialog(void) {
IFileSaveDialog *save = NULL;
HRESULT hr;
if (d->kind == UHDK_DIALOG_SAVE_FILE) {
hr = CoCreateInstance(&CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER,
&IID_IFileSaveDialog, (void **)&save);
hr = CoCreateInstance(
&CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, &IID_IFileSaveDialog, (void **)&save
);
dialog = (IFileDialog *)save;
} else {
hr = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
&IID_IFileOpenDialog, (void **)&open);
hr = CoCreateInstance(
&CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, &IID_IFileOpenDialog, (void **)&open
);
dialog = (IFileDialog *)open;
}
if (FAILED(hr)) {
@ -1208,13 +1288,19 @@ static void showDialog(void) {
static BOOL armWatch(Watch *watch) {
ResetEvent(watch->overlapped.hEvent);
watch->pending = ReadDirectoryChangesW(
watch->directory, watch->buffer, sizeof(watch->buffer), FALSE,
watch->directory,
watch->buffer,
sizeof(watch->buffer),
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_ATTRIBUTES,
NULL, &watch->overlapped, NULL);
NULL,
&watch->overlapped,
NULL
);
return watch->pending;
}
static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **out) {
WCHAR *path = filePath(root);
if (!path)
return UHDK_STATUS_OUT_OF_MEMORY;
@ -1248,8 +1334,14 @@ static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
slash[1] = 0;
}
watch->directory = CreateFileW(
path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
path,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
profileFree(path);
watch->overlapped.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
watch->handle = handle;
@ -1263,10 +1355,14 @@ static uhdk_status createWatch(uhdk_file *root, uhdk_watch *handle) {
profileFree(watch);
return status;
}
*out = watch;
return UHDK_STATUS_OK;
}
void z_native_watch_commit(uhdk_watch *handle, void *prepared) {
Watch *watch = prepared;
watch->next = host.watches;
host.watches = watch;
z_object_set_native(handle, watch);
return UHDK_STATUS_OK;
}
static void watchEvent(Watch *watch, uint32_t flags, uhdk_status status) {
z_event e = {0};
@ -1304,10 +1400,11 @@ static void pollWatches(void) {
(FILE_NOTIFY_INFORMATION *)((uint8_t *)w->buffer + offset);
if (info->FileNameLength > size - offset - offsetof(FILE_NOTIFY_INFORMATION, FileName))
break;
BOOL match = !w->leaf ||
(wcslen(w->leaf) * 2 == info->FileNameLength &&
CompareStringOrdinal(w->leaf, -1, info->FileName,
(int)info->FileNameLength / 2, TRUE) == CSTR_EQUAL);
BOOL match =
!w->leaf || (wcslen(w->leaf) * 2 == info->FileNameLength &&
CompareStringOrdinal(
w->leaf, -1, info->FileName, (int)info->FileNameLength / 2, TRUE
) == CSTR_EQUAL);
if (match)
switch (info->Action) {
case FILE_ACTION_ADDED:
@ -1346,7 +1443,7 @@ int z_native_is_main_thread(void) {
LONG previous = InterlockedCompareExchange(&main_thread, current, 0);
return !previous || previous == current;
}
uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
uhdk_status z_native_start(uhdk_session *app, uhdk_text name) {
(void)name;
memset(&host, 0, sizeof(host));
host.app = app;
@ -1373,8 +1470,9 @@ uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
z_native_finish();
return status;
}
host.dispatch = CreateWindowExW(0, window_class, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL,
cls.hInstance, NULL);
host.dispatch = CreateWindowExW(
0, window_class, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, cls.hInstance, NULL
);
if (!host.dispatch) {
z_native_finish();
return osError();
@ -1387,20 +1485,27 @@ uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
preferences();
return UHDK_STATUS_OK;
}
void z_native_run(void) {
void z_native_pump(uint64_t timeout_ns) {
uint64_t milliseconds = timeout_ns / 1000000 + (timeout_ns % 1000000 != 0);
DWORD timeout = timeout_ns == UINT64_MAX
? INFINITE
: (DWORD)(milliseconds >= INFINITE ? INFINITE - 1 : milliseconds);
DWORD result = MsgWaitForMultipleObjectsEx(0, NULL, timeout, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
if (result == WAIT_FAILED) {
z_native_failed(host.app, UHDK_STATUS_OS_ERROR);
host.running = FALSE;
return;
}
MSG message;
while (host.running) {
int result = GetMessageW(&message, NULL, 0, 0);
if (result <= 0) {
z_event e = {0};
e.type = UHDK_EVENT_QUIT_REQUESTED;
z_emit(host.app, &e);
if (result < 0)
break;
continue;
for (unsigned i = 0; i < 64 && PeekMessageW(&message, NULL, 0, 0, PM_REMOVE); ++i) {
if (message.message == WM_QUIT) {
z_event event = {0};
event.type = UHDK_EVENT_QUIT_REQUESTED;
z_emit(host.app, &event);
} else {
TranslateMessage(&message);
DispatchMessageW(&message);
}
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
void z_native_wake(void) {
@ -1410,13 +1515,6 @@ void z_native_wake(void) {
void z_native_again(void) {
z_native_wake();
}
void z_native_stop(void) {
host.running = FALSE;
if (host.dialog)
IFileDialog_Close(host.dialog, HRESULT_FROM_WIN32(ERROR_CANCELLED));
if (host.popup_id)
EndMenu();
}
void z_native_finish(void) {
if (host.dispatch) {
KillTimer(host.dispatch, 1);
@ -1441,12 +1539,6 @@ void z_native_finish(void) {
host.com_initialized = FALSE;
}
}
void *z_native_pool_push(void) {
return NULL;
}
void z_native_pool_pop(void *pool) {
(void)pool;
}
void z_native_cancel(uint64_t id) {
if (host.pending_dialog_id == id) {
host.pending_dialog = NULL;
@ -1463,19 +1555,27 @@ void z_native_cancel(uint64_t id) {
if (host.popup_id == id)
EndMenu();
}
static void destroyTray(void *native);
void z_native_destroy(uint32_t kind, void *native) {
if (!native)
return;
if (kind == Z_KIND_GL) {
Graphics *g = native;
if (kind == Z_KIND_TRAY) {
destroyTray(native);
} else if (kind == Z_KIND_GL) {
Window *w = native;
Graphics *g = w->graphics;
if (!g)
return;
EnterCriticalSection(&g->lock);
wglDeleteContext(g->rc);
ReleaseDC(g->window, g->dc);
LeaveCriticalSection(&g->lock);
DeleteCriticalSection(&g->lock);
profileFree(g);
w->graphics = NULL;
} else if (kind == Z_KIND_WINDOW) {
Window *w = native;
releasePointer(w, UHDK_CYCLE_CANCELLED);
Window **link = &host.windows;
while (*link && *link != w)
link = &(*link)->next;
@ -1574,7 +1674,7 @@ static uhdk_status clipboardRead(uint64_t id, uint64_t limit) {
profileFree(text);
return Z_DEFERRED;
}
static uhdk_status setIcon(const uhdk_image *image) {
static HICON createIcon(const uhdk_image *image) {
BITMAPV5HEADER header = {0};
header.bV5Size = sizeof(header);
header.bV5Width = (LONG)image->width;
@ -1591,10 +1691,10 @@ static uhdk_status setIcon(const uhdk_image *image) {
HBITMAP color = CreateDIBSection(dc, (BITMAPINFO *)&header, DIB_RGB_COLORS, &pixels, NULL, 0);
ReleaseDC(NULL, dc);
if (!color)
return UHDK_STATUS_OS_ERROR;
return NULL;
for (uint32_t y = 0; y < image->height; y++)
for (uint32_t x = 0; x < image->width; x++) {
const uint8_t *p = image->pixels.ptr + y * image->stride_bytes + x * 4;
const uint8_t *p = image->pixels.ptr + ((size_t)y * image->width + x) * 4;
uint8_t *out = (uint8_t *)pixels + ((size_t)y * image->width + x) * 4;
out[0] = (uint8_t)((uint32_t)p[2] * p[3] / 255);
out[1] = (uint8_t)((uint32_t)p[1] * p[3] / 255);
@ -1610,6 +1710,14 @@ static uhdk_status setIcon(const uhdk_image *image) {
DeleteObject(color);
if (mask)
DeleteObject(mask);
if (!icon)
return NULL;
return icon;
}
#include "tray.inc"
static uhdk_status setIcon(const uhdk_image *image) {
HICON icon = createIcon(image);
if (!icon)
return UHDK_STATUS_OS_ERROR;
for (Window *w = host.windows; w; w = w->next) {
@ -1621,9 +1729,15 @@ static uhdk_status setIcon(const uhdk_image *image) {
host.icon = icon;
return UHDK_STATUS_OK;
}
uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t request,
z_request_result *result) {
uhdk_status z_native_execute(
uhdk_session *app,
const z_command *cmd,
uint64_t request,
z_request_result *result
) {
(void)app;
(void)result;
Window *w =
cmd->target && z_object_kind(cmd->target) == Z_KIND_WINDOW ? windowOf(cmd->target) : NULL;
switch (cmd->op) {
@ -1633,19 +1747,23 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
return UHDK_STATUS_OUT_OF_MEMORY;
w->handle = cmd->target;
w->flags = cmd->window.flags;
w->style = cmd->window.style;
w->min_size = cmd->window.min_size;
w->max_size = cmd->window.max_size;
w->scale = 1;
w->cursor = LoadCursorW(NULL, IDC_ARROW);
DWORD style = cmd->window.flags & UHDK_WINDOW_DECORATED
? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX
: WS_POPUP;
if (cmd->window.flags & UHDK_WINDOW_RESIZABLE)
DWORD style =
cmd->window.style.decorated ? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX : WS_POPUP;
if (cmd->window.style.resizable)
style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
UINT dpi = GetDpiForSystem();
float scale = (float)dpi / 96;
RECT r = {0, 0, (LONG)(cmd->window.content_size.width * scale),
(LONG)(cmd->window.content_size.height * scale)};
RECT r = {
0,
0,
(LONG)(cmd->window.content_size.width * scale),
(LONG)(cmd->window.content_size.height * scale)
};
AdjustWindowRectExForDpi(&r, style, FALSE, 0, dpi);
WCHAR *title = wide(cmd->window.title);
if (!title) {
@ -1653,9 +1771,20 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
return UHDK_STATUS_OUT_OF_MEMORY;
}
HWND parent = cmd->window.parent ? windowOf(cmd->window.parent)->hwnd : NULL;
HWND hwnd = CreateWindowExW(0, window_class, title, style, CW_USEDEFAULT, CW_USEDEFAULT,
r.right - r.left, r.bottom - r.top, parent, NULL,
GetModuleHandleW(NULL), w);
HWND hwnd = CreateWindowExW(
0,
window_class,
title,
style,
CW_USEDEFAULT,
CW_USEDEFAULT,
r.right - r.left,
r.bottom - r.top,
parent,
NULL,
GetModuleHandleW(NULL),
w
);
profileFree(title);
if (!hwnd) {
profileFree(w);
@ -1665,7 +1794,6 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
w->next = host.windows;
host.windows = w;
z_object_set_native(cmd->target, w);
result->value.window = cmd->target;
if (host.icon) {
SendMessageW(hwnd, WM_SETICON, ICON_BIG, (LPARAM)host.icon);
SendMessageW(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)host.icon);
@ -1684,16 +1812,30 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
}
case Z_SIZE: {
RECT r = {0, 0, (LONG)(cmd->size.width * w->scale), (LONG)(cmd->size.height * w->scale)};
AdjustWindowRectExForDpi(&r, (DWORD)GetWindowLongPtrW(w->hwnd, GWL_STYLE),
GetMenu(w->hwnd) != NULL, 0, GetDpiForWindow(w->hwnd));
if (!SetWindowPos(w->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE))
AdjustWindowRectExForDpi(
&r,
(DWORD)GetWindowLongPtrW(w->hwnd, GWL_STYLE),
GetMenu(w->hwnd) != NULL,
0,
GetDpiForWindow(w->hwnd)
);
if (!SetWindowPos(
w->hwnd,
NULL,
0,
0,
r.right - r.left,
r.bottom - r.top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
))
return osError();
metrics(w);
break;
}
case Z_STATE: {
BOOL minimize = cmd->number == UHDK_WINDOW_MINIMIZED;
if (minimize)
releasePointer(w, UHDK_CYCLE_HIDDEN);
BOOL full = cmd->number == UHDK_WINDOW_FULLSCREEN || (minimize && w->fullscreen);
if (full && !w->fullscreen) {
if (IsIconic(w->hwnd))
@ -1705,17 +1847,25 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
m.cbSize = sizeof(m);
GetMonitorInfoW(MonitorFromWindow(w->hwnd, MONITOR_DEFAULTTONEAREST), &m);
w->fullscreen = TRUE;
SetWindowLongPtrW(w->hwnd, GWL_STYLE,
(w->saved_style & ~WS_OVERLAPPEDWINDOW) | WS_POPUP);
SetWindowPos(w->hwnd, HWND_TOP, m.rcMonitor.left, m.rcMonitor.top,
m.rcMonitor.right - m.rcMonitor.left, m.rcMonitor.bottom - m.rcMonitor.top,
SWP_FRAMECHANGED);
SetWindowLongPtrW(
w->hwnd, GWL_STYLE, (w->saved_style & ~WS_OVERLAPPEDWINDOW) | WS_POPUP
);
SetWindowPos(
w->hwnd,
HWND_TOP,
m.rcMonitor.left,
m.rcMonitor.top,
m.rcMonitor.right - m.rcMonitor.left,
m.rcMonitor.bottom - m.rcMonitor.top,
SWP_FRAMECHANGED
);
} else if (!full && w->fullscreen) {
w->fullscreen = FALSE;
SetWindowLongPtrW(w->hwnd, GWL_STYLE, w->saved_style);
SetWindowPlacement(w->hwnd, &w->placement);
SetWindowPos(w->hwnd, NULL, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
SetWindowPos(
w->hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED
);
}
if (minimize)
ShowWindow(w->hwnd, SW_MINIMIZE);
@ -1727,9 +1877,49 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
break;
}
case Z_VISIBLE:
if (!cmd->number)
releasePointer(w, UHDK_CYCLE_HIDDEN);
ShowWindow(w->hwnd, cmd->number ? SW_SHOWNOACTIVATE : SW_HIDE);
metrics(w);
break;
case Z_STYLE: {
DWORD style =
(DWORD)(w->fullscreen ? w->saved_style : GetWindowLongPtrW(w->hwnd, GWL_STYLE));
style &=
~(WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_POPUP);
style |= cmd->style.decorated ? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX : WS_POPUP;
if (cmd->style.resizable)
style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
if (w->fullscreen) {
w->saved_style = style;
w->style = cmd->style;
break;
}
RECT client, window;
GetClientRect(w->hwnd, &client);
GetWindowRect(w->hwnd, &window);
SetLastError(0);
if (!SetWindowLongPtrW(w->hwnd, GWL_STYLE, style) && GetLastError())
return osError();
RECT frame = {0, 0, client.right, client.bottom};
if (!AdjustWindowRectExForDpi(
&frame, style, GetMenu(w->hwnd) != NULL, 0, GetDpiForWindow(w->hwnd)
))
return osError();
if (!SetWindowPos(
w->hwnd,
NULL,
window.left,
window.top,
frame.right - frame.left,
frame.bottom - frame.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED
))
return osError();
w->style = cmd->style;
metrics(w);
break;
}
case Z_FOCUS:
ShowWindow(w->hwnd, SW_SHOW);
SetForegroundWindow(w->hwnd);
@ -1737,36 +1927,54 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
metrics(w);
break;
case Z_GL: {
uhdk_status status = createGraphics(w, cmd->other);
if (status == UHDK_STATUS_OK)
result->value.gl_context = cmd->other;
uhdk_status status = createGraphics(w);
return status;
}
case Z_CURSOR: {
LPCWSTR cursors[] = {IDC_ARROW, IDC_IBEAM, IDC_CROSS, IDC_HAND,
IDC_SIZEWE, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZENESW,
IDC_SIZEALL, IDC_NO, IDC_WAIT};
LPCWSTR cursors[] = {
IDC_ARROW,
IDC_IBEAM,
IDC_CROSS,
IDC_HAND,
IDC_SIZEWE,
IDC_SIZENS,
IDC_SIZENWSE,
IDC_SIZENESW,
IDC_SIZEALL,
IDC_NO,
IDC_WAIT
};
w->cursor =
cmd->number == UHDK_CURSOR_HIDDEN ? NULL : LoadCursorW(NULL, cursors[cmd->number]);
SetCursor(w->cursor);
break;
}
case Z_POINTER: {
if (w->pointer_mode == cmd->number)
break;
if (cmd->number == UHDK_POINTER_CONFINED) {
RECT rect;
POINT point;
if (GetFocus() != w->hwnd || GetForegroundWindow() != w->hwnd ||
!IsWindowVisible(w->hwnd) || IsIconic(w->hwnd) || !confinementRect(w, &rect) ||
!GetCursorPos(&point) || !PtInRect(&rect, point))
return UHDK_STATUS_UNAVAILABLE;
if (!ClipCursor(&rect))
return osError();
}
if (cmd->number == UHDK_POINTER_CAPTURE) {
SetCapture(w->hwnd);
if (GetCapture() != w->hwnd)
return UHDK_STATUS_OS_ERROR;
} else if (GetCapture() == w->hwnd) {
ReleaseCapture();
break;
}
z_event e = {0};
e.type = UHDK_EVENT_POINTER_MODE_CHANGED;
e.window = w->handle;
e.data.pointer_mode = (uint32_t)cmd->number;
z_emit(host.app, &e);
releasePointer(w, UHDK_CYCLE_CAPTURE_RELEASED);
if (cmd->number != UHDK_POINTER_NORMAL)
pointerModeEvent(w, (uint32_t)cmd->number, UHDK_CYCLE_CAPTURE_RELEASED);
break;
}
case Z_FUNCTION_KEYS:
w->function_key_policy = (uhdk_function_key_policy)cmd->number;
break;
case Z_TEXT_ENABLE:
w->text_enabled = !!cmd->number;
ImmAssociateContextEx(w->hwnd, NULL, w->text_enabled ? IACE_DEFAULT : 0);
@ -1854,12 +2062,6 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
profileFree(url);
return status > 32 ? UHDK_STATUS_OK : UHDK_STATUS_OS_ERROR;
}
case Z_WATCH: {
uhdk_status status = createWatch(cmd->target, cmd->other);
if (status == UHDK_STATUS_OK)
result->value.watch = cmd->other;
return status;
}
case Z_DESTROY: {
void *native = z_object_native(cmd->target);
z_object_set_native(cmd->target, NULL);

226
src/windows/tray.inc Normal file
View File

@ -0,0 +1,226 @@
/* Included after image/menu helpers. Each icon owns a hidden top-level HWND to
* receive Shell recovery broadcasts even when application windows are hidden. */
typedef struct Tray {
uhdk_tray *handle;
HWND window;
HICON icon;
GUID identity;
WCHAR tooltip[128];
BOOL added, destroyed;
unsigned refs;
HMENU tracking;
} Tray;
static const WCHAR tray_class[] = L"UHDK.Tray";
static UINT tray_restart;
#define Z_TRAY_MESSAGE (WM_APP + 20)
static NOTIFYICONDATAW trayData(Tray *t) {
NOTIFYICONDATAW data = {0};
data.cbSize = sizeof(data);
data.hWnd = t->window;
data.uID = 1;
data.guidItem = t->identity;
data.uFlags = NIF_GUID | NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP;
data.uCallbackMessage = Z_TRAY_MESSAGE;
data.hIcon = t->icon;
memcpy(data.szTip, t->tooltip, sizeof(t->tooltip));
return data;
}
static void traySync(Tray *t) {
NOTIFYICONDATAW data = trayData(t);
if (z_tray_desc(t->handle)->hidden) {
if (t->added)
Shell_NotifyIconW(NIM_DELETE, &data);
t->added = FALSE;
z_tray_state(t->handle, UHDK_FALSE, UHDK_STATUS_OK);
return;
}
BOOL was_added = t->added;
BOOL ok = Shell_NotifyIconW(was_added ? NIM_MODIFY : NIM_ADD, &data);
if (!ok && was_added)
ok = Shell_NotifyIconW(NIM_ADD, &data);
t->added = ok;
if (ok) {
data.uVersion = NOTIFYICON_VERSION_4;
if (!Shell_NotifyIconW(NIM_SETVERSION, &data)) {
Shell_NotifyIconW(NIM_DELETE, &data);
t->added = FALSE;
}
}
z_tray_state(
t->handle, (uhdk_bool)t->added, t->added ? UHDK_STATUS_OK : UHDK_STATUS_UNAVAILABLE
);
}
static void trayRelease(Tray *t) {
if (--t->refs == 0) {
if (t->icon)
DestroyIcon(t->icon);
profileFree(t);
}
}
static void trayMenu(Tray *t, POINT point) {
uhdk_menu *root = z_tray_desc(t->handle)->menu;
if (!root || t->tracking)
return;
HMENU menu = buildMenu(root, TRUE);
if (!menu)
return;
t->refs++;
uhdk_menu_retain(root);
t->tracking = menu;
if (point.x == -1 && point.y == -1) {
NOTIFYICONIDENTIFIER id = {0};
id.cbSize = sizeof(id);
id.hWnd = t->window;
id.uID = 1;
id.guidItem = t->identity;
RECT rect;
if (SUCCEEDED(Shell_NotifyIconGetRect(&id, &rect)))
point = (POINT){rect.left, rect.bottom};
else
GetCursorPos(&point);
}
SetForegroundWindow(t->window);
TrackPopupMenuEx(
menu, TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON, point.x, point.y, t->window, NULL
);
t->tracking = NULL;
if (!t->destroyed) {
PostMessageW(t->window, WM_NULL, 0, 0);
NOTIFYICONDATAW data = trayData(t);
Shell_NotifyIconW(NIM_SETFOCUS, &data);
}
DestroyMenu(menu);
uhdk_menu_release(root);
trayRelease(t);
}
static LRESULT CALLBACK trayProc(HWND window, UINT message, WPARAM wp, LPARAM lp) {
Tray *t = (Tray *)GetWindowLongPtrW(window, GWLP_USERDATA);
if (message == WM_NCCREATE) {
t = ((CREATESTRUCTW *)lp)->lpCreateParams;
t->window = window;
SetWindowLongPtrW(window, GWLP_USERDATA, (LONG_PTR)t);
}
if (!t || t->destroyed)
return DefWindowProcW(window, message, wp, lp);
if (tray_restart && message == tray_restart) {
t->added = FALSE;
traySync(t);
return 0;
}
if (message == Z_TRAY_MESSAGE) {
POINT point = {GET_X_LPARAM(wp), GET_Y_LPARAM(wp)};
switch (LOWORD(lp)) {
case NIN_SELECT:
case NIN_KEYSELECT:
if (z_tray_desc(t->handle)->menu_on_primary)
trayMenu(t, point);
else
z_tray_activate(t->handle, UHDK_TRAY_ACTIVATE_PRIMARY);
break;
case WM_CONTEXTMENU:
trayMenu(t, point);
break;
case WM_MBUTTONUP:
z_tray_activate(t->handle, UHDK_TRAY_ACTIVATE_SECONDARY);
break;
}
return 0;
}
if (message == WM_MENUCOMMAND && t->tracking) {
MENUITEMINFOW item = {0};
item.cbSize = sizeof(item);
item.fMask = MIIM_DATA;
if (GetMenuItemInfoW((HMENU)lp, (UINT)wp, TRUE, &item))
z_tray_command(t->handle, (const uhdk_menu_item *)item.dwItemData);
return 0;
}
return DefWindowProcW(window, message, wp, lp);
}
uhdk_status z_native_tray_update(uhdk_tray *handle, const uhdk_tray_desc *desc) {
HICON icon = createIcon(&desc->icon);
if (!icon)
return UHDK_STATUS_OS_ERROR;
WCHAR *tooltip = wide(desc->tooltip.len ? desc->tooltip : desc->title);
if (!tooltip) {
DestroyIcon(icon);
return UHDK_STATUS_OUT_OF_MEMORY;
}
Tray *t = z_object_native(handle);
if (!t) {
t = profileCalloc(1, sizeof(*t));
if (!t) {
DestroyIcon(icon);
profileFree(tooltip);
return UHDK_STATUS_OUT_OF_MEMORY;
}
t->handle = handle;
t->refs = 1;
/* Stable identity scoped by executable and application-defined item ID. */
uint64_t hashes[2] = {14695981039346656037ull, 7809847782465536322ull};
WCHAR executable[32768];
DWORD len = GetModuleFileNameW(NULL, executable, 32768);
for (unsigned j = 0; j < 2; j++) {
for (DWORD i = 0; i < len; i++)
hashes[j] = (hashes[j] ^ executable[i]) * 1099511628211ull;
for (uint64_t i = 0; i < desc->id.len; i++)
hashes[j] = (hashes[j] ^ (uint8_t)desc->id.ptr[i]) * 1099511628211ull;
}
memcpy(&t->identity, hashes, sizeof(t->identity));
WNDCLASSEXW cls = {0};
cls.cbSize = sizeof(cls);
cls.lpfnWndProc = trayProc;
cls.hInstance = GetModuleHandleW(NULL);
cls.lpszClassName = tray_class;
tray_restart = RegisterWindowMessageW(L"TaskbarCreated");
if ((!RegisterClassExW(&cls) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) ||
!CreateWindowExW(
WS_EX_TOOLWINDOW,
tray_class,
L"",
WS_POPUP,
0,
0,
0,
0,
NULL,
NULL,
cls.hInstance,
t
)) {
profileFree(t);
profileFree(tooltip);
DestroyIcon(icon);
return UHDK_STATUS_OS_ERROR;
}
z_object_set_native(handle, t);
}
if (t->tracking)
EndMenu();
if (t->icon)
DestroyIcon(t->icon);
t->icon = icon;
size_t length = wcslen(tooltip);
if (length > 127)
length = 127;
if (length && tooltip[length - 1] >= 0xd800 && tooltip[length - 1] <= 0xdbff)
length--;
memcpy(t->tooltip, tooltip, length * sizeof(WCHAR));
t->tooltip[length] = 0;
profileFree(tooltip);
traySync(t);
return UHDK_STATUS_OK;
}
static void destroyTray(void *native) {
Tray *t = native;
t->destroyed = TRUE;
if (t->tracking)
EndMenu();
NOTIFYICONDATAW data = trayData(t);
if (t->added)
Shell_NotifyIconW(NIM_DELETE, &data);
SetWindowLongPtrW(t->window, GWLP_USERDATA, 0);
DestroyWindow(t->window);
trayRelease(t);
}