Окна открываются и закрываются

This commit is contained in:
2025-12-06 21:04:58 +03:00
parent 74ead297d5
commit 68a4647e3f

View File

@@ -3,63 +3,213 @@ const builtin = @import("builtin");
const dvui = @import("dvui");
const SDLBackend = @import("sdl-backend");
const WindowContext = struct {
backend: SDLBackend,
window: dvui.Window,
title: [:0]u8,
id: usize,
fn deinit(self: *WindowContext, allocator: std.mem.Allocator, last_backend: bool) void {
self.window.deinit();
if (last_backend) {
self.backend.deinit();
} else {
destroyBackendKeepingSDL(&self.backend);
}
allocator.free(self.title);
self.* = undefined;
}
};
pub fn main() !void {
if (@import("builtin").os.tag == .windows) {
// on windows graphical apps have no console, so output goes to nowhere - attach it manually. related: https://github.com/ziglang/zig/issues/4196
dvui.Backend.Common.windowsAttachConsole() catch {};
}
SDLBackend.enableSDLLogging();
std.log.info("SDL version: {f}", .{SDLBackend.getSDLVersion()});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var backend = try SDLBackend.initWindow(.{
.allocator = allocator,
.size = .{ .w = 800.0, .h = 600.0 },
.title = "My DVUI App",
.vsync = true,
});
defer backend.deinit();
var windows = try std.ArrayList(*WindowContext).initCapacity(allocator, 0);
defer {
for (windows.items, 0..) |ctx, i| {
const last = i + 1 == windows.items.len;
ctx.deinit(allocator, last);
allocator.destroy(ctx);
}
windows.deinit(allocator);
}
var win = try dvui.Window.init(@src(), allocator, backend.backend(), .{
.theme = switch (backend.preferredColorScheme() orelse .light) {
.light => dvui.Theme.builtin.adwaita_light,
.dark => dvui.Theme.builtin.adwaita_dark,
},
});
defer win.deinit();
var next_window_id: usize = 1;
const first_ctx = try createWindow(allocator, next_window_id);
next_window_id += 1;
try windows.append(allocator, first_ctx);
var interrupted = false;
main_loop: while (true) {
if (windows.items.len == 0) break :main_loop;
const saw_events = try pumpEvents(&windows);
var min_wait_event_micros: u32 = std.math.maxInt(u32);
var idx: usize = 0;
while (idx < windows.items.len) {
const ctx = windows.items[idx];
// beginWait coordinates with waitTime below to run frames only when needed
const nstime = win.beginWait(interrupted);
const nstime = ctx.window.beginWait(interrupted);
// marks the beginning of a frame for dvui, can call dvui functions after this
try win.begin(nstime);
// send all SDL events to dvui for processing
try backend.addAllEvents(&win);
try ctx.window.begin(nstime);
// if dvui widgets might not cover the whole window, then need to clear
// the previous frame's render
_ = SDLBackend.c.SDL_SetRenderDrawColor(backend.renderer, 0, 0, 0, 255);
_ = SDLBackend.c.SDL_RenderClear(backend.renderer);
_ = SDLBackend.c.SDL_SetRenderDrawColor(ctx.backend.renderer, 0, 0, 0, 255);
_ = SDLBackend.c.SDL_RenderClear(ctx.backend.renderer);
const keep_running = gui_frame();
if (!keep_running) break :main_loop;
const keep_open = try gui_frame(ctx, allocator, &windows, &next_window_id);
if (!keep_open) {
closeWindow(&windows, allocator, idx);
continue;
}
// marks end of dvui frame, don't call dvui functions after this
// - sends all dvui stuff to backend for rendering, must be called before renderPresent()
const end_micros = try win.end(.{});
const end_micros = try ctx.window.end(.{});
// cursor management
try backend.setCursor(win.cursorRequested());
try backend.textInputRect(win.textInputRequested());
try ctx.backend.setCursor(ctx.window.cursorRequested());
try ctx.backend.textInputRect(ctx.window.textInputRequested());
// render frame to OS
try backend.renderPresent();
try ctx.backend.renderPresent();
// waitTime and beginWait combine to achieve variable framerates
const wait_event_micros = win.waitTime(end_micros);
interrupted = try backend.waitEventTimeout(wait_event_micros);
const wait_event_micros = ctx.window.waitTime(end_micros);
min_wait_event_micros = @min(min_wait_event_micros, wait_event_micros);
idx += 1;
}
if (windows.items.len == 0) break :main_loop;
interrupted = saw_events or try windows.items[0].backend.waitEventTimeout(min_wait_event_micros);
}
}
fn gui_frame() bool {
fn createWindow(allocator: std.mem.Allocator, id: usize) !*WindowContext {
var ctx = try allocator.create(WindowContext);
errdefer allocator.destroy(ctx);
ctx.id = id;
const title_bytes = try std.fmt.allocPrint(allocator, "My DVUI App #{d}", .{id});
defer allocator.free(title_bytes);
ctx.title = try allocator.allocSentinel(u8, title_bytes.len, 0);
@memcpy(ctx.title[0..title_bytes.len], title_bytes);
ctx.backend = try SDLBackend.initWindow(.{
.allocator = allocator,
.size = .{ .w = 800.0, .h = 600.0 },
.title = ctx.title,
.vsync = true,
});
errdefer destroyBackendKeepingSDL(&ctx.backend);
const theme = switch (ctx.backend.preferredColorScheme() orelse .light) {
.light => dvui.Theme.builtin.adwaita_light,
.dark => dvui.Theme.builtin.adwaita_dark,
};
ctx.window = try dvui.Window.init(@src(), allocator, ctx.backend.backend(), .{ .theme = theme });
errdefer ctx.window.deinit();
return ctx;
}
fn closeWindow(windows: *std.ArrayList(*WindowContext), allocator: std.mem.Allocator, idx: usize) void {
const last = windows.items.len == 1;
const ctx = windows.swapRemove(idx);
ctx.deinit(allocator, last);
allocator.destroy(ctx);
}
fn destroyBackendKeepingSDL(backend: *SDLBackend) void {
SDLBackend.c.SDL_DestroyRenderer(backend.renderer);
SDLBackend.c.SDL_DestroyWindow(backend.window);
backend.we_own_window = false;
backend.deinit();
}
fn windowId(ctx: *WindowContext) u32 {
return @intCast(SDLBackend.c.SDL_GetWindowID(ctx.backend.window));
}
fn eventWindowId(event: SDLBackend.c.SDL_Event) ?u32 {
return switch (event.type) {
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_KEY_DOWN else SDLBackend.c.SDL_KEYDOWN => @intCast(event.key.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_KEY_UP else SDLBackend.c.SDL_KEYUP => @intCast(event.key.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_TEXT_INPUT else SDLBackend.c.SDL_TEXTINPUT => @intCast(event.text.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_TEXT_EDITING else SDLBackend.c.SDL_TEXTEDITING => @intCast(event.edit.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_MOTION else SDLBackend.c.SDL_MOUSEMOTION => @intCast(event.motion.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_BUTTON_DOWN else SDLBackend.c.SDL_MOUSEBUTTONDOWN => @intCast(event.button.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_BUTTON_UP else SDLBackend.c.SDL_MOUSEBUTTONUP => @intCast(event.button.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_WHEEL else SDLBackend.c.SDL_MOUSEWHEEL => @intCast(event.wheel.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_WINDOW_CLOSE_REQUESTED else SDLBackend.c.SDL_WINDOWEVENT => @intCast(event.window.windowID),
else => null,
};
}
fn pumpEvents(windows: *std.ArrayList(*WindowContext)) !bool {
var event: SDLBackend.c.SDL_Event = undefined;
const poll_got_event = if (SDLBackend.sdl3) true else 1;
var saw_event = false;
while (SDLBackend.c.SDL_PollEvent(&event) == poll_got_event) {
saw_event = true;
if (eventWindowId(event)) |wid| {
for (windows.items) |ctx| {
if (windowId(ctx) == wid) {
_ = try ctx.backend.addEvent(&ctx.window, event);
break;
}
}
} else {
// broadcast events without a window target (like SDL_QUIT)
for (windows.items) |ctx| {
_ = try ctx.backend.addEvent(&ctx.window, event);
}
}
}
return saw_event;
}
fn gui_frame(ctx: *WindowContext, allocator: std.mem.Allocator, windows: *std.ArrayList(*WindowContext), next_window_id: *usize) !bool {
for (ctx.window.events.items) |*e| {
if (e.evt == .window and e.evt.window.action == .close) return false;
// Treat SDL_QUIT as a global request; ignore here so other windows keep running.
}
var root = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .both, .padding = dvui.Rect.all(12), .background = true, .style = .window });
defer root.deinit();
dvui.label(@src(), "Window #{d}", .{ctx.id}, .{ .font_style = .title_2 });
dvui.label(@src(), "Open windows: {d}", .{windows.items.len}, .{});
if (dvui.button(@src(), "New window", .{}, .{})) {
const id = next_window_id.*;
next_window_id.* += 1;
const new_ctx = try createWindow(allocator, id);
try windows.append(allocator, new_ctx);
}
return true;
}