big overhual to lifecycle and opting for significant simplification of api

This commit is contained in:
Peterino2 2026-09-19 13:09:20 -07:00
parent f6686e66ec
commit 22a462481a
12 changed files with 604 additions and 110 deletions

View File

@ -27,12 +27,13 @@ window is created and can be changed later with `uhdk_window_set_style`.
Set `decorated` to false for application-drawn chrome; on Wayland this requests 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. client-side decoration instead of the compositor's usual title bar and border.
The recommended window path queues `uhdk_window_create` and The primary application path is `uhdk_open` followed by one
`uhdk_gl_context_create` in setup order and returns stable handles immediately. `uhdk_next_frame`/`uhdk_end_frame` loop. It creates a visible window and current
Window value commands do not create completion requests. Native creation failures OpenGL context before returning, reports events and framebuffer metrics together,
arrive as `UHDK_EVENT_RESOURCE_FAILED`; normal metrics and redraw events indicate and handles presentation at the frame boundary. The lower-level window/context
when a window can render. `uhdk_gl_context_try_begin_frame` combines that readiness API remains available for additional windows and custom thread layouts. Its create
check with the framebuffer metrics needed by a renderer. calls return stable handles immediately, and native creation failures arrive as
`UHDK_EVENT_RESOURCE_FAILED`.
## Experimental desktop input and window observations ## Experimental desktop input and window observations
@ -151,7 +152,78 @@ are not implemented. Native UTF-16 path bytes are kept separately from the WTF-8
paths passed to Zig I/O. If a native path cannot be exported losslessly as a shell paths passed to Zig I/O. If a native path cannot be exported losslessly as a shell
URI, URI export returns `UNSUPPORTED`; native-path export still preserves it. URI, URI export returns `UNSUPPORTED`; native-path export still preserves it.
## Application lifecycle ## Session loop
`uhdk_open` is the default setup path. Pass NULL for defaults, or zero-initialize
`uhdk_options`, set `struct_size`, and override the options you need. Successful
setup returns a visible window, a current OpenGL 3.3-or-newer core context, and a
loaded GL function table. Setup failures unwind all resources.
```c
#define UHDK_ENABLE_OPENGL
#include "uhdk.h"
int main(void) {
uhdk_options options = {0};
options.struct_size = sizeof(options);
options.title = (uhdk_text){"Hello UHDK", 10};
options.content_size = (uhdk_size){800, 600};
uhdk_session *session = 0;
if (uhdk_open(&options, &session) != UHDK_STATUS_OK)
return 1;
uhdk_app *app = uhdk_get_app(session);
/* Create shaders, textures, etc. using uhdk_get_gl(session) here. */
uhdk_frame frame;
uhdk_status status = UHDK_STATUS_OK;
while (uhdk_next_frame(session, &frame)) {
for (uint64_t i = 0; i < frame.events.len; ++i) {
uint32_t type = frame.events.ptr[i].type;
if (type == UHDK_EVENT_WINDOW_CLOSE_REQUESTED ||
type == UHDK_EVENT_QUIT_REQUESTED)
uhdk_app_quit(app);
}
if (frame.drawable) {
frame.gl->Viewport(0, 0, frame.metrics.framebuffer_width,
frame.metrics.framebuffer_height);
frame.gl->ClearColor(0.1f, 0.15f, 0.2f, 1.0f);
frame.gl->Clear(GL_COLOR_BUFFER_BIT);
}
status = uhdk_end_frame(session);
if (status != UHDK_STATUS_OK)
break;
}
if (status == UHDK_STATUS_OK)
status = uhdk_get_status(session);
/* Delete application GL resources here, while the context is current. */
uhdk_close(session);
return status == UHDK_STATUS_OK ? 0 : 1;
}
```
All session/application/GL work stays on OS main. `next_frame` releases native GL
locks, pumps native work and worker completions, then restores the current context.
`end_frame` presents drawable iterations. Every successful `next_frame` needs an
`end_frame`, including event-only iterations. `close` can discard an unfinished
iteration without presenting it. Do not poll or manage GL brackets manually for
a session, and do not destroy its borrowed app/window/context handles separately.
Continuous mode is the default and requests vsync. `UHDK_RENDER_ON_DEMAND` waits
for events or wake deadlines after the first iteration. Repaint the complete
framebuffer whenever `drawable` is true. Hidden/minimized windows still receive
events, and `uhdk_app_wake` or a wake deadline can schedule application work.
The first iteration never waits. Session GL calls are valid before, during and
after iterations until close; drawing to the window is conditional on `drawable`.
A fatal native/driver error may prevent further GL work, including cleanup.
Accept close/quit requests with `uhdk_app_quit`. Keep iterating to drain request
completions and `STOPPED`; then `next_frame` returns false and `get_status` returns
OK. Failures also end the loop, with a non-OK status. An early `close` abandons
undelivered results and drains internal teardown. File workers stay independent,
although their results reach the application at frame boundaries. Long main-thread
updates delay native event handling.
## Low-level application lifecycle
Set `uhdk_app_desc.use_application_thread` before `uhdk_app_create`: Set `uhdk_app_desc.use_application_thread` before `uhdk_app_create`:
@ -177,8 +249,7 @@ ownership established. It honors the flag, creating and joining the application
thread when enabled. Its callback owns its loop and must not attach/detach/destroy. thread when enabled. Its callback owns its loop and must not attach/detach/destroy.
The caller must destroy the app after run returns, including on run failure. The caller must destroy the app after run returns, including on run failure.
The caller decides when to poll, update, and render; there are no application tick Low-level applications decide when to poll, update, and render. Use `UHDK_PROFILE_BEGIN`/`UHDK_PROFILE_END` for application phases. Frame stats
APIs. Use `UHDK_PROFILE_BEGIN`/`UHDK_PROFILE_END` for application phases. Frame stats
report rendering CPU time and presentation cadence, not combined update time. report rendering CPU time and presentation cadence, not combined update time.
Poll outside GL frame brackets. Zero timeout does not intentionally wait; native Poll outside GL frame brackets. Zero timeout does not intentionally wait; native
modal handling may exceed finite wait budgets. When app code runs on main, long modal handling may exceed finite wait budgets. When app code runs on main, long
@ -222,7 +293,7 @@ copies only its pointers. Retain file/menu references when needed beyond a poll,
but even retained handles cannot outlive the app. but even retained handles cannot outlive the app.
UHDK is pre-release: API and ABI compatibility with earlier revisions is not UHDK is pre-release: API and ABI compatibility with earlier revisions is not
guaranteed. Set creation descriptors to `UHDK_ABI_VERSION`. Event envelopes have guaranteed. Low-level app descriptors set `abi_version` to `UHDK_ABI_VERSION`; session options do not require it. Event envelopes have
a fixed array stride within each returned batch. a fixed array stride within each returned batch.
The scratch arena is maintained as UHDK-owned code in The scratch arena is maintained as UHDK-owned code in

View File

@ -77,6 +77,7 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
.optimize = optimize, .optimize = optimize,
}); });
native.defineCMacro("UHDK_ENABLE_OPENGL", "1");
native.addIncludePath(b.path("include")); native.addIncludePath(b.path("include"));
module.addImport("native", native.createModule()); module.addImport("native", native.createModule());
module.addImport("profile", createProfileModule(b, target, optimize, instrumented)); module.addImport("profile", createProfileModule(b, target, optimize, instrumented));
@ -103,6 +104,7 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize:
module.addCSourceFile(.{ .file = b.path("src/windows/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DUNICODE", "-D_UNICODE" } }); 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", "api-ms-win-core-synch-l1-2-0" }) |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/gl_loader.c"), .flags = &.{ "-std=c99", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden" } });
module.addCSourceFile(.{ .file = b.path("src/platform_io.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); module.addCSourceFile(.{ .file = b.path("src/platform_io.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
const lib = b.addLibrary(.{ const lib = b.addLibrary(.{

View File

@ -145,6 +145,10 @@ enum {
UHDK_STATUS_BUFFER_TOO_SMALL = 11 UHDK_STATUS_BUFFER_TOO_SMALL = 11
}; };
typedef struct uhdk_session uhdk_session;
/* Opaque unless UHDK_ENABLE_OPENGL is defined; then this is the bundled
* GladGLContext function table. Owned by the session and valid until close. */
typedef struct GladGLContext uhdk_gl_functions;
typedef struct uhdk_app uhdk_app; typedef struct uhdk_app uhdk_app;
typedef struct uhdk_window uhdk_window; typedef struct uhdk_window uhdk_window;
typedef struct uhdk_gl_context uhdk_gl_context; typedef struct uhdk_gl_context uhdk_gl_context;
@ -304,6 +308,7 @@ UHDK_API uhdk_status UHDK_CALL uhdk_request_cancel(uhdk_app *app, uhdk_request_i
/* Rendering CPU time excludes swap_buffers, blocked waits and descheduling. /* Rendering CPU time excludes swap_buffers, blocked waits and descheduling.
* A presented begin_frame/end_frame bracket updates render_time_ns/frame_count. * A presented begin_frame/end_frame bracket updates render_time_ns/frame_count.
* Session render_time_ns includes application update work within the iteration.
* frames_per_second uses wall time between presented end_frame calls; it is zero * frames_per_second uses wall time between presented end_frame calls; it is zero
* before two presentations and retains its last sample while idle. event_count * before two presentations and retains its last sample while idle. event_count
* counts polled events. Use profiling markers for application-defined work. */ * counts polled events. Use profiling markers for application-defined work. */
@ -391,6 +396,75 @@ typedef struct uhdk_window_metrics {
uhdk_bool suspended; uhdk_bool suspended;
} uhdk_window_metrics; } uhdk_window_metrics;
/* Primary application API. All session calls belong to OS main. Native events
* are pumped by next_frame; filesystem work runs independently on I/O workers.
* The session owns its app, first window and GL context. Borrowed handles must
* not be destroyed separately or used with app_run/poll or manual GL brackets.
* Use a low-level application for custom threading or multiple GL contexts.
*/
typedef uint32_t uhdk_render_mode;
enum {
UHDK_RENDER_CONTINUOUS = 0,
UHDK_RENDER_ON_DEMAND = 1
};
typedef struct uhdk_options {
uint32_t struct_size;
uhdk_render_mode render_mode;
uhdk_text application_id;
uhdk_text title;
uhdk_size content_size; /* Zero components default to 800 x 600. */
uhdk_size min_size;
uhdk_size max_size;
uhdk_backend preferred_backend;
uhdk_bool undecorated; /* Zero defaults to decorated and resizable. */
uhdk_bool fixed_size;
uhdk_bool disable_vsync; /* Zero requests vsync; unsupported control is tolerated. */
uhdk_bool request_focus;
uint64_t startup_timeout_ns; /* Native resource readiness wait; zero = 10 seconds. */
} uhdk_options;
typedef struct uhdk_frame {
const uhdk_gl_functions *gl;
uhdk_event_list events;
uhdk_window_metrics metrics;
uhdk_bool drawable;
} uhdk_frame;
/* NULL options selects defaults. Otherwise zero-initialize and set struct_size.
* Creates native services, a visible window, and a current OpenGL >=3.3 core
* context before returning OK. Failure cleans up and sets *out=NULL. Startup
* pumps native events internally and preserves them for the first frame.
* GL resources may be created immediately with get_gl: the bundled OpenGL 3.3
* function table is already loaded. No application callbacks execute during setup.
*/
UHDK_API uhdk_status UHDK_CALL uhdk_open(const uhdk_options *options, uhdk_session **out);
/* Begin one application iteration, including event-only iterations when hidden
* or minimized. Each successful call requires end_frame, even if not drawable.
* Events remain borrowed until the next next_frame or close. Continuous mode
* polls without waiting while drawable; on-demand mode waits for events/wakes.
* The first iteration never waits. A drawable iteration should repaint the
* complete window framebuffer. False means stopped or failed; get_status
* distinguishes normal termination (OK) from an error. No frame opens on false.
* STOPPED and final request completions are delivered before normal termination.
*/
UHDK_API uhdk_bool UHDK_CALL uhdk_next_frame(uhdk_session *session, uhdk_frame *out);
/* Presents drawable frames and finishes the iteration. The context remains
* current for resource work between iterations, including shutdown. Call quit
* to accept a close/quit request; this suppresses presentation during draining.
* Native changes are applied at the next frame boundary. Never block waiting
* for native requests between boundaries. GL calls stay on OS main.
*/
UHDK_API uhdk_status UHDK_CALL uhdk_end_frame(uhdk_session *session);
UHDK_API uhdk_status UHDK_CALL uhdk_get_status(uhdk_session *session);
UHDK_API const uhdk_gl_functions *UHDK_CALL uhdk_get_gl(uhdk_session *session);
UHDK_API uhdk_app *UHDK_CALL uhdk_get_app(uhdk_session *session);
UHDK_API uhdk_window *UHDK_CALL uhdk_get_window(uhdk_session *session);
UHDK_API uhdk_gl_context *UHDK_CALL uhdk_get_context(uhdk_session *session);
/* NULL safe. Discards an unfinished frame without presenting. Destroy app-owned
* GL resources before close; all session handles become invalid on return. */
UHDK_API void UHDK_CALL uhdk_close(uhdk_session *session);
/* Queue native creation and return a stable handle immediately. Creation /* Queue native creation and return a stable handle immediately. Creation
* failures arrive as RESOURCE_FAILED; success is observed through normal * failures arrive as RESOURCE_FAILED; success is observed through normal
* window metrics/redraw events. */ * window metrics/redraw events. */
@ -432,8 +506,10 @@ UHDK_API void UHDK_CALL uhdk_window_invalidate(uhdk_window *window); /* Coalesce
* *
* One context per window. Create does NOT change the current context. Explicitly * One context per window. Create does NOT change the current context. Explicitly
* begin_frame locks drawable updates and makes it current; end_frame unlocks. * begin_frame locks drawable updates and makes it current; end_frame unlocks.
* ALL raw GL calls (including initialization and deletion) and presentation must * For low-level applications, ALL raw GL calls (including initialization and
* be inside this bracket. Never wait for platform results inside a bracket. * deletion) and presentation must be inside this bracket. Sessions manage these
* brackets internally; their context is current from open until close.
* Never wait for platform results inside a bracket.
* make_current/clear_current are also available inside a bracket. * make_current/clear_current are also available inside a bracket.
* Contexts cannot migrate to another thread. Destroy detaches a current context; * Contexts cannot migrate to another thread. Destroy detaches a current context;
* window destruction also destroys its context and invalidates the handle. * window destruction also destroys its context and invalidates the handle.

View File

@ -60,6 +60,14 @@ user: ?*anyopaque = null,
preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences), preferences: c.uhdk_preferences = std.mem.zeroes(c.uhdk_preferences),
stats: c.uhdk_app_stats = std.mem.zeroes(c.uhdk_app_stats), stats: c.uhdk_app_stats = std.mem.zeroes(c.uhdk_app_stats),
last_frame_time: ?u64 = null, last_frame_time: ?u64 = null,
session_gl: c.uhdk_gl_functions = std.mem.zeroes(c.uhdk_gl_functions),
session_window: ?*c.uhdk_window = null,
session_context: ?*c.uhdk_gl_context = null,
session_status: abi.Status = abi.OK,
session_active: bool = false,
session_drawable: bool = false,
session_first: bool = true,
session_on_demand: bool = false,
pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application { pub fn create(gpa: std.mem.Allocator, io: std.Io, name: []const u8) !*Application {
const self = try gpa.create(Application); const self = try gpa.create(Application);
errdefer gpa.destroy(self); errdefer gpa.destroy(self);

View File

@ -11,6 +11,7 @@ arena: std.heap.ArenaAllocator,
next: ?*Resource = null, next: ?*Resource = null,
alive: bool = true, alive: bool = true,
ready: bool, ready: bool,
creation_status: u32 = 0,
refs: usize = 1, refs: usize = 1,
native: ?*anyopaque = null, native: ?*anyopaque = null,
payload: Payload, payload: Payload,

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

@ -0,0 +1,185 @@
//! Main-thread application iterations. Native work runs only outside GL ownership.
const std = @import("std");
const c = @import("native");
const abi = @import("../abi.zig");
const runtime = @import("../runtime.zig");
const Application = @import("../Application.zig");
const app = @import("app.zig");
const windows = @import("windows.zig");
const graphics = @import("graphics.zig");
fn state(session: *c.uhdk_session) *Application {
return @ptrCast(@alignCast(session));
}
fn handle(a: *Application) *c.uhdk_app {
return runtime.toAppHandle(a);
}
fn acquire(a: *Application) abi.Status {
const context = a.session_context orelse return abi.UNAVAILABLE;
if (runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK;
return graphics.uhdk_gl_context_begin_frame(context);
}
fn release(a: *Application) abi.Status {
const context = a.session_context orelse return abi.OK;
if (!runtime.fromObjectHandle(context).payload.gl.bracket) return abi.OK;
return graphics.uhdk_gl_context_end_frame(context);
}
fn ready(a: *Application, resource: anytype, deadline: u64) abi.Status {
const object = runtime.fromObjectHandle(resource);
while (!object.ready) {
if (!object.alive) return if (object.creation_status == abi.OK) abi.UNAVAILABLE else object.creation_status;
if (a.native_error != abi.OK) return a.native_error;
if (a.event_error != abi.OK) return a.event_error;
const now = runtime.now(a.io);
if (now >= deadline) return abi.UNAVAILABLE;
runtime.dispatch(handle(a));
c.z_native_pump(@min(deadline - now, 10 * std.time.ns_per_ms));
}
return abi.OK;
}
pub export fn uhdk_open(options: [*c]const c.uhdk_options, out: [*c]?*c.uhdk_session) abi.Status {
if (out == null) return abi.INVALID;
out.* = null;
if (c.z_native_is_main_thread() == 0) return c.UHDK_STATUS_WRONG_THREAD;
var opts = std.mem.zeroes(c.uhdk_options);
if (options != null) {
if (!abi.validDescriptor(c.uhdk_options, options)) return abi.INVALID;
opts = options.*;
}
if (opts.render_mode > c.UHDK_RENDER_ON_DEMAND or
(opts.undecorated != 0 and opts.undecorated != 1) or
(opts.fixed_size != 0 and opts.fixed_size != 1) or
(opts.disable_vsync != 0 and opts.disable_vsync != 1) or
(opts.request_focus != 0 and opts.request_focus != 1)) return abi.INVALID;
var desc = std.mem.zeroes(c.uhdk_app_desc);
desc.struct_size = @sizeOf(c.uhdk_app_desc);
desc.abi_version = c.UHDK_ABI_VERSION;
desc.application_id = opts.application_id;
desc.display_name = if (opts.title.len == 0) abi.textSpan("UHDK") else opts.title;
desc.preferred_backend = opts.preferred_backend;
var application: ?*c.uhdk_app = null;
var status = app.uhdk_app_create(&desc, &application);
if (status != abi.OK) return status;
const a = runtime.fromAppHandle(application);
var success = false;
defer if (!success) {
_ = release(a);
app.uhdk_app_destroy(application);
};
a.session_on_demand = opts.render_mode == c.UHDK_RENDER_ON_DEMAND;
var window = std.mem.zeroes(c.uhdk_window_desc);
window.struct_size = @sizeOf(c.uhdk_window_desc);
window.title = desc.display_name;
window.flags = c.UHDK_WINDOW_OPENGL;
window.style = .{ .struct_size = @sizeOf(c.uhdk_window_style), .decorated = 1 - opts.undecorated, .resizable = 1 - opts.fixed_size, .reserved = 0 };
window.content_size = opts.content_size;
if (window.content_size.width == 0) window.content_size.width = 800;
if (window.content_size.height == 0) window.content_size.height = 600;
window.min_size = opts.min_size;
window.max_size = opts.max_size;
const deadline = runtime.now(a.io) +| (if (opts.startup_timeout_ns == 0) 10 * std.time.ns_per_s else opts.startup_timeout_ns);
status = windows.uhdk_window_create(application, &window, &a.session_window);
if (status != abi.OK) return status;
status = ready(a, a.session_window, deadline);
if (status != abi.OK) return status;
status = graphics.uhdk_gl_context_create(a.session_window, &a.session_context);
if (status != abi.OK) return status;
status = ready(a, a.session_context, deadline);
if (status != abi.OK) return status;
status = windows.uhdk_window_set_visible(a.session_window, 1);
if (status != abi.OK) return status;
if (opts.request_focus != 0) {
status = windows.uhdk_window_request_focus(a.session_window);
if (status != abi.OK) return status;
}
runtime.dispatch(application);
c.z_native_pump(0);
if (a.native_error != abi.OK) return a.native_error;
status = acquire(a);
if (status != abi.OK) return status;
status = graphics.uhdk_gl_context_set_swap_interval(a.session_context, 1 - @as(i32, opts.disable_vsync));
if (status != abi.OK and status != c.UHDK_STATUS_UNSUPPORTED) return status;
if (c.z_gl_load(a.session_context, &a.session_gl) == 0) return c.UHDK_STATUS_UNSUPPORTED;
out.* = @ptrCast(a);
success = true;
return abi.OK;
}
pub export fn uhdk_next_frame(session: ?*c.uhdk_session, out: [*c]c.uhdk_frame) c.uhdk_bool {
const a = state(session orelse return 0);
if (runtime.checkThread(a) != abi.OK) return 0;
if (out == null or a.session_active) {
a.session_status = if (out == null) abi.INVALID else c.UHDK_STATUS_BUSY;
return 0;
}
out.* = std.mem.zeroes(c.uhdk_frame);
if (a.session_status != abi.OK or a.stopped_seen) return 0;
var metrics = std.mem.zeroes(c.uhdk_window_metrics);
metrics.struct_size = @sizeOf(c.uhdk_window_metrics);
_ = windows.uhdk_window_get_metrics(a.session_window, &metrics);
const wait = !a.session_first and (a.session_on_demand or !drawable(metrics));
a.session_status = release(a);
if (a.session_status != abi.OK) return 0;
const poll_status = app.uhdk_app_poll_events(handle(a), if (wait) c.UHDK_WAIT_FOREVER else 0, &out.*.events);
// Restore GL ownership even after polling fails so cleanup can delete resources.
const acquire_status = acquire(a);
a.session_status = if (poll_status != abi.OK) poll_status else acquire_status;
if (a.session_status != abi.OK) return 0;
a.session_status = windows.uhdk_window_get_metrics(a.session_window, &metrics);
if (a.session_status != abi.OK) return 0;
out.*.gl = &a.session_gl;
out.*.metrics = metrics;
a.session_drawable = !a.stopping and drawable(metrics);
out.*.drawable = @intFromBool(a.session_drawable);
a.session_first = false;
a.session_active = true;
return 1;
}
fn drawable(metrics: c.uhdk_window_metrics) bool {
const minimized = if (metrics.observations & c.UHDK_WINDOW_OBSERVE_MINIMIZED != 0)
metrics.minimized != 0
else
metrics.state == c.UHDK_WINDOW_MINIMIZED;
const suspended = metrics.observations & c.UHDK_WINDOW_OBSERVE_SUSPENDED != 0 and metrics.suspended != 0;
return metrics.visible != 0 and metrics.framebuffer_width != 0 and metrics.framebuffer_height != 0 and
!minimized and !suspended;
}
pub export fn uhdk_end_frame(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID);
if (runtime.checkThread(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
if (!a.session_active) return c.UHDK_STATUS_BUSY;
a.session_active = false;
var status: abi.Status = abi.OK;
if (a.session_drawable and !a.stopping) status = graphics.uhdk_gl_context_swap_buffers(a.session_context);
const end_status = release(a);
const begin_status = if (end_status == abi.OK) acquire(a) else end_status;
a.session_status = if (status != abi.OK) status else begin_status;
return a.session_status;
}
pub export fn uhdk_get_status(session: ?*c.uhdk_session) abi.Status {
const a = state(session orelse return abi.INVALID);
if (runtime.checkThread(a) != abi.OK) return c.UHDK_STATUS_WRONG_THREAD;
return a.session_status;
}
pub export fn uhdk_get_gl(session: ?*c.uhdk_session) [*c]const c.uhdk_gl_functions {
return &state(session orelse return null).session_gl;
}
pub export fn uhdk_get_app(session: ?*c.uhdk_session) ?*c.uhdk_app {
return handle(state(session orelse return null));
}
pub export fn uhdk_get_window(session: ?*c.uhdk_session) ?*c.uhdk_window {
return state(session orelse return null).session_window;
}
pub export fn uhdk_get_context(session: ?*c.uhdk_session) ?*c.uhdk_gl_context {
return state(session orelse return null).session_context;
}
pub export fn uhdk_close(session: ?*c.uhdk_session) void {
const a = state(session orelse return);
std.debug.assert(runtime.checkThread(a) == abi.OK);
_ = release(a);
app.uhdk_app_destroy(handle(a));
}

19
src/gl_loader.c Normal file
View File

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

View File

@ -133,7 +133,8 @@ static uint32_t physical(unsigned short k) {
[98] = 64, [99] = 60, [100] = 65, [101] = 66, [103] = 68, [105] = 104, [106] = 107, [98] = 64, [99] = 60, [100] = 65, [101] = 66, [103] = 68, [105] = 104, [106] = 107,
[107] = 105, [109] = 67, [111] = 69, [113] = 106, [114] = 73, [115] = 74, [116] = 75, [107] = 105, [109] = 67, [111] = 69, [113] = 106, [114] = 73, [115] = 74, [116] = 75,
[117] = 76, [118] = 61, [119] = 77, [120] = 59, [121] = 78, [122] = 58, [123] = 80, [117] = 76, [118] = 61, [119] = 77, [120] = 59, [121] = 78, [122] = 58, [123] = 80,
[124] = 79, [125] = 81, [126] = 82}; [124] = 79, [125] = 81, [126] = 82
};
return k < 128 ? map[k] : 0; return k < 128 ? map[k] : 0;
} }
static uhdk_key logical(NSEvent *e) { static uhdk_key logical(NSEvent *e) {
@ -705,8 +706,9 @@ static uhdk_key logical(NSEvent *e) {
NSUInteger n = 0; NSUInteger n = 0;
for (NSURL *url in urls) { for (NSURL *url in urls) {
const char *path = url.fileSystemRepresentation; const char *path = url.fileSystemRepresentation;
uhdk_file *f = z_file_from_url(host.app, (uhdk_bytes){(const uint8_t *)path, strlen(path)}, uhdk_file *f = z_file_from_url(
(__bridge void *)url); host.app, (uhdk_bytes){(const uint8_t *)path, strlen(path)}, (__bridge void *)url
);
if (f) if (f)
files[n++] = f; files[n++] = f;
} }
@ -1022,7 +1024,8 @@ static NSMenu *makeMenu(uhdk_menu *menu, ZWindow *window) {
.appearance = [appearance isEqualToString:NSAppearanceNameDarkAqua] ? UHDK_APPEARANCE_DARK .appearance = [appearance isEqualToString:NSAppearanceNameDarkAqua] ? UHDK_APPEARANCE_DARK
: UHDK_APPEARANCE_LIGHT, : UHDK_APPEARANCE_LIGHT,
.reduced_motion = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion, .reduced_motion = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion,
.high_contrast = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast}; .high_contrast = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast
};
z_preferences(self.app, &p); z_preferences(self.app, &p);
} }
- (void)observeValueForKeyPath:(NSString *)keyPath - (void)observeValueForKeyPath:(NSString *)keyPath
@ -1073,9 +1076,13 @@ uhdk_status z_native_file_init(uhdk_file *file, uhdk_bytes path, uhdk_text uri,
g.scoped = [g.url startAccessingSecurityScopedResource]; g.scoped = [g.url startAccessingSecurityScopedResource];
} }
void *owned = g ? (__bridge_retained void *)g : NULL; void *owned = g ? (__bridge_retained void *)g : NULL;
uhdk_status status = uhdk_status status = z_file_init(
z_file_init(file, (uhdk_bytes){(const uint8_t *)native, strlen(native)}, file,
utf8(url.absoluteString), utf8(url.lastPathComponent), owned); (uhdk_bytes){(const uint8_t *)native, strlen(native)},
utf8(url.absoluteString),
utf8(url.lastPathComponent),
owned
);
if (status != UHDK_STATUS_OK && owned) { if (status != UHDK_STATUS_OK && owned) {
id unused = CFBridgingRelease(owned); id unused = CFBridgingRelease(owned);
(void)unused; (void)unused;
@ -1108,8 +1115,14 @@ static NSURL *fileURL(uhdk_file *file) {
} }
} }
@end @end
static void watchEvents(ConstFSEventStreamRef stream, void *info, size_t count, void *paths, static void watchEvents(
const FSEventStreamEventFlags flags[], const FSEventStreamEventId ids[]) { ConstFSEventStreamRef stream,
void *info,
size_t count,
void *paths,
const FSEventStreamEventFlags flags[],
const FSEventStreamEventId ids[]
) {
(void)stream; (void)stream;
(void)ids; (void)ids;
ZWatch *watch = (__bridge ZWatch *)info; ZWatch *watch = (__bridge ZWatch *)info;
@ -1151,8 +1164,9 @@ static void watchEvents(ConstFSEventStreamRef stream, void *info, size_t count,
if (match && ![path isEqualToString:watch.path]) { if (match && ![path isEqualToString:watch.path]) {
const char *raw = path.fileSystemRepresentation; const char *raw = path.fileSystemRepresentation;
if (raw) if (raw)
child = z_file_from_url(host.app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)}, child = z_file_from_url(
NULL); host.app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)}, NULL
);
if (child) if (child)
e.data.watch.file = child; e.data.watch.file = child;
} }
@ -1257,15 +1271,17 @@ static uhdk_status showPanel(uhdk_app *app, const uhdk_file_dialog_desc *d, uint
NSUInteger n = 0; NSUInteger n = 0;
for (NSURL *url in urls) { for (NSURL *url in urls) {
const char *raw = url.fileSystemRepresentation; const char *raw = url.fileSystemRepresentation;
uhdk_file *f = z_file_from_url(app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)}, uhdk_file *f = z_file_from_url(
(__bridge void *)url); app, (uhdk_bytes){(const uint8_t *)raw, strlen(raw)}, (__bridge void *)url
);
if (f) if (f)
files[n++] = f; files[n++] = f;
} }
z_request_result result = {0}; z_request_result result = {0};
result.value.files = (uhdk_file_list){files, n}; result.value.files = (uhdk_file_list){files, n};
z_complete(app, request, n == urls.count ? UHDK_STATUS_OK : UHDK_STATUS_OUT_OF_MEMORY, z_complete(
&result); app, request, n == urls.count ? UHDK_STATUS_OK : UHDK_STATUS_OUT_OF_MEMORY, &result
);
for (NSUInteger i = 0; i < n; i++) for (NSUInteger i = 0; i < n; i++)
uhdk_file_release(files[i]); uhdk_file_release(files[i]);
}; };
@ -1461,8 +1477,12 @@ void z_native_pool_pop(void *p) {
int z_native_is_main_thread(void) { int z_native_is_main_thread(void) {
return NSThread.isMainThread; return NSThread.isMainThread;
} }
uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t request, uhdk_status z_native_execute(
z_request_result *result) { uhdk_app *app,
const z_command *cmd,
uint64_t request,
z_request_result *result
) {
@autoreleasepool { @autoreleasepool {
@try { @try {
ZWindow *w = cmd->target && z_object_kind(cmd->target) == Z_KIND_WINDOW ZWindow *w = cmd->target && z_object_kind(cmd->target) == Z_KIND_WINDOW
@ -1480,8 +1500,9 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
NSWindowStyleMaskMiniaturizable; NSWindowStyleMaskMiniaturizable;
if (w.style.resizable) if (w.style.resizable)
style |= NSWindowStyleMaskResizable; style |= NSWindowStyleMaskResizable;
NSRect rect = NSMakeRect(0, 0, cmd->window.content_size.width, NSRect rect = NSMakeRect(
cmd->window.content_size.height); 0, 0, cmd->window.content_size.width, cmd->window.content_size.height
);
w.window = [[NSWindow alloc] initWithContentRect:rect w.window = [[NSWindow alloc] initWithContentRect:rect
styleMask:style styleMask:style
backing:NSBackingStoreBuffered backing:NSBackingStoreBuffered
@ -1498,8 +1519,10 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
w.window.delegate = w; w.window.delegate = w;
w.window.contentMinSize = w.window.contentMinSize =
NSMakeSize(cmd->window.min_size.width, cmd->window.min_size.height); NSMakeSize(cmd->window.min_size.width, cmd->window.min_size.height);
w.window.contentMaxSize = NSMakeSize(cmd->window.max_size.width ?: CGFLOAT_MAX, w.window.contentMaxSize = NSMakeSize(
cmd->window.max_size.height ?: CGFLOAT_MAX); cmd->window.max_size.width ?: CGFLOAT_MAX,
cmd->window.max_size.height ?: CGFLOAT_MAX
);
if (cmd->window.parent) { if (cmd->window.parent) {
ZWindow *parent = (__bridge ZWindow *)z_object_native(cmd->window.parent); ZWindow *parent = (__bridge ZWindow *)z_object_native(cmd->window.parent);
[parent.window addChildWindow:w.window ordered:NSWindowAbove]; [parent.window addChildWindow:w.window ordered:NSWindowAbove];
@ -1532,8 +1555,9 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
break; break;
case Z_STYLE: { case Z_STYLE: {
NSWindowStyleMask mask = w.window.styleMask; NSWindowStyleMask mask = w.window.styleMask;
mask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | mask &=
NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable); ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable);
if (cmd->style.decorated) if (cmd->style.decorated)
mask |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | mask |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable; NSWindowStyleMaskMiniaturizable;
@ -1552,15 +1576,17 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
case Z_GL: { case Z_GL: {
if (!(w.flags & UHDK_WINDOW_OPENGL)) if (!(w.flags & UHDK_WINDOW_OPENGL))
return UHDK_STATUS_INVALID_ARGUMENT; return UHDK_STATUS_INVALID_ARGUMENT;
NSOpenGLPixelFormatAttribute attrs[] = {NSOpenGLPFAOpenGLProfile, NSOpenGLPixelFormatAttribute attrs[] = {
NSOpenGLProfileVersion4_1Core, NSOpenGLPFAOpenGLProfile,
NSOpenGLPFAColorSize, NSOpenGLProfileVersion4_1Core,
24, NSOpenGLPFAColorSize,
NSOpenGLPFAAlphaSize, 24,
8, NSOpenGLPFAAlphaSize,
NSOpenGLPFADoubleBuffer, 8,
NSOpenGLPFAAccelerated, NSOpenGLPFADoubleBuffer,
0}; NSOpenGLPFAAccelerated,
0
};
NSOpenGLPixelFormat *format = NSOpenGLPixelFormat *format =
[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs]; [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
if (!format) if (!format)
@ -1752,8 +1778,11 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
if (!rep) if (!rep)
return UHDK_STATUS_OUT_OF_MEMORY; return UHDK_STATUS_OUT_OF_MEMORY;
for (uint32_t y = 0; y < i->height; y++) for (uint32_t y = 0; y < i->height; y++)
memcpy(rep.bitmapData + (size_t)y * rep.bytesPerRow, memcpy(
i->pixels.ptr + y * i->stride_bytes, (size_t)i->width * 4); rep.bitmapData + (size_t)y * rep.bytesPerRow,
i->pixels.ptr + y * i->stride_bytes,
(size_t)i->width * 4
);
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(i->width, i->height)]; NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(i->width, i->height)];
[image addRepresentation:rep]; [image addRepresentation:rep];
NSApp.applicationIconImage = image; NSApp.applicationIconImage = image;

View File

@ -7,6 +7,7 @@
#include "uhdk.h" #include "uhdk.h"
#include <stddef.h> #include <stddef.h>
#include "edit_keys.h" #include "edit_keys.h"
int32_t z_gl_load(uhdk_gl_context *context, uhdk_gl_functions *functions);
/* Private producer storage. Converted to public pointer payloads at poll. */ /* Private producer storage. Converted to public pointer payloads at poll. */
typedef struct z_request_result { typedef struct z_request_result {
uhdk_request_id id; uhdk_request_id id;

View File

@ -4,6 +4,7 @@ const c = @import("native");
comptime { comptime {
checkExports(@import("api/app.zig")); checkExports(@import("api/app.zig"));
checkExports(@import("api/session.zig"));
checkExports(@import("api/windows.zig")); checkExports(@import("api/windows.zig"));
checkExports(@import("api/graphics.zig")); checkExports(@import("api/graphics.zig"));
checkExports(@import("api/input.zig")); checkExports(@import("api/input.zig"));

View File

@ -310,6 +310,10 @@ pub fn finish(
}; };
const redraw = command.completion == .resource and status == abi.OK and command.data.op == c.Z_GL; const redraw = command.completion == .resource and status == abi.OK and command.data.op == c.Z_GL;
const redraw_window = if (redraw) fromObjectHandle(command.data.other).payload.gl.owner else null; const redraw_window = if (redraw) fromObjectHandle(command.data.other).payload.gl.owner else null;
if (command.completion == .resource) {
const object = fromObjectHandle(if (command.data.op == c.Z_WINDOW) command.data.target else command.data.other);
object.creation_status = status;
}
if (status != abi.OK) discardCreation(command); if (status != abi.OK) discardCreation(command);
const node = command.node; const node = command.node;
const publish = switch (command.completion) { const publish = switch (command.completion) {

View File

@ -120,9 +120,10 @@ static uhdk_status osError(void) {
static WCHAR *wide(uhdk_text text) { static WCHAR *wide(uhdk_text text) {
if (text.len > INT_MAX) if (text.len > INT_MAX)
return NULL; return NULL;
int n = text.len ? MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.ptr, (int)text.len, int n =
NULL, 0) text.len
: 0; ? MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.ptr, (int)text.len, NULL, 0)
: 0;
if (text.len && !n) if (text.len && !n)
return NULL; return NULL;
WCHAR *s = profileCalloc((size_t)n + 1, sizeof(WCHAR)); WCHAR *s = profileCalloc((size_t)n + 1, sizeof(WCHAR));
@ -199,9 +200,15 @@ static void preferences(void) {
uhdk_preferences p = {0}; uhdk_preferences p = {0};
p.struct_size = sizeof(p); p.struct_size = sizeof(p);
DWORD light = 1, size = sizeof(light); DWORD light = 1, size = sizeof(light);
RegGetValueW(HKEY_CURRENT_USER, RegGetValueW(
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", HKEY_CURRENT_USER,
L"AppsUseLightTheme", RRF_RT_REG_DWORD, NULL, &light, &size); L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
L"AppsUseLightTheme",
RRF_RT_REG_DWORD,
NULL,
&light,
&size
);
p.appearance = light ? UHDK_APPEARANCE_LIGHT : UHDK_APPEARANCE_DARK; p.appearance = light ? UHDK_APPEARANCE_LIGHT : UHDK_APPEARANCE_DARK;
HIGHCONTRASTW contrast = {sizeof(contrast), 0, NULL}; HIGHCONTRASTW contrast = {sizeof(contrast), 0, NULL};
SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0); SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0);
@ -332,7 +339,8 @@ static uint32_t physicalKey(LPARAM param) {
[57] = 44, [58] = 57, [59] = 58, [60] = 59, [61] = 60, [62] = 61, [63] = 62, [64] = 63, [57] = 44, [58] = 57, [59] = 58, [60] = 59, [61] = 60, [62] = 61, [63] = 62, [64] = 63,
[65] = 64, [66] = 65, [67] = 66, [68] = 67, [69] = 83, [70] = 71, [71] = 95, [72] = 96, [65] = 64, [66] = 65, [67] = 66, [68] = 67, [69] = 83, [70] = 71, [71] = 95, [72] = 96,
[73] = 97, [74] = 86, [75] = 92, [76] = 93, [77] = 94, [78] = 87, [79] = 89, [80] = 90, [73] = 97, [74] = 86, [75] = 92, [76] = 93, [77] = 94, [78] = 87, [79] = 89, [80] = 90,
[81] = 91, [82] = 98, [83] = 99, [86] = 100, [87] = 68, [88] = 69}; [81] = 91, [82] = 98, [83] = 99, [86] = 100, [87] = 68, [88] = 69
};
unsigned scan = (unsigned)(param >> 16) & 127; unsigned scan = (unsigned)(param >> 16) & 127;
if (param & (1 << 24)) if (param & (1 << 24))
switch (scan) { switch (scan) {
@ -379,8 +387,10 @@ static void imePosition(Window *w) {
HIMC ime = ImmGetContext(w->hwnd); HIMC ime = ImmGetContext(w->hwnd);
if (!ime) if (!ime)
return; return;
POINT point = {(LONG)(w->text_state.caret.x * w->scale), POINT point = {
(LONG)((w->text_state.caret.y + w->text_state.caret.height) * w->scale)}; (LONG)(w->text_state.caret.x * w->scale),
(LONG)((w->text_state.caret.y + w->text_state.caret.height) * w->scale)
};
COMPOSITIONFORM composition = {0}; COMPOSITIONFORM composition = {0};
composition.dwStyle = CFS_POINT; composition.dwStyle = CFS_POINT;
composition.ptCurrentPos = point; composition.ptCurrentPos = point;
@ -517,8 +527,15 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
case WM_DPICHANGED: { case WM_DPICHANGED: {
RECT *r = (RECT *)lp; RECT *r = (RECT *)lp;
w->scale = (float)HIWORD(wp) / 96.0f; w->scale = (float)HIWORD(wp) / 96.0f;
SetWindowPos(hwnd, NULL, r->left, r->top, r->right - r->left, r->bottom - r->top, SetWindowPos(
SWP_NOZORDER | SWP_NOACTIVATE); hwnd,
NULL,
r->left,
r->top,
r->right - r->left,
r->bottom - r->top,
SWP_NOZORDER | SWP_NOACTIVATE
);
metrics(w); metrics(w);
imePosition(w); imePosition(w);
return 0; return 0;
@ -532,8 +549,13 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
uhdk_size sizes[] = {w->min_size, w->max_size}; uhdk_size sizes[] = {w->min_size, w->max_size};
for (unsigned i = 0; i < 2; ++i) { for (unsigned i = 0; i < 2; ++i) {
RECT r = {0, 0, (LONG)(sizes[i].width * scale), (LONG)(sizes[i].height * scale)}; RECT r = {0, 0, (LONG)(sizes[i].width * scale), (LONG)(sizes[i].height * scale)};
AdjustWindowRectExForDpi(&r, (DWORD)GetWindowLongPtrW(hwnd, GWL_STYLE), AdjustWindowRectExForDpi(
GetMenu(hwnd) != NULL, 0, dpi ? dpi : 96); &r,
(DWORD)GetWindowLongPtrW(hwnd, GWL_STYLE),
GetMenu(hwnd) != NULL,
0,
dpi ? dpi : 96
);
POINT *p = i ? &m->ptMaxTrackSize : &m->ptMinTrackSize; POINT *p = i ? &m->ptMaxTrackSize : &m->ptMinTrackSize;
if (sizes[i].width > 0) if (sizes[i].width > 0)
p->x = r.right - r.left; p->x = r.right - r.left;
@ -810,10 +832,14 @@ uhdk_status z_native_file_init(uhdk_file *file, uhdk_bytes path, uhdk_text uri,
if ((*p == L'\\' || *p == L'/') && p[1]) if ((*p == L'\\' || *p == L'/') && p[1])
leaf = p + 1; leaf = p + 1;
char *display = utf8(leaf, (int)wcslen(leaf), &display_len); char *display = utf8(leaf, (int)wcslen(leaf), &display_len);
uhdk_status status = uhdk_status status = display ? z_file_init(
display ? z_file_init(file, (uhdk_bytes){(uint8_t *)name, n * 2}, file,
(uhdk_text){url8, uri_len}, (uhdk_text){display, display_len}, NULL) (uhdk_bytes){(uint8_t *)name, n * 2},
: UHDK_STATUS_OS_ERROR; (uhdk_text){url8, uri_len},
(uhdk_text){display, display_len},
NULL
)
: UHDK_STATUS_OS_ERROR;
profileFree(display); profileFree(display);
profileFree(url8); profileFree(url8);
profileFree(url); profileFree(url);
@ -1059,12 +1085,14 @@ static void showDialog(void) {
IFileSaveDialog *save = NULL; IFileSaveDialog *save = NULL;
HRESULT hr; HRESULT hr;
if (d->kind == UHDK_DIALOG_SAVE_FILE) { if (d->kind == UHDK_DIALOG_SAVE_FILE) {
hr = CoCreateInstance(&CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, hr = CoCreateInstance(
&IID_IFileSaveDialog, (void **)&save); &CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, &IID_IFileSaveDialog, (void **)&save
);
dialog = (IFileDialog *)save; dialog = (IFileDialog *)save;
} else { } else {
hr = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, hr = CoCreateInstance(
&IID_IFileOpenDialog, (void **)&open); &CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, &IID_IFileOpenDialog, (void **)&open
);
dialog = (IFileDialog *)open; dialog = (IFileDialog *)open;
} }
if (FAILED(hr)) { if (FAILED(hr)) {
@ -1209,10 +1237,16 @@ static void showDialog(void) {
static BOOL armWatch(Watch *watch) { static BOOL armWatch(Watch *watch) {
ResetEvent(watch->overlapped.hEvent); ResetEvent(watch->overlapped.hEvent);
watch->pending = ReadDirectoryChangesW( watch->pending = ReadDirectoryChangesW(
watch->directory, watch->buffer, sizeof(watch->buffer), FALSE, watch->directory,
watch->buffer,
sizeof(watch->buffer),
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE |
FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_ATTRIBUTES,
NULL, &watch->overlapped, NULL); NULL,
&watch->overlapped,
NULL
);
return watch->pending; return watch->pending;
} }
uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **out) { uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **out) {
@ -1249,8 +1283,14 @@ uhdk_status z_native_watch_prepare(uhdk_file *root, uhdk_watch *handle, void **o
slash[1] = 0; slash[1] = 0;
} }
watch->directory = CreateFileW( watch->directory = CreateFileW(
path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, path,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
profileFree(path); profileFree(path);
watch->overlapped.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL); watch->overlapped.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
watch->handle = handle; watch->handle = handle;
@ -1309,10 +1349,11 @@ static void pollWatches(void) {
(FILE_NOTIFY_INFORMATION *)((uint8_t *)w->buffer + offset); (FILE_NOTIFY_INFORMATION *)((uint8_t *)w->buffer + offset);
if (info->FileNameLength > size - offset - offsetof(FILE_NOTIFY_INFORMATION, FileName)) if (info->FileNameLength > size - offset - offsetof(FILE_NOTIFY_INFORMATION, FileName))
break; break;
BOOL match = !w->leaf || BOOL match =
(wcslen(w->leaf) * 2 == info->FileNameLength && !w->leaf || (wcslen(w->leaf) * 2 == info->FileNameLength &&
CompareStringOrdinal(w->leaf, -1, info->FileName, CompareStringOrdinal(
(int)info->FileNameLength / 2, TRUE) == CSTR_EQUAL); w->leaf, -1, info->FileName, (int)info->FileNameLength / 2, TRUE
) == CSTR_EQUAL);
if (match) if (match)
switch (info->Action) { switch (info->Action) {
case FILE_ACTION_ADDED: case FILE_ACTION_ADDED:
@ -1378,8 +1419,9 @@ uhdk_status z_native_start(uhdk_app *app, uhdk_text name) {
z_native_finish(); z_native_finish();
return status; return status;
} }
host.dispatch = CreateWindowExW(0, window_class, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, host.dispatch = CreateWindowExW(
cls.hInstance, NULL); 0, window_class, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, cls.hInstance, NULL
);
if (!host.dispatch) { if (!host.dispatch) {
z_native_finish(); z_native_finish();
return osError(); return osError();
@ -1637,8 +1679,12 @@ static uhdk_status setIcon(const uhdk_image *image) {
host.icon = icon; host.icon = icon;
return UHDK_STATUS_OK; return UHDK_STATUS_OK;
} }
uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t request, uhdk_status z_native_execute(
z_request_result *result) { uhdk_app *app,
const z_command *cmd,
uint64_t request,
z_request_result *result
) {
(void)app; (void)app;
(void)result; (void)result;
Window *w = Window *w =
@ -1655,15 +1701,18 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
w->max_size = cmd->window.max_size; w->max_size = cmd->window.max_size;
w->scale = 1; w->scale = 1;
w->cursor = LoadCursorW(NULL, IDC_ARROW); w->cursor = LoadCursorW(NULL, IDC_ARROW);
DWORD style = cmd->window.style.decorated DWORD style =
? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX cmd->window.style.decorated ? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX : WS_POPUP;
: WS_POPUP;
if (cmd->window.style.resizable) if (cmd->window.style.resizable)
style |= WS_THICKFRAME | WS_MAXIMIZEBOX; style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
UINT dpi = GetDpiForSystem(); UINT dpi = GetDpiForSystem();
float scale = (float)dpi / 96; float scale = (float)dpi / 96;
RECT r = {0, 0, (LONG)(cmd->window.content_size.width * scale), RECT r = {
(LONG)(cmd->window.content_size.height * scale)}; 0,
0,
(LONG)(cmd->window.content_size.width * scale),
(LONG)(cmd->window.content_size.height * scale)
};
AdjustWindowRectExForDpi(&r, style, FALSE, 0, dpi); AdjustWindowRectExForDpi(&r, style, FALSE, 0, dpi);
WCHAR *title = wide(cmd->window.title); WCHAR *title = wide(cmd->window.title);
if (!title) { if (!title) {
@ -1671,9 +1720,20 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
return UHDK_STATUS_OUT_OF_MEMORY; return UHDK_STATUS_OUT_OF_MEMORY;
} }
HWND parent = cmd->window.parent ? windowOf(cmd->window.parent)->hwnd : NULL; HWND parent = cmd->window.parent ? windowOf(cmd->window.parent)->hwnd : NULL;
HWND hwnd = CreateWindowExW(0, window_class, title, style, CW_USEDEFAULT, CW_USEDEFAULT, HWND hwnd = CreateWindowExW(
r.right - r.left, r.bottom - r.top, parent, NULL, 0,
GetModuleHandleW(NULL), w); window_class,
title,
style,
CW_USEDEFAULT,
CW_USEDEFAULT,
r.right - r.left,
r.bottom - r.top,
parent,
NULL,
GetModuleHandleW(NULL),
w
);
profileFree(title); profileFree(title);
if (!hwnd) { if (!hwnd) {
profileFree(w); profileFree(w);
@ -1701,10 +1761,22 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
} }
case Z_SIZE: { case Z_SIZE: {
RECT r = {0, 0, (LONG)(cmd->size.width * w->scale), (LONG)(cmd->size.height * w->scale)}; RECT r = {0, 0, (LONG)(cmd->size.width * w->scale), (LONG)(cmd->size.height * w->scale)};
AdjustWindowRectExForDpi(&r, (DWORD)GetWindowLongPtrW(w->hwnd, GWL_STYLE), AdjustWindowRectExForDpi(
GetMenu(w->hwnd) != NULL, 0, GetDpiForWindow(w->hwnd)); &r,
if (!SetWindowPos(w->hwnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top, (DWORD)GetWindowLongPtrW(w->hwnd, GWL_STYLE),
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE)) GetMenu(w->hwnd) != NULL,
0,
GetDpiForWindow(w->hwnd)
);
if (!SetWindowPos(
w->hwnd,
NULL,
0,
0,
r.right - r.left,
r.bottom - r.top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
))
return osError(); return osError();
metrics(w); metrics(w);
break; break;
@ -1722,17 +1794,25 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
m.cbSize = sizeof(m); m.cbSize = sizeof(m);
GetMonitorInfoW(MonitorFromWindow(w->hwnd, MONITOR_DEFAULTTONEAREST), &m); GetMonitorInfoW(MonitorFromWindow(w->hwnd, MONITOR_DEFAULTTONEAREST), &m);
w->fullscreen = TRUE; w->fullscreen = TRUE;
SetWindowLongPtrW(w->hwnd, GWL_STYLE, SetWindowLongPtrW(
(w->saved_style & ~WS_OVERLAPPEDWINDOW) | WS_POPUP); w->hwnd, GWL_STYLE, (w->saved_style & ~WS_OVERLAPPEDWINDOW) | WS_POPUP
SetWindowPos(w->hwnd, HWND_TOP, m.rcMonitor.left, m.rcMonitor.top, );
m.rcMonitor.right - m.rcMonitor.left, m.rcMonitor.bottom - m.rcMonitor.top, SetWindowPos(
SWP_FRAMECHANGED); w->hwnd,
HWND_TOP,
m.rcMonitor.left,
m.rcMonitor.top,
m.rcMonitor.right - m.rcMonitor.left,
m.rcMonitor.bottom - m.rcMonitor.top,
SWP_FRAMECHANGED
);
} else if (!full && w->fullscreen) { } else if (!full && w->fullscreen) {
w->fullscreen = FALSE; w->fullscreen = FALSE;
SetWindowLongPtrW(w->hwnd, GWL_STYLE, w->saved_style); SetWindowLongPtrW(w->hwnd, GWL_STYLE, w->saved_style);
SetWindowPlacement(w->hwnd, &w->placement); SetWindowPlacement(w->hwnd, &w->placement);
SetWindowPos(w->hwnd, NULL, 0, 0, 0, 0, SetWindowPos(
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); w->hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED
);
} }
if (minimize) if (minimize)
ShowWindow(w->hwnd, SW_MINIMIZE); ShowWindow(w->hwnd, SW_MINIMIZE);
@ -1748,10 +1828,10 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
metrics(w); metrics(w);
break; break;
case Z_STYLE: { case Z_STYLE: {
DWORD style = (DWORD)(w->fullscreen ? w->saved_style DWORD style =
: GetWindowLongPtrW(w->hwnd, GWL_STYLE)); (DWORD)(w->fullscreen ? w->saved_style : GetWindowLongPtrW(w->hwnd, GWL_STYLE));
style &= ~(WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | style &=
WS_THICKFRAME | WS_POPUP); ~(WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_POPUP);
style |= cmd->style.decorated ? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX : WS_POPUP; style |= cmd->style.decorated ? WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX : WS_POPUP;
if (cmd->style.resizable) if (cmd->style.resizable)
style |= WS_THICKFRAME | WS_MAXIMIZEBOX; style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
@ -1767,12 +1847,19 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
if (!SetWindowLongPtrW(w->hwnd, GWL_STYLE, style) && GetLastError()) if (!SetWindowLongPtrW(w->hwnd, GWL_STYLE, style) && GetLastError())
return osError(); return osError();
RECT frame = {0, 0, client.right, client.bottom}; RECT frame = {0, 0, client.right, client.bottom};
if (!AdjustWindowRectExForDpi(&frame, style, GetMenu(w->hwnd) != NULL, 0, if (!AdjustWindowRectExForDpi(
GetDpiForWindow(w->hwnd))) &frame, style, GetMenu(w->hwnd) != NULL, 0, GetDpiForWindow(w->hwnd)
))
return osError(); return osError();
if (!SetWindowPos(w->hwnd, NULL, window.left, window.top, frame.right - frame.left, if (!SetWindowPos(
frame.bottom - frame.top, w->hwnd,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED)) NULL,
window.left,
window.top,
frame.right - frame.left,
frame.bottom - frame.top,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED
))
return osError(); return osError();
w->style = cmd->style; w->style = cmd->style;
metrics(w); metrics(w);
@ -1789,9 +1876,19 @@ uhdk_status z_native_execute(uhdk_app *app, const z_command *cmd, uint64_t reque
return status; return status;
} }
case Z_CURSOR: { case Z_CURSOR: {
LPCWSTR cursors[] = {IDC_ARROW, IDC_IBEAM, IDC_CROSS, IDC_HAND, LPCWSTR cursors[] = {
IDC_SIZEWE, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZENESW, IDC_ARROW,
IDC_SIZEALL, IDC_NO, IDC_WAIT}; IDC_IBEAM,
IDC_CROSS,
IDC_HAND,
IDC_SIZEWE,
IDC_SIZENS,
IDC_SIZENWSE,
IDC_SIZENESW,
IDC_SIZEALL,
IDC_NO,
IDC_WAIT
};
w->cursor = w->cursor =
cmd->number == UHDK_CURSOR_HIDDEN ? NULL : LoadCursorW(NULL, cursors[cmd->number]); cmd->number == UHDK_CURSOR_HIDDEN ? NULL : LoadCursorW(NULL, cursors[cmd->number]);
SetCursor(w->cursor); SetCursor(w->cursor);