added strata demo, C Sharp bindings, and bitmap font generator

This commit is contained in:
Peterino2 2026-09-19 09:35:04 -07:00
parent 6d9a0acf9a
commit 97bb36827f
25 changed files with 1165 additions and 142 deletions

View File

@ -22,6 +22,11 @@ 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_async`.
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.
## Experimental desktop input and window observations
macOS uses AppKit editing selectors. Windows and Wayland share Ctrl-based defaults
@ -98,6 +103,8 @@ must arrange its runtime location/rpath.
## C interface
- [Introduction and complete API reference](index.html): a self-contained webpage
covering the types, functions, and contracts in `uhdk.h`.
- [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.

View File

@ -2,11 +2,13 @@ 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 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 module = lib.root_module;
const install_lib = b.addInstallArtifact(lib, .{});
@ -15,18 +17,23 @@ 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,
@ -52,23 +62,29 @@ pub fn createLibrary(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
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 {
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,
});
const native = b.addTranslateC(.{
.root_source_file = b.path("src/native.h"),
.target = target,
.optimize = optimize,
});
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"),
@ -84,14 +100,20 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
@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/platform_io.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
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"} });
const lib = b.addLibrary(.{
.name = artifact_name,
.linkage = if (shared) .dynamic else .static,
.root_module = module,
});
// temp
// lib.root_module.strip = false;
return lib;
}

View File

@ -308,11 +308,18 @@ UHDK_API uhdk_status UHDK_CALL uhdk_app_get_stats(uhdk_app *app, uhdk_app_stats
*/
typedef uint32_t uhdk_window_flags;
enum {
UHDK_WINDOW_RESIZABLE = 1u << 0,
UHDK_WINDOW_DECORATED = 1u << 1,
UHDK_WINDOW_OPENGL = 1u << 3 /* Prepare a drawable for uhdk_gl_context_create. */
};
/* Native decorations are the title bar, border, and standard window controls.
* Disable them when the application paints and operates its own window chrome. */
typedef struct uhdk_window_style {
uint32_t struct_size;
uhdk_bool decorated;
uhdk_bool resizable;
uint16_t reserved;
} uhdk_window_style;
typedef uint32_t uhdk_window_state;
enum {
UHDK_WINDOW_NORMAL = 0,
@ -324,6 +331,7 @@ enum {
typedef struct uhdk_window_desc {
uint32_t struct_size;
uhdk_window_flags flags;
uhdk_window_style style;
uhdk_text title;
uhdk_size content_size;
uhdk_size min_size;
@ -393,6 +401,14 @@ UHDK_API uhdk_status UHDK_CALL uhdk_window_set_visible_async(
uhdk_bool visible,
uhdk_request_id *out
);
/* Change native decoration and resize styling without recreating the window.
* Completion acknowledges the native request; the window manager may apply it
* asynchronously. Content dimensions remain content-area dimensions. */
UHDK_API uhdk_status UHDK_CALL uhdk_window_set_style_async(
uhdk_window *window,
const uhdk_window_style *style,
uhdk_request_id *out
);
UHDK_API uhdk_status UHDK_CALL uhdk_window_request_focus_async(
uhdk_window *window,
uhdk_request_id *out

View File

@ -7,6 +7,8 @@ pkgs.mkShell {
pkgs.dbus
pkgs.wayland-scanner
pkgs.clang-tools
pkgs.rustc
pkgs.cargo
];
# NixOS does not put desktop libraries in the conventional loader search path.
# This affects running an unwrapped development executable, not compilation.

View File

@ -11,7 +11,6 @@ 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_dispatch: bool = false,

View File

@ -2,45 +2,49 @@
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.file) |file| file.close(self.io);
self.file = null;
if (self.atomic_file) |*file| file.deinit(self.io);
self.atomic_file = null;
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 {
@ -52,46 +56,21 @@ 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,
}
@ -104,7 +83,8 @@ 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]);
@ -114,19 +94,48 @@ 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;
@ -140,13 +149,13 @@ test "chunked replacement, bounded read, and cancellation before commit" {
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()) {
@ -158,11 +167,11 @@ 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();

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

@ -10,6 +10,7 @@ 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.
@ -30,22 +31,13 @@ pub export fn uhdk_app_create(desc: [*c]const c.uhdk_app_desc, out: [*c]?*c.uhdk
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;
};
const application = Application.create(gpa, MinimalIo.instance, abi.textBytes(desc.*.display_name)) 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;
application.use_application_thread = desc.*.use_application_thread != 0;
singleton = true;
const status = initialize(application);
@ -404,10 +396,6 @@ fn releaseStorage(application: *Application) void {
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;
}

View File

@ -11,13 +11,14 @@ pub export fn uhdk_window_create_async(
) abi.Status {
if (handle == null or !abi.validDescriptor(c.uhdk_window_desc, desc)) return abi.INVALID;
const d = desc.*;
if (!abi.validText(d.title, true) or
if (!validStyle(&d.style) or
!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;
d.flags & ~@as(u32, c.UHDK_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
@ -41,6 +42,13 @@ pub export fn uhdk_window_create_async(
return status;
}
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_destroy(handle: ?*c.uhdk_window) void {
if (handle) |_| runtime.destroyObject(runtime.fromObjectHandle(handle));
}
@ -82,6 +90,17 @@ pub export fn uhdk_window_set_visible_async(
return runtime.scalarCommand(handle, c.Z_KIND_WINDOW, c.Z_VISIBLE, @intCast(visible), out);
}
pub export fn uhdk_window_set_style_async(
handle: ?*c.uhdk_window,
style: [*c]const c.uhdk_window_style,
out: [*c]u64,
) 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.submit(runtime.fromObjectHandle(handle).app, command, out);
}
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);
}

View File

@ -1,22 +1,37 @@
//! 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();
@ -55,9 +70,31 @@ pub const Canvas = struct {
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();
@ -76,17 +113,29 @@ pub const Canvas = struct {
}
};
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

@ -9,8 +9,9 @@ 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.
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.
@ -85,7 +86,8 @@ 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.
windows remain possible, and `uhdk_window_set_style_async` can switch the
decoration request at runtime. 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
app ID. Applications own their desktop-file and icon installation.
- A window is created hidden after its first configure. Showing requests mapping;

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.
@ -14,10 +15,12 @@ The source is the unmodified Google Fonts Roboto variable TTF, pinned in
derivative distributed under the accompanying SIL Open Font License (`OFL.txt`).
The TTF is downloaded only for maintainer regeneration and is not shipped here.
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:

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

@ -48,6 +48,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,
@ -399,7 +400,7 @@ fn decorationConfigure(data: ?*anyopaque, _: ?*c.struct_zxdg_toplevel_decoration
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 {
@ -475,9 +476,9 @@ 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);
@ -510,18 +511,12 @@ 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);
@ -534,8 +529,33 @@ fn setupWindow(b: *Backend, w: *Window, desc: n.uhdk_window_desc) u32 {
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.?;
@ -597,17 +617,11 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
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) {
@ -638,6 +652,7 @@ export fn z_native_execute(_: ?*n.uhdk_app, raw: [*c]const n.z_command, id: u64,
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),

View File

@ -62,7 +62,8 @@ 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.flags = UHDK_WINDOW_OPENGL;
desc.style = (uhdk_window_style){sizeof(uhdk_window_style), 1, 1, 0};
desc.content_size = (uhdk_size){320, 240};
return desc;
}
@ -109,6 +110,13 @@ static void test_main(uhdk_app *app, void *user) {
native.struct_size = sizeof(native);
OK(uhdk_window_get_native(w, &native));
assert(native.backend == UHDK_BACKEND_WAYLAND && native.primary && native.secondary);
uhdk_window_style style = {sizeof(style), 0, 0, 0};
OK(uhdk_window_set_style_async(w, &style, &id));
OK(wait_request(app, id).status);
style.decorated = 1;
style.resizable = 1;
OK(uhdk_window_set_style_async(w, &style, &id));
OK(wait_request(app, id).status);
const uint8_t path[] = "/tmp/uhdk file-%\xff";
uhdk_file *file;

View File

@ -40,7 +40,7 @@ static uhdk_window *window(uhdk_app *app) {
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;
desc.style = (uhdk_window_style){sizeof(uhdk_window_style), 1, 1, 0};
uint64_t id;
OK(uhdk_window_create_async(app, &desc, &id));
uhdk_request_result r = wait_result(app, id);

View File

@ -32,7 +32,7 @@ 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>')))
codepoints = list(range(32, 127))
header_size = 8 + len(codepoints) * 16
records, pixels = bytearray(), bytearray()
for cp in codepoints:
@ -48,6 +48,49 @@ def generate(manifest, font_path):
return b'UF16' + struct.pack('<I', len(codepoints)) + records + pixels
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 pack(data):
assert data[:4] == b'UF16'
count, = struct.unpack_from('<I', data, 4)
records = bytearray(12 * count)
streams = bytearray()
fallback = None
for index in range(count):
cp, offset, width, height, x, y, advance = struct.unpack_from('<IIBBbbB', data, 8 + index * 16)
assert cp <= 0xffff
pixels = data[offset:offset + width * height]
samples = [(value + 8) // 17 for value in pixels]
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)
packed_offset = 8 + len(records) + len(streams)
assert packed_offset <= 0xffff and len(encoded) <= 0xffff
struct.pack_into('<HHHBBbbBB', records, index * 12, cp, packed_offset, len(encoded), width, height, x, y, advance, 0)
streams += encoded
if cp == ord('?') and fallback is None:
fallback = index
if cp == 0xfffd:
fallback = index
assert fallback is not None
result = b'FAP1' + struct.pack('<HH', count, fallback) + records + streams
assert len(result) <= 0xffff
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
mode = parser.add_mutually_exclusive_group(required=True)
@ -58,12 +101,12 @@ def main():
args = parser.parse_args()
manifest = json.loads((ROOT / 'manifest.json').read_text())
if args.regenerate or args.verify_generation:
data = generate(manifest, args.font)
data = pack(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

@ -56,6 +56,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;
@ -1472,11 +1473,12 @@ 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);
@ -1529,6 +1531,20 @@ 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];

View File

@ -61,6 +61,7 @@ enum {
Z_SIZE,
Z_STATE,
Z_VISIBLE,
Z_STYLE,
Z_FOCUS,
Z_GL,
Z_CURSOR,
@ -102,6 +103,7 @@ typedef struct z_command {
uhdk_size size;
uhdk_point point;
uhdk_window_desc window;
uhdk_window_style style;
uhdk_text_state text_state;
uhdk_file_dialog_desc dialog;
uhdk_image image;
@ -126,6 +128,51 @@ uhdk_status z_native_gl_proc(void *context, uhdk_text, uhdk_gl_proc *);
void z_native_handles(void *, uhdk_native_window *);
/* 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_dispatch(uhdk_app *);
void z_emit(uhdk_app *, const z_event *);

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

@ -17,6 +17,7 @@ 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("arenas.zig");
if (@import("builtin").os.tag == .linux) {

View File

@ -542,7 +542,6 @@ pub fn fileStep(application: *Application, command: *Request) bool {
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,
@ -565,7 +564,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,

View File

@ -55,6 +55,7 @@ struct Window {
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;
@ -1648,14 +1649,15 @@ 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
DWORD style = cmd->window.style.decorated
? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX
: WS_POPUP;
if (cmd->window.flags & UHDK_WINDOW_RESIZABLE)
if (cmd->window.style.resizable)
style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
UINT dpi = GetDpiForSystem();
float scale = (float)dpi / 96;
@ -1745,6 +1747,37 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
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);