From 97bb36827fcbfa88e8f03ea190a23326250bb26f Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Sat, 19 Sep 2026 09:35:04 -0700 Subject: [PATCH] added strata demo, C Sharp bindings, and bitmap font generator --- README.md | 7 + build.zig | 30 +- include/uhdk.h | 20 +- shell.nix | 2 + src/Application.zig | 1 - src/FileOperation.zig | 113 ++--- src/MinimalIo.zig | 61 +++ src/api/app.zig | 16 +- src/api/windows.zig | 23 +- src/linux/Bitmap.zig | 91 +++- src/linux/README.md | 8 +- src/linux/font/README.md | 19 +- src/linux/font/manifest.json | 2 +- src/linux/font/roboto-16.bin | Bin 24191 -> 0 bytes src/linux/font/roboto-16.fontatlas | Bin 0 -> 5803 bytes src/linux/native.zig | 57 ++- src/linux/tests/native.c | 10 +- src/linux/tests/services.c | 2 +- src/linux/tools/bitmap-font.py | 53 ++- src/macos/native.m | 20 +- src/native.h | 47 ++ src/platform_io.c | 684 +++++++++++++++++++++++++++++ src/root.zig | 1 + src/runtime.zig | 3 +- src/windows/native.c | 37 +- 25 files changed, 1165 insertions(+), 142 deletions(-) create mode 100644 src/MinimalIo.zig delete mode 100644 src/linux/font/roboto-16.bin create mode 100644 src/linux/font/roboto-16.fontatlas create mode 100644 src/platform_io.c diff --git a/README.md b/README.md index 1186f9e..8a4a81c 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/build.zig b/build.zig index 55fec6b..33d817c 100644 --- a/build.zig +++ b/build.zig @@ -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; } diff --git a/include/uhdk.h b/include/uhdk.h index 1dfc144..77dff37 100644 --- a/include/uhdk.h +++ b/include/uhdk.h @@ -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 diff --git a/shell.nix b/shell.nix index cb6f1af..0643483 100644 --- a/shell.nix +++ b/shell.nix @@ -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. diff --git a/src/Application.zig b/src/Application.zig index 2950b7b..006986c 100644 --- a/src/Application.zig +++ b/src/Application.zig @@ -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, diff --git a/src/FileOperation.zig b/src/FileOperation.zig index 4375e8e..3e6a332 100644 --- a/src/FileOperation.zig +++ b/src/FileOperation.zig @@ -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(); diff --git a/src/MinimalIo.zig b/src/MinimalIo.zig new file mode 100644 index 0000000..33f24a3 --- /dev/null +++ b/src/MinimalIo.zig @@ -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); +} diff --git a/src/api/app.zig b/src/api/app.zig index fa9eb2a..779295d 100644 --- a/src/api/app.zig +++ b/src/api/app.zig @@ -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; } diff --git a/src/api/windows.zig b/src/api/windows.zig index 56b9061..f16f720 100644 --- a/src/api/windows.zig +++ b/src/api/windows.zig @@ -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); } diff --git a/src/linux/Bitmap.zig b/src/linux/Bitmap.zig index 55d4dcc..bcad1e4 100644 --- a/src/linux/Bitmap.zig +++ b/src/linux/Bitmap.zig @@ -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("�"), 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); diff --git a/src/linux/README.md b/src/linux/README.md index e3df311..d2adcb0 100644 --- a/src/linux/README.md +++ b/src/linux/README.md @@ -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; diff --git a/src/linux/font/README.md b/src/linux/font/README.md index 4f8af7a..f557748 100644 --- a/src/linux/font/README.md +++ b/src/linux/font/README.md @@ -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: diff --git a/src/linux/font/manifest.json b/src/linux/font/manifest.json index 8e518c9..a26cd1f 100644 --- a/src/linux/font/manifest.json +++ b/src/linux/font/manifest.json @@ -18,6 +18,6 @@ "freetype": "2.13.3" }, "generated": { - "roboto-16.bin": "23bfe858a9ff398b3826d836bb815255ced0e50ac7f695b2d9309a15b32d335e" + "roboto-16.fontatlas": "6fe87564a24392257fc03e48a7044e18b69d07e9a3461be502c8a1f99fefcab3" } } diff --git a/src/linux/font/roboto-16.bin b/src/linux/font/roboto-16.bin deleted file mode 100644 index 6e652e61380e3b1da1de11e3c33f97a9c2ad6e07..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 24191 zcmd^n2UJx@*Y@Vpn<$7a8Z|1hpkhY_!CqtUVz05p-h1zgXpAvpiAIg0v5UR8#D;Fv(<>^b*vug3i0ePiBat$(jI=j>-@PoKS~oVmAKiyC$B5K$SpCpJVTc(W_3 zVjD_f`~{qaEs-g(Dfn`5&48_dt-zOuI}2=SNAE1bSAc6;fXD{nNS2)79s;ZKUjnza zBQi#~G5CsbV}Z>IQ8K4r2`)&7&A?ZNYgmxT9P;MitH7-VwzQ;l&d(X{6|k`hX*s>B zaIwIqW|YO{uLfsT2zAqtmT`4Bdth^0B|R75F~F8cpVO-W_tXH_1a5Ax53dD$*Z|iC zF6E#PuLHc?0M`XhHNf?N2Nu@Ly8_=a!1aOaJLvDX#_U|SPl08zRVc)WqD7yFNzWsu%lFT6E%iQ0k%ds_iq!p zX~p#Y*AzI>05=03QCyL?2HzYm7Fcc17Qj7A=y6NntH7K-%eP|pnI5+Wz71@GaIS9~ zxEx?Ly|%z3O6tqk4mcKA4gU(bXDQSN@wqjXRx*t&pH zzRtiU%IL$p0Q(r=uE17M8g+bk172W&y8~w#;2yvepj2x4dIFayr;pzY*vA0(2DU1% z5AOrK0NB)ylDU1n;O+pcJ5XlgHCwxJ$t5cp3t138hxUhXPLqR>Ow@p93~Sd^7OF;Y^|QkeB*90(iWF zW%^$OhXAYn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W{e&^`epC`pVO3${MR4Fzj`l?qK~r;_fL+vb(YmJ zPr?Cz;Rg>jN};@litE}qG}Ot8KT?!XQ_Qk1oZ&2`)j^bjJ|Q|5;( iZXr;lt6!=y=y1h4qoppCU-tKPg;V_sH&eMkdH)~78QOaQ diff --git a/src/linux/font/roboto-16.fontatlas b/src/linux/font/roboto-16.fontatlas new file mode 100644 index 0000000000000000000000000000000000000000..1221abf31f2462b0d6275edd284124fe4ab4ede4 GIT binary patch literal 5803 zcma)94RjmTmA-G@%xI*MfCPnQS$?eW(=C)l z_sQV^+s0NGc9*8a(b?{v!V(hooZZtd35i;^l%{DSI2)3*1GuK`fnH!}L)zY&%5q|ie2Kq$O{Z!QHbb1Md0otH5XpP=T zKF~folREW<BoQv_fA*uTIey(|=FVmyq9@Uy+$d*IVHV zeJMR-U0tCsqm9;;75Z`-wQSO%vrgZ@=qG8@u%s)<@rK9(-=Zt2&U+GhEgJFCd|K$O zsqh=<0dE~y(AlC!dfEFB1*>Qgl?TaDf1{jI(;z(fu$flMjNJIT+ywC`lipV&~Z9#Mp;kn zwUq9jq93Op&p4e-%r)o<+A!nnivCYh7x;!vg9bfC@`TAXze|^%Fe&r5bk7NwlOJ>a z^gVjzgs)ZRK24iXxX{Hdu>B16Pw~G`C(XQw%qllmJWDsuoJ~3~pwlvXXyzQ(FW@hy zf0{XiY{arnRcZgkm9i(UR>?N|z4>?aIXC8ir3FrXNofzWS7|q8Ob$4qobKFQGcYY) zDwWo=mh${eX<6fG_V$Aja*EXrg0=q$2bK0p#4gWdMT?UnuPg00B@Y|LJ4eh^fN6{S zlkuupOHxaBo~X3OL-UjJgTR2n+K|@4Mm!X6e`-BM#@dCVI;BOvu#$S$^t&Ao(;n8a zC*yI+9>Fs5h47QA{BeudT?Y}y8md>V^ zYFIWlJIyR>TjDiJ>p5g7QEX6JxVK%|IeX}=hJul5tLgW!J?2Y4_MMXL?CQLu-6({E zpM(QHVBySSk@2zkP%u5pA`)Ve^0UZ#S>&ywfA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eRPdqfRZSfD5G0t7^&}Vq&9Gj0vaJ#W)%X<>A8{VUH0z&*Y+KroEiDtoBAKR3)b)e literal 0 HcmV?d00001 diff --git a/src/linux/native.zig b/src/linux/native.zig index 6296894..25525d7 100644 --- a/src/linux/native.zig +++ b/src/linux/native.zig @@ -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), diff --git a/src/linux/tests/native.c b/src/linux/tests/native.c index adad69b..21a522d 100644 --- a/src/linux/tests/native.c +++ b/src/linux/tests/native.c @@ -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; diff --git a/src/linux/tests/services.c b/src/linux/tests/services.c index 4826822..91650b8 100644 --- a/src/linux/tests/services.c +++ b/src/linux/tests/services.c @@ -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); diff --git a/src/linux/tools/bitmap-font.py b/src/linux/tools/bitmap-font.py index 4701f95..348354c 100644 --- a/src/linux/tools/bitmap-font.py +++ b/src/linux/tools/bitmap-font.py @@ -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, '–—‘’“”…•€←↑→↓�'))) + 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('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]; diff --git a/src/native.h b/src/native.h index 39a5d4d..55c72b7 100644 --- a/src/native.h +++ b/src/native.h @@ -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 *); diff --git a/src/platform_io.c b/src/platform_io.c new file mode 100644 index 0000000..7fab265 --- /dev/null +++ b/src/platform_io.c @@ -0,0 +1,684 @@ +#ifndef _WIN32 +#define _GNU_SOURCE +#define _DARWIN_C_SOURCE +#endif +#include "native.h" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include + +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 +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#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 diff --git a/src/root.zig b/src/root.zig index f53fa16..f5cb538 100644 --- a/src/root.zig +++ b/src/root.zig @@ -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) { diff --git a/src/runtime.zig b/src/runtime.zig index 6e5fb33..2e554fe 100644 --- a/src/runtime.zig +++ b/src/runtime.zig @@ -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, diff --git a/src/windows/native.c b/src/windows/native.c index cefa978..9526533 100644 --- a/src/windows/native.c +++ b/src/windows/native.c @@ -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);