|
| 1 | +const std = @import("std"); |
| 2 | +const zhttp = @import("zhttp"); |
| 3 | +const webui = @import("webui"); |
1 | 4 | const runner = @import("example_shared"); |
| 5 | +const time_compat = @import("time_compat"); |
| 6 | +const env_compat = @import("env_compat"); |
2 | 7 |
|
3 | 8 | pub const rpc_methods = runner.rpc_methods; |
4 | 9 |
|
5 | | -pub fn main() !void { |
6 | | - try runner.runExample(.custom_web_server, rpc_methods); |
| 10 | +fn onEventLog(_: ?*anyopaque, event: *const webui.Event) void { |
| 11 | + std.debug.print("[custom_web_server][event][window={d}] kind={s} name={s} payload={s}\n", .{ |
| 12 | + event.window_id, |
| 13 | + @tagName(event.kind), |
| 14 | + event.name, |
| 15 | + event.payload, |
| 16 | + }); |
| 17 | +} |
| 18 | + |
| 19 | +fn parseSurfaceToken(token: []const u8) ?webui.LaunchSurface { |
| 20 | + if (std.mem.eql(u8, token, "webview")) return .native_webview; |
| 21 | + if (std.mem.eql(u8, token, "browser")) return .browser_window; |
| 22 | + if (std.mem.eql(u8, token, "web-tab") or std.mem.eql(u8, token, "web-url")) return .web_url; |
| 23 | + return null; |
| 24 | +} |
| 25 | + |
| 26 | +fn parseRunModeSpec(mode: []const u8, run_mode_explicit: bool, darling_runtime: bool) webui.AppOptions { |
| 27 | + const effective_mode = if (darling_runtime and !run_mode_explicit) "web-tab" else mode; |
| 28 | + const single = parseSurfaceToken(effective_mode); |
| 29 | + |
| 30 | + const launch_policy: webui.LaunchPolicy = if (single) |surface| |
| 31 | + switch (surface) { |
| 32 | + .native_webview => .{ |
| 33 | + .first = .native_webview, |
| 34 | + .second = null, |
| 35 | + .third = null, |
| 36 | + .allow_dual_surface = false, |
| 37 | + .app_mode_required = true, |
| 38 | + }, |
| 39 | + .browser_window => .{ |
| 40 | + .first = .browser_window, |
| 41 | + .second = null, |
| 42 | + .third = null, |
| 43 | + .allow_dual_surface = false, |
| 44 | + .app_mode_required = true, |
| 45 | + }, |
| 46 | + .web_url => .{ |
| 47 | + .first = .web_url, |
| 48 | + .second = null, |
| 49 | + .third = null, |
| 50 | + .allow_dual_surface = false, |
| 51 | + .app_mode_required = false, |
| 52 | + }, |
| 53 | + } |
| 54 | + else |
| 55 | + webui.LaunchPolicy.webviewFirst(); |
| 56 | + |
| 57 | + return .{ |
| 58 | + .launch_policy = launch_policy, |
| 59 | + .linux_webview_target = if (std.mem.eql(u8, webui.BuildFlags.linux_webview_target, "webkitgtk-6")) |
| 60 | + .webkitgtk_6 |
| 61 | + else |
| 62 | + .webview, |
| 63 | + .window_fallback_emulation = true, |
| 64 | + }; |
| 65 | +} |
| 66 | + |
| 67 | +const IndexEndpoint = struct { |
| 68 | + pub const Info: zhttp.router.EndpointInfo = .{}; |
| 69 | + |
| 70 | + pub fn call(comptime rctx: zhttp.ReqCtx, req: rctx.T()) !zhttp.Res { |
| 71 | + _ = req; |
| 72 | + return .{ |
| 73 | + .status = .ok, |
| 74 | + .headers = &.{.{ .name = "content-type", .value = "text/html; charset=utf-8" }}, |
| 75 | + .body = "<!doctype html><html><head><meta charset=\"utf-8\"/>" ++ |
| 76 | + "<title>custom_web_server</title><script src=\"/webui/bridge.js\"></script>" ++ |
| 77 | + "<style>body{font-family:system-ui,sans-serif;margin:24px;background:#0f172a;color:#e2e8f0}" ++ |
| 78 | + "button{padding:10px 14px;border:0;background:#38bdf8;color:#082f49;font-weight:700;cursor:pointer}" ++ |
| 79 | + "pre{margin-top:16px;padding:12px;background:#111827;min-height:72px}</style></head>" ++ |
| 80 | + "<body><h1>custom_web_server</h1><p>WebUI mounted into a user-owned zhttp server.</p>" ++ |
| 81 | + "<button id=\"ping\">Ping</button><button id=\"sum\">Add 9 + 14</button><pre id=\"out\">ready</pre>" ++ |
| 82 | + "<script>const out=document.getElementById('out');" ++ |
| 83 | + "const rpc=()=>globalThis.webuiRpc??(typeof webuiRpc!=='undefined'?webuiRpc:undefined);" ++ |
| 84 | + "async function call(name,...args){const c=rpc();if(!c||typeof c[name]!=='function')throw new Error('RPC bridge unavailable');return await c[name](...args);}" ++ |
| 85 | + "document.getElementById('ping').addEventListener('click',async()=>{out.textContent=String(await call('ping'));});" ++ |
| 86 | + "document.getElementById('sum').addEventListener('click',async()=>{out.textContent=String(await call('add',9,14));});" ++ |
| 87 | + "</script></body></html>", |
| 88 | + }; |
| 89 | + } |
| 90 | +}; |
| 91 | + |
| 92 | +const IndexHtmlEndpoint = struct { |
| 93 | + pub const Info: zhttp.router.EndpointInfo = .{}; |
| 94 | + pub fn call(comptime rctx: zhttp.ReqCtx, req: rctx.T()) !zhttp.Res { |
| 95 | + return IndexEndpoint.call(rctx, req); |
| 96 | + } |
| 97 | +}; |
| 98 | + |
| 99 | +const Server = zhttp.Server(.{ |
| 100 | + .Context = webui.Service, |
| 101 | + .routes = .{ |
| 102 | + zhttp.get("/", IndexEndpoint), |
| 103 | + zhttp.get("/index.html", IndexHtmlEndpoint), |
| 104 | + zhttp.get("/webui/{*path}", webui.ZhttpGetEndpoint), |
| 105 | + zhttp.post("/webui/{*path}", webui.ZhttpPostEndpoint), |
| 106 | + }, |
| 107 | +}); |
| 108 | + |
| 109 | +fn runServer(args: Server.RunArgs) std.Io.Cancelable!void { |
| 110 | + Server.run(args) catch |err| switch (err) { |
| 111 | + error.Canceled => return error.Canceled, |
| 112 | + else => std.debug.panic("custom zhttp server failed: {s}", .{@errorName(err)}), |
| 113 | + }; |
| 114 | +} |
| 115 | + |
| 116 | +fn parseExitMsArg(arg: []const u8) ?u64 { |
| 117 | + const prefix = "--exit-ms="; |
| 118 | + if (!std.mem.startsWith(u8, arg, prefix)) return null; |
| 119 | + return std.fmt.parseInt(u64, arg[prefix.len..], 10) catch null; |
| 120 | +} |
| 121 | + |
| 122 | +test "parseExitMsArg accepts explicit exit override" { |
| 123 | + try std.testing.expectEqual(@as(?u64, 1800), parseExitMsArg("--exit-ms=1800")); |
| 124 | + try std.testing.expectEqual(@as(?u64, null), parseExitMsArg("--exit-ms=nope")); |
| 125 | + try std.testing.expectEqual(@as(?u64, null), parseExitMsArg("--other=1800")); |
| 126 | +} |
| 127 | + |
| 128 | +fn parseExitMs(init: std.process.Init) ?u64 { |
| 129 | + var args_iter = init.minimal.args.iterateAllocator(std.heap.page_allocator) catch return null; |
| 130 | + defer args_iter.deinit(); |
| 131 | + _ = args_iter.next(); |
| 132 | + while (args_iter.next()) |arg| { |
| 133 | + if (parseExitMsArg(arg)) |ms| return ms; |
| 134 | + } |
| 135 | + |
| 136 | + if (init.environ_map.get("WEBUI_EXAMPLE_EXIT_MS")) |raw| { |
| 137 | + return std.fmt.parseInt(u64, raw, 10) catch null; |
| 138 | + } |
| 139 | + |
| 140 | + const raw = env_compat.getEnvVarOwned(std.heap.page_allocator, "WEBUI_EXAMPLE_EXIT_MS") catch return null; |
| 141 | + defer std.heap.page_allocator.free(raw); |
| 142 | + return std.fmt.parseInt(u64, raw, 10) catch null; |
| 143 | +} |
| 144 | + |
| 145 | +pub fn main(init: std.process.Init) !void { |
| 146 | + var service = try webui.Service.init(init.gpa, rpc_methods, .{ |
| 147 | + .app = parseRunModeSpec( |
| 148 | + webui.BuildFlags.run_mode, |
| 149 | + webui.BuildFlags.run_mode_explicit, |
| 150 | + webui.isDarlingRuntime(), |
| 151 | + ), |
| 152 | + .window = .{ |
| 153 | + .title = "custom_web_server", |
| 154 | + }, |
| 155 | + .rpc = .{ |
| 156 | + .dispatcher_mode = .threaded, |
| 157 | + .threaded_poll_interval_ns = 500 * std.time.ns_per_us, |
| 158 | + }, |
| 159 | + .process_signals = true, |
| 160 | + }); |
| 161 | + defer service.deinit(); |
| 162 | + service.onEvent(onEventLog, null); |
| 163 | + |
| 164 | + var actual_port: u16 = 0; |
| 165 | + var group: std.Io.Group = .init; |
| 166 | + var group_done = false; |
| 167 | + defer if (!group_done) { |
| 168 | + group.cancel(init.io); |
| 169 | + group.await(init.io) catch {}; |
| 170 | + }; |
| 171 | + |
| 172 | + const addr0: std.Io.net.IpAddress = .{ .ip4 = std.Io.net.Ip4Address.loopback(0) }; |
| 173 | + try group.concurrent(init.io, runServer, .{.{ |
| 174 | + .gpa = init.gpa, |
| 175 | + .io = init.io, |
| 176 | + .address = addr0, |
| 177 | + .ctx = &service, |
| 178 | + .actual_port_out = &actual_port, |
| 179 | + }}); |
| 180 | + |
| 181 | + while (actual_port == 0) { |
| 182 | + try std.Io.sleep(init.io, std.Io.Duration.fromMilliseconds(1), .awake); |
| 183 | + } |
| 184 | + |
| 185 | + const url = try std.fmt.allocPrint(init.gpa, "http://127.0.0.1:{d}/", .{actual_port}); |
| 186 | + defer init.gpa.free(url); |
| 187 | + |
| 188 | + try service.showUrl(url); |
| 189 | + try service.run(); |
| 190 | + |
| 191 | + std.debug.print("[custom_web_server] serving {s}\n", .{url}); |
| 192 | + const exit_ms = parseExitMs(init); |
| 193 | + if (exit_ms) |ms| { |
| 194 | + time_compat.sleep(ms * std.time.ns_per_ms); |
| 195 | + service.shutdown(); |
| 196 | + group.cancel(init.io); |
| 197 | + std.process.exit(0); |
| 198 | + } |
| 199 | + const deadline_ms = if (exit_ms) |ms| |
| 200 | + time_compat.milliTimestamp() + @as(i64, @intCast(ms)) |
| 201 | + else |
| 202 | + std.math.maxInt(i64); |
| 203 | + while (!service.shouldExit()) { |
| 204 | + if (time_compat.milliTimestamp() >= deadline_ms) break; |
| 205 | + time_compat.sleep(20 * std.time.ns_per_ms); |
| 206 | + } |
| 207 | + |
| 208 | + service.shutdown(); |
| 209 | + group.cancel(init.io); |
| 210 | + group.await(init.io) catch {}; |
| 211 | + group_done = true; |
7 | 212 | } |
0 commit comments