Вкладки документов

This commit is contained in:
2026-02-22 22:01:41 +03:00
parent 48824532f1
commit bee9513ba0
2 changed files with 257 additions and 156 deletions

View File

@@ -1,36 +1,99 @@
const std = @import("std"); const std = @import("std");
const Canvas = @import("Canvas.zig"); const Canvas = @import("Canvas.zig");
const CpuRenderEngine = @import("render/CpuRenderEngine.zig"); const CpuRenderEngine = @import("render/CpuRenderEngine.zig");
const RenderEngine = @import("render/RenderEngine.zig").RenderEngine;
const Document = @import("models/Document.zig"); const Document = @import("models/Document.zig");
const basic_models = @import("models/basic_models.zig");
const WindowContext = @This(); const WindowContext = @This();
/// Один открытый документ: документ + свой холст и движок рендера
pub const OpenDocument = struct {
document: Document,
cpu_render: CpuRenderEngine,
canvas: Canvas,
/// Инициализировать по месту (canvas хранит указатель на cpu_render этого же экземпляра).
pub fn init(allocator: std.mem.Allocator, self: *OpenDocument) void {
const default_size = basic_models.Size{ .width = 800, .height = 600 };
self.document = Document.init(allocator, default_size);
self.cpu_render = CpuRenderEngine.init(allocator, .Squares);
self.canvas = Canvas.init(allocator, (&self.cpu_render).renderEngine());
}
pub fn deinit(self: *OpenDocument) void {
self.document.deinit();
self.canvas.deinit();
}
};
allocator: std.mem.Allocator, allocator: std.mem.Allocator,
canvas: Canvas,
cpu_render: *CpuRenderEngine,
frame_index: u64, frame_index: u64,
/// Открытые документы в текущем окне /// Список открытых документов (вкладок): указатели на документ+холст
documents: std.ArrayList(Document), documents: std.ArrayList(*OpenDocument),
/// Индекс активной вкладки; null — ни один документ не выбран
active_document_index: ?usize,
pub fn init(allocator: std.mem.Allocator) !WindowContext { pub fn init(allocator: std.mem.Allocator) !WindowContext {
var self: WindowContext = undefined; const frame_index: u64 = 0;
self.allocator = allocator; const documents = std.ArrayList(*OpenDocument).empty;
const active_document_index: ?usize = null;
self.cpu_render = try allocator.create(CpuRenderEngine); return .{
errdefer allocator.destroy(self.cpu_render); .allocator = allocator,
self.cpu_render.* = CpuRenderEngine.init(allocator, .Squares); .frame_index = frame_index,
.documents = documents,
self.canvas = Canvas.init(allocator, self.cpu_render.renderEngine()); .active_document_index = active_document_index,
};
self.frame_index = 0;
self.documents = std.ArrayList(Document).empty;
return self;
} }
pub fn deinit(self: *WindowContext) void { pub fn deinit(self: *WindowContext) void {
for (self.documents.items) |*doc| doc.deinit(); for (self.documents.items) |ptr| {
ptr.deinit();
self.allocator.destroy(ptr);
}
self.documents.deinit(self.allocator); self.documents.deinit(self.allocator);
self.canvas.deinit(); }
self.allocator.destroy(self.cpu_render);
/// Вернуть указатель на активный открытый документ (null если нет выбранной вкладки).
pub fn activeDocument(self: *WindowContext) ?*OpenDocument {
const i = self.active_document_index orelse return null;
if (i >= self.documents.items.len) return null;
return self.documents.items[i];
}
/// Добавить новый документ и сделать его активным.
pub fn addNewDocument(self: *WindowContext) !void {
const ptr = try self.allocator.create(OpenDocument);
errdefer self.allocator.destroy(ptr);
OpenDocument.init(self.allocator, ptr);
try self.documents.append(self.allocator, ptr);
self.active_document_index = self.documents.items.len - 1;
}
/// Выбрать вкладку по индексу.
pub fn setActiveDocument(self: *WindowContext, index: usize) void {
if (index < self.documents.items.len) {
self.active_document_index = index;
}
}
/// Закрыть вкладку по индексу; активная вкладка сдвигается при необходимости.
pub fn closeDocument(self: *WindowContext, index: usize) void {
if (index >= self.documents.items.len) return;
const open_doc = self.documents.items[index];
open_doc.deinit();
self.allocator.destroy(open_doc);
_ = self.documents.orderedRemove(index);
if (self.active_document_index) |*active| {
if (index < active.*) {
active.* -= 1;
} else if (index == active.*) {
if (self.documents.items.len > 0) {
active.* = @min(index, self.documents.items.len - 1);
} else {
self.active_document_index = null;
}
}
}
} }

View File

@@ -3,7 +3,6 @@ const builtin = @import("builtin");
const dvui = @import("dvui"); const dvui = @import("dvui");
const dvui_ext = @import("ui/dvui_ext.zig"); const dvui_ext = @import("ui/dvui_ext.zig");
const SDLBackend = @import("sdl-backend"); const SDLBackend = @import("sdl-backend");
const Document = @import("models/Document.zig");
const ImageRect = @import("models/basic_models.zig").ImageRect; const ImageRect = @import("models/basic_models.zig").ImageRect;
const WindowContext = @import("WindowContext.zig"); const WindowContext = @import("WindowContext.zig");
const sdl_c = SDLBackend.c; const sdl_c = SDLBackend.c;
@@ -70,8 +69,8 @@ pub fn main() !void {
} }
fn gui_frame(ctx: *WindowContext) bool { fn gui_frame(ctx: *WindowContext) bool {
const canvas = &ctx.canvas;
const ctrl: bool = dvui.currentWindow().modifiers.control(); const ctrl: bool = dvui.currentWindow().modifiers.control();
const active_doc = ctx.activeDocument();
for (dvui.events()) |*e| { for (dvui.events()) |*e| {
if (e.evt == .window and e.evt.window.action == .close) return false; if (e.evt == .window and e.evt.window.action == .close) return false;
@@ -80,172 +79,211 @@ fn gui_frame(ctx: *WindowContext) bool {
const root = dvui.box( const root = dvui.box(
@src(), @src(),
.{ .dir = .horizontal }, .{ .dir = .vertical },
.{ .expand = .both, .background = true, .style = .window }, .{ .expand = .both, .background = true, .style = .window },
); );
defer root.deinit(); defer root.deinit();
// Левая панель с фиксированной шириной // Верхняя строка: таббар (вкладки документов + кнопка "Новый")
var left_panel = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .vertical, .min_size_content = .{ .w = 200 }, .background = true }); var tab_bar = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal, .min_size_content = .{ .h = 32 }, .background = true, .padding = dvui.Rect.all(4) });
{ {
dvui.label(@src(), "Tools", .{}, .{}); for (ctx.documents.items, 0..) |open_doc, i| {
if (dvui.button(@src(), "Fill Random Color", .{}, .{}) or ctx.frame_index == 0) { _ = open_doc;
canvas.exampleReset() catch |err| { var buf: [32]u8 = undefined;
std.debug.print("Error reset example: {}\n", .{err}); const label = std.fmt.bufPrint(&buf, "Doc {d}", .{i + 1}) catch "Doc";
}; if (dvui.button(@src(), label, .{}, .{ .id_extra = i })) {
canvas.pos = .{ .x = 400, .y = 400 }; ctx.setActiveDocument(i);
}
if (dvui.checkbox(@src(), &canvas.native_scaling, "Scaling", .{})) {}
if (dvui.button(@src(), if (ctx.cpu_render.type == .Gradient) "Gradient" else "Squares", .{}, .{})) {
if (ctx.cpu_render.type == .Gradient) {
ctx.cpu_render.type = .Squares;
} else {
ctx.cpu_render.type = .Gradient;
} }
canvas.redrawExample() catch {}; }
if (dvui.button(@src(), "+", .{}, .{})) {
ctx.addNewDocument() catch |err| {
std.debug.print("addNewDocument error: {}\n", .{err});
};
} }
} }
left_panel.deinit(); tab_bar.deinit();
// Правая панель - занимает оставшееся пространство // Нижняя строка: левая панель + контент
const back = dvui.box( var content_row = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .both }); // no background to not override
@src(),
.{ .dir = .horizontal },
.{ .expand = .both, .padding = dvui.Rect.all(12), .background = true },
);
{ {
const fill_color = Color.black.opacity(0.25); // Левая панель с фиксированной шириной (инструменты для активного документа)
var right_panel = dvui.box( var left_panel = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .vertical, .min_size_content = .{ .w = 200 }, .background = true });
{
dvui.label(@src(), "Tools", .{}, .{});
if (active_doc) |doc| {
const canvas = &doc.canvas;
if (dvui.button(@src(), "Fill Random Color", .{}, .{}) or ctx.frame_index == 0) {
canvas.exampleReset() catch |err| {
std.debug.print("Error reset example: {}\n", .{err});
};
canvas.pos = .{ .x = 400, .y = 400 };
}
if (dvui.checkbox(@src(), &canvas.native_scaling, "Scaling", .{})) {}
if (dvui.button(@src(), if (doc.cpu_render.type == .Gradient) "Gradient" else "Squares", .{}, .{})) {
if (doc.cpu_render.type == .Gradient) {
doc.cpu_render.type = .Squares;
} else {
doc.cpu_render.type = .Gradient;
}
canvas.redrawExample() catch {};
}
} else {
dvui.label(@src(), "No document", .{}, .{});
}
}
left_panel.deinit();
// Правая панель — контент выбранного документа или заглушка
const back = dvui.box(
@src(), @src(),
.{ .dir = .vertical }, .{ .dir = .horizontal },
.{ .{ .expand = .both, .padding = dvui.Rect.all(12), .background = true },
.expand = .both,
.background = true,
.padding = dvui.Rect.all(5),
.corner_radius = dvui.Rect.all(24),
.color_fill = fill_color,
},
); );
{ {
var textured = dvui_ext.texturedBox(right_panel.data().contentRectScale(), dvui.Rect.all(20)); const fill_color = Color.black.opacity(0.25);
var right_panel = dvui.box(
@src(),
.{ .dir = .vertical },
.{
.expand = .both,
.background = true,
.padding = dvui.Rect.all(5),
.corner_radius = dvui.Rect.all(24),
.color_fill = fill_color,
},
);
{ {
var overlay = dvui.overlay( if (active_doc) |doc| {
@src(), const canvas = &doc.canvas;
.{ .expand = .both }, var textured = dvui_ext.texturedBox(right_panel.data().contentRectScale(), dvui.Rect.all(20));
);
{
var scroll = dvui.scrollArea(
@src(),
.{
.scroll_info = &canvas.scroll,
.vertical_bar = .auto,
.horizontal_bar = .auto,
},
.{
.expand = .both,
.background = false,
},
);
{ {
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale(); var overlay = dvui.overlay(
const img_size = canvas.getScaledImageSize();
// Получить viewport и scroll offset
const viewport_rect = scroll.data().contentRect();
const scroll_current = dvui.Point{ .x = canvas.scroll.viewport.x, .y = canvas.scroll.viewport.y };
// viewport_rect/scroll_current — в natural единицах.
// Для расчёта видимой области в пикселях изображения переводим в physical.
const viewport_px = dvui.Rect{
.x = viewport_rect.x * natural_scale,
.y = viewport_rect.y * natural_scale,
.w = viewport_rect.w * natural_scale,
.h = viewport_rect.h * natural_scale,
};
const scroll_px = dvui.Point{
.x = scroll_current.x * natural_scale,
.y = scroll_current.y * natural_scale,
};
canvas.updateVisibleImageRect(viewport_px, scroll_px) catch |err| {
std.debug.print("updateVisibleImageRect error: {}\n", .{err});
};
// `canvas.texture` contains ONLY the visible part.
// If we render it inside a widget sized as the full image, dvui will stretch it.
// Instead: create a scroll content surface sized like the full image, then place
// the visible texture at the correct offset at 1:1.
const content_w_px: u32 = img_size.x + img_size.w;
const content_h_px: u32 = img_size.y + img_size.h;
const content_w = @as(f32, @floatFromInt(content_w_px)) / natural_scale;
const content_h = @as(f32, @floatFromInt(content_h_px)) / natural_scale;
var canvas_layer = dvui.overlay(
@src(), @src(),
.{ .min_size_content = .{ .w = content_w, .h = content_h }, .background = false }, .{ .expand = .both },
); );
{ {
if (canvas.texture) |tex| { var scroll = dvui.scrollArea(
const vis = canvas._visible_rect orelse ImageRect{ .x = 0, .y = 0, .w = 0, .h = 0 }; @src(),
const left = @as(f32, @floatFromInt(img_size.x + vis.x)) / natural_scale; .{
const top = @as(f32, @floatFromInt(img_size.y + vis.y)) / natural_scale; .scroll_info = &canvas.scroll,
.vertical_bar = .auto,
.horizontal_bar = .auto,
},
.{
.expand = .both,
.background = false,
},
);
{
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale();
const img_size = canvas.getScaledImageSize();
_ = dvui.image( const viewport_rect = scroll.data().contentRect();
const scroll_current = dvui.Point{ .x = canvas.scroll.viewport.x, .y = canvas.scroll.viewport.y };
const viewport_px = dvui.Rect{
.x = viewport_rect.x * natural_scale,
.y = viewport_rect.y * natural_scale,
.w = viewport_rect.w * natural_scale,
.h = viewport_rect.h * natural_scale,
};
const scroll_px = dvui.Point{
.x = scroll_current.x * natural_scale,
.y = scroll_current.y * natural_scale,
};
canvas.updateVisibleImageRect(viewport_px, scroll_px) catch |err| {
std.debug.print("updateVisibleImageRect error: {}\n", .{err});
};
const content_w_px: u32 = img_size.x + img_size.w;
const content_h_px: u32 = img_size.y + img_size.h;
const content_w = @as(f32, @floatFromInt(content_w_px)) / natural_scale;
const content_h = @as(f32, @floatFromInt(content_h_px)) / natural_scale;
var canvas_layer = dvui.overlay(
@src(), @src(),
.{ .source = .{ .texture = tex } }, .{ .min_size_content = .{ .w = content_w, .h = content_h }, .background = false },
.{
.background = false,
.expand = .none,
.gravity_x = 0.0,
.gravity_y = 0.0,
.margin = .{ .x = left, .y = top, .w = canvas.pos.x, .h = canvas.pos.y },
.min_size_content = .{
.w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
},
.max_size_content = .{
.w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
},
},
); );
} {
} if (canvas.texture) |tex| {
canvas_layer.deinit(); const vis = canvas._visible_rect orelse ImageRect{ .x = 0, .y = 0, .w = 0, .h = 0 };
const left = @as(f32, @floatFromInt(img_size.x + vis.x)) / natural_scale;
const top = @as(f32, @floatFromInt(img_size.y + vis.y)) / natural_scale;
// Заблокировать события скролла, если нажат ctrl _ = dvui.image(
if (ctrl) { @src(),
for (dvui.events()) |*e| { .{ .source = .{ .texture = tex } },
switch (e.evt) { .{
.mouse => |mouse| { .background = false,
const action = mouse.action; .expand = .none,
if (dvui.eventMatchSimple(e, scroll.data()) and (action == .wheel_x or action == .wheel_y)) { .gravity_x = 0.0,
switch (action) { .gravity_y = 0.0,
.wheel_y => |y| { .margin = .{ .x = left, .y = top, .w = canvas.pos.x, .h = canvas.pos.y },
canvas.addZoom(y / 1000); .min_size_content = .{
canvas.redrawExample() catch {}; .w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
}, },
else => {}, .max_size_content = .{
} .w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
e.handled = true; .h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
},
},
);
}
}
canvas_layer.deinit();
if (ctrl) {
for (dvui.events()) |*e| {
switch (e.evt) {
.mouse => |mouse| {
const action = mouse.action;
if (dvui.eventMatchSimple(e, scroll.data()) and (action == .wheel_x or action == .wheel_y)) {
switch (action) {
.wheel_y => |y| {
canvas.addZoom(y / 1000);
canvas.redrawExample() catch {};
},
else => {},
}
e.handled = true;
}
},
else => {},
} }
}, }
else => {},
} }
} }
scroll.deinit();
dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 });
}
overlay.deinit();
}
textured.deinit();
} else {
var no_doc_center = dvui.box(
@src(),
.{ .dir = .vertical },
.{ .expand = .both, .padding = dvui.Rect.all(20) },
);
{
dvui.label(@src(), "No document open", .{}, .{});
if (dvui.button(@src(), "New document", .{}, .{})) {
ctx.addNewDocument() catch |err| {
std.debug.print("addNewDocument error: {}\n", .{err});
};
} }
} }
scroll.deinit(); no_doc_center.deinit();
dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 });
} }
overlay.deinit();
} }
textured.deinit(); right_panel.deinit();
} }
right_panel.deinit(); back.deinit();
} }
back.deinit(); content_row.deinit();
ctx.frame_index += 1; ctx.frame_index += 1;