Something went wrong. Try again.
Fork of dvui, the immediate-mode Zig GUI, with a font face index for Pipit
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524//! A scrollable grid widget for displaying tabular data. Also known as a//! table, TableWidget for grepping purposes.//!//! Useful to implement spreadsheet style interactions.//!//! Use `layout_only` if you only want to layout widgets.const std = @import("std");const dvui = @import("../dvui.zig");
pub const fnv = std.hash.Fnv1a_64;
const GridWidget = @This();
pub var defaults: dvui.Options = .{ .name = "Grid", // role based on layout_only in init .corners = .{ .tl = .square, .tr = .square, .br = .default, .bl = .default, }, .style = .content, .background = true, .border = .all(1),};
pub const InitOptions = struct { /// Scroll options for the grid body scroll_opts: dvui.ScrollAreaWidget.InitOpts = .{},
/// How many rows in the grid. If null use the max cell row we saw last /// frame. Required to use `rowsVisible`. rows: ?usize = null,
/// Use solely for laying out child widgets. /// * disables keyboard navigation /// * implies autoSize always layout_only: bool = false,};
pub const Cell = struct { col: usize, row: usize,};
pub const SortDirection = enum { unsorted, ascending, descending,};
pub const AutoSize = enum { rows, cols, both,};
pub const COL_MIN_WIDTH = 6;pub const COL_MIN_START = 26;pub const ROW_MIN_HEIGHT = 6;
const RowHeight = struct { row: usize, height: f32,
pub fn lower(r: usize, item: RowHeight) bool { return item.row < r; }
pub fn order(r: usize, item: RowHeight) std.math.Order { return std.math.order(r, item.row); }};
// if the cursor is a cell that wasn't run, this is how to pick the "nearest"const NavDir = enum { mouse, // visually nearest next, // "next" (tab) or leave grid prev, // "prev" (shift-tab) or leave grid left, // highest col <= cursor in row right, // lowest col => cursor in row up, // highest row <= cursor in col down, // lowest row => cursor in col};
wd: dvui.WidgetData,layout_only: bool,last_focus: dvui.Id = .zero,cols: usize,rows: usize,rows_provided: bool = false,max_seen_col: isize = -1,max_seen_row: isize = -1,first_visible_row: usize = 0,first_visible_row_y: f32 = 0,cursor: Cell = .{ .col = 0, .row = 0 },cell_widget: CellWidget,
// used to navigate across non-run cellscell_found: bool = false,cell_nearest: ?struct { col: usize, row: usize, dist: f32 } = null,cell_dir: *NavDir,
auto_size: ?AutoSize = null,default_min: dvui.Size,
shrink: bool = false,col_widths: []f32 = &.{},col_expands: []bool = &.{},col_expands_new: []bool = &.{},col_resizable: []bool = &.{},col_resize: ?usize = null,col_resize_amount: f32 = 0,col_expand: f32 = 0,col_widths_auto: std.ArrayList(f32) = .empty,col_header_height: *f32,col_header_height_auto: f32 = 0,col_header_group: dvui.FocusGroupWidget,
row_height_default: *?f32,row_heights: []RowHeight = &.{},row_heights_auto: std.ArrayList(RowHeight) = .empty,// AccessKit supportak_row_ids: std.array_hash_map.Auto(usize, dvui.Id) = .empty,
msi: *dvui.ScrollInfo, // main scroll infoscroll: dvui.ScrollAreaWidget, // main scroll areacsi: dvui.ScrollInfo = .{ .horizontal = .auto, .vertical = .none }, // column header scroll infocscroll: ?dvui.ScrollAreaWidget = null, // column header scroll arearscroll: ?dvui.ScrollAreaWidget = null, // row header scroll areabscroll: ?dvui.ScrollContainerWidget = null, // body scroll containerframe_viewport: dvui.Point = .{}, // Fixed scroll viewport for this framescroll_to_cursor: bool = false,
sort_dir: SortDirection = .unsorted,sort_col: usize = 0,
focus_touch: bool = false, // true if the grid was focused by a touch event
mouse_mode: *bool = undefined, // if false, cellHovered uses grid cursor instead of mouse .positionfocus_in_grid: *bool = undefined,focus_on_widget: ?dvui.Id = null,move_by_row: bool = false, // if true (from focusOnWidget), tab moves up/down a row, instead of right/left
pub fn init(self: *GridWidget, src: std.builtin.SourceLocation, init_opts: InitOptions, opts: dvui.Options) void { var defs = defaults; if (!init_opts.layout_only) defs.role = .grid; const options = defs.override(opts);
const default_m = options.fontGet().sizeM(4, 1).pad(dvui.TextLayoutWidget.defaults.paddingGet());
self.* = .{ .wd = dvui.WidgetData.init(src, .{ .scroll_when_focused = false }, options), .layout_only = init_opts.layout_only, .default_min = default_m, .cell_widget = undefined, .cols = undefined, .rows = undefined, .col_header_group = undefined, .row_height_default = dvui.dataGetPtrDefault(null, self.data().id, "__row_height_default", ?f32, null), .col_header_height = dvui.dataGetPtrDefault(null, self.data().id, "__col_header_height", f32, default_m.h), .scroll = undefined, .msi = undefined, .mouse_mode = dvui.dataGetPtrDefault(null, self.data().id, "__mouse_mode", bool, false), .focus_in_grid = dvui.dataGetPtrDefault(null, self.data().id, "__focus_in_grid", bool, false), .cell_dir = dvui.dataGetPtrDefault(null, self.data().id, "__cell_dir", NavDir, .mouse), };
if (self.data().id == dvui.focusedWidgetId()) self.focus_in_grid.* = true;
for (dvui.events()) |*e| { // exempt modifier keys from turning off mouse mode if (e.evt == .key and e.evt.key.action == .down and !e.evt.key.code.isModifier()) { self.mouse_mode.* = false; } else if (e.evt == .mouse and e.evt.mouse.action != .position) { self.mouse_mode.* = true; } }
self.data().register(); dvui.parentSet(self.widget()); self.data().borderAndBackground(.{});
if (dvui.dataGet(null, self.data().id, "__auto_size", AutoSize)) |which| { self.auto_size = which; dvui.dataRemove(null, self.data().id, "__auto_size"); }
self.cols = dvui.dataGet(null, self.data().id, "__cols", usize) orelse 0; self.rows = init_opts.rows orelse dvui.dataGet(null, self.data().id, "__rows", usize) orelse 0; if (init_opts.rows) |_| self.rows_provided = true;
self.col_widths = dvui.dataGetSlice(null, self.data().id, "__col_widths", []f32) orelse &.{}; if (self.cols != self.col_widths.len) { dvui.dataSetSliceCopies(null, self.data().id, "__col_widths", @as([]const f32, &.{100.0}), self.cols); const old = self.col_widths; self.col_widths = dvui.dataGetSlice(null, self.data().id, "__col_widths", []f32).?; const len = @min(old.len, self.col_widths.len); @memcpy(self.col_widths[0..len], old[0..len]); }
self.col_resizable = dvui.dataGetSlice(null, self.data().id, "__col_resizable", []bool) orelse &.{}; if (self.cols != self.col_resizable.len) { dvui.dataSetSliceCopies(null, self.data().id, "__col_resizable", @as([]const bool, &.{true}), self.cols); const old = self.col_resizable; self.col_resizable = dvui.dataGetSlice(null, self.data().id, "__col_resizable", []bool).?; const len = @min(old.len, self.col_resizable.len); @memcpy(self.col_resizable[0..len], old[0..len]); }
self.col_expands = dvui.dataGetSlice(null, self.data().id, "__col_expands", []bool) orelse &.{}; self.col_expands_new = dvui.currentWindow().arena().alloc(bool, self.cols) catch &.{}; @memset(self.col_expands_new, false);
self.row_heights = dvui.dataGetSlice(null, self.data().id, "__row_heights", []RowHeight) orelse &.{};
self.cursor = dvui.dataGet(null, self.data().id, "__cursor", Cell) orelse .{ .col = 0, .row = 0 }; // maybe the rows/cols changed, try to keep the cursor on a valid cell self.cursor.col = @min(self.cols -| 1, self.cursor.col); self.cursor.row = @min(self.rows -| 1, self.cursor.row);
self.scroll_to_cursor = dvui.dataGet(null, self.data().id, "__scroll_to_cursor", bool) orelse false;
self.sort_dir = dvui.dataGet(null, self.data().id, "__sort_dir", SortDirection) orelse .unsorted; self.sort_col = dvui.dataGet(null, self.data().id, "__sort_col", usize) orelse 0;
self.focus_touch = dvui.dataGet(null, self.data().id, "__focus_touch", bool) orelse false;
if (self.layout_only or dvui.firstFrame(self.data().id)) { self.autoSize(.both); }
if (dvui.dataGet(null, self.data().id, "__csi", dvui.ScrollInfo)) |stored| self.csi = stored;
var scroll_opts = init_opts.scroll_opts; scroll_opts.frame_viewport_out = scroll_opts.frame_viewport_out orelse &self.frame_viewport; scroll_opts.container = false;
self.scroll.init( @src(), scroll_opts, .{ .name = "GridScrollArea", .role = .none, .expand = .both, .background = false, }, );
self.msi = self.scroll.si; self.frame_viewport = scroll_opts.frame_viewport_out.?.*; // noop unless frame_viewport_out was passed into us
// expand or shrink horizontally var any_expanded = false; for (self.col_expands) |ce| any_expanded |= ce; if ((any_expanded or self.msi.horizontal == .none) and self.cols > 0) { var total: f32 = 0; for (self.col_widths) |w| total += w;
if (self.msi.viewport.w < total) { // This makes colWeight return values for all columns, not just expanded ones self.shrink = true; }
var total_weight: f32 = 0; for (0..self.cols) |col| total_weight += self.colWeight(col); if (total_weight > 0) { self.col_expand = (self.msi.viewport.w - total) / total_weight; }
if (self.msi.horizontal != .none) { // horizontal scroll available, so don't shrink self.col_expand = @max(0, self.col_expand); }
if (!any_expanded) { // not expanding, so only shrink self.col_expand = @min(0, self.col_expand); }
// can never shrink to nothing (protects against factor calculation when resizing) self.col_expand = @max(-0.99, self.col_expand); }}
/// Focus the grid if neither it nor any widget inside has focus.pub fn ensureFocus(self: *GridWidget) void { if (!self.focus_in_grid.*) { dvui.focusWidget(self.data().id, null, null); }}
pub const AutoSizeOptions = struct { auto: AutoSize, min_width: ?f32 = null, min_height: ?f32 = null, max_width: ?f32 = null, max_height: ?f32 = null,};
/// Resize cols/rows to fit the contents.////// If not working, try adding min_size_content/max_size_content to cells.////// autoSize goes multiple frames until all run cells are settled.pub fn autoSize(self: *GridWidget, auto: AutoSize) void { self.auto_size = auto;}
/// Return first/last row in the viewport. Must pass `.rows` to `init`.pub fn rowsVisible(self: *GridWidget) struct { usize, usize } { if (!self.rows_provided) { dvui.log.err("GridWidget: {x} rowsVisible() requires InitOptions.rows", .{self.data().id}); dvui.Debug.errorOutline(self.data().rectScale().r); return .{ 0, self.rows }; }
if (self.msi.viewport.h == 0) { // First frame, run the rows we are likely to see. return .{ 0, @min(50, self.rows) }; }
// expand the visible rows by this on each side so keyboard navigation // works to unseen rows const extra: usize = 1; const start_y: f32 = @max(0, self.frame_viewport.y); const end_y: f32 = self.frame_viewport.y + self.msi.viewport.h;
var r: usize = 0; var y: f32 = 0; var rh: f32 = self.rowHeight(r);
// find first row where bottom is visible while (r < self.rows and (y + rh) <= start_y) { r += 1; y += rh; rh = self.rowHeight(r); }
const start = r; self.first_visible_row = r; self.first_visible_row_y = y;
// go until first non-visible row (because last is exclusive) while (r < self.rows and y < end_y) { r += 1; y += rh; rh = self.rowHeight(r); }
//std.debug.print("first {d} {d} to {d} {d} start {d} {d}\n", .{ self.first_visible_row, self.first_visible_row_y, r, y, start_y, end_y });
return .{ start -| extra, @min(r + extra, self.rows) };}
pub fn widget(self: *GridWidget) dvui.Widget { return dvui.Widget.init(self, data, rectFor, screenRectScale, minSizeForChild);}
pub fn data(self: *GridWidget) *dvui.WidgetData { return self.wd.validate();}
pub fn rectFor(self: *GridWidget, id: dvui.Id, min_size: dvui.Size, e: dvui.Options.Expand, g: dvui.Options.Gravity) dvui.Rect { _ = id; return dvui.placeIn(self.data().contentRect().justSize(), min_size, e, g);}
pub fn screenRectScale(self: *GridWidget, rect: dvui.Rect) dvui.RectScale { return self.data().contentRectScale().rectToRectScale(rect);}
pub fn minSizeForChild(self: *GridWidget, s: dvui.Size) void { self.data().minSizeMax(self.data().options.padSize(s));}
pub const CellWidget = struct { grid: *GridWidget, col: usize, row: usize, grid_focus: bool, wd: dvui.WidgetData, layout: dvui.BasicLayout = .{},
pub const InitOptions = struct { grid: *GridWidget, col: usize, row: usize, grid_focus: bool, draw_focus: bool = true, fade: ?f32 = 0.0, };
pub fn init(self: *CellWidget, src: std.builtin.SourceLocation, init_opts: CellWidget.InitOptions, opts: dvui.Options) void { if (init_opts.col < init_opts.grid.col_expands_new.len and opts.expandGet().isHorizontal()) { init_opts.grid.col_expands_new[init_opts.col] = true; }
// expand is used to control col/row stuff but turn it off here - we // are given an explicit rect anyway var local_opts = opts; local_opts.expand = .none;
const defs: dvui.Options = .{ .name = "Cell" }; self.* = .{ .grid = init_opts.grid, .col = init_opts.col, .row = init_opts.row, .grid_focus = init_opts.grid_focus, .wd = dvui.WidgetData.init(src, .{}, defs.override(local_opts)), };
dvui.parentSet(self.widget()); self.data().register(); self.data().borderAndBackground(.{ .fade = init_opts.fade });
if (self.grid_focus and init_opts.draw_focus) { const rs = self.data().backgroundRectScale(); if (!rs.r.empty()) { const fill = (dvui.themeGet().text_select orelse dvui.themeGet().color(.highlight, .fill)).opacity(0.75); rs.r.fill(self.data().options.cornersGet().scale(rs.s, dvui.CornerRect.Physical), .{ .color = .{ .color = fill } }); } } }
pub const FocusOnWidgetOptions = struct { /// Widget id to focus if this grid cell is selected. id: dvui.Id,
/// Focus id if any cell in the row is selected. row: bool = false, };
/// Tie grid cell focus to a widget: /// * focus the widget if the cell is selected /// * when widget is focused, select this cell pub fn focusOnWidget(self: *CellWidget, opts: FocusOnWidgetOptions) void { if (self.grid_focus) { dvui.focusWidget(opts.id, null, null); }
if (self.grid.focus_in_grid.*) { if (opts.row and self.row == self.grid.cursor.row) { self.grid.cursor.row = self.row; self.grid.cursor.col = self.col;
// Need to defer this, because focus_in_grid can be true for 1 // frame after the user clicks outside the grid. self.grid.focus_on_widget = opts.id; } }
if (opts.id == dvui.focusedWidgetId()) { self.grid.cursor.row = self.row; self.grid.cursor.col = self.col; if (opts.row) self.grid.move_by_row = true; } }
pub fn widget(self: *CellWidget) dvui.Widget { return dvui.Widget.init(self, CellWidget.data, CellWidget.rectFor, CellWidget.screenRectScale, CellWidget.minSizeForChild); }
pub fn data(self: *CellWidget) *dvui.WidgetData { return self.wd.validate(); }
pub fn rectFor(self: *CellWidget, id: dvui.Id, min_size: dvui.Size, e: dvui.Options.Expand, g: dvui.Options.Gravity) dvui.Rect { return self.layout.rectFor(self.data().contentRect().justSize(), id, min_size, e, g); }
pub fn screenRectScale(self: *CellWidget, rect: dvui.Rect) dvui.RectScale { return self.data().contentRectScale().rectToRectScale(rect); }
pub fn minSizeForChild(self: *CellWidget, s: dvui.Size) void { const ms = self.layout.minSizeForChild(s); self.data().minSizeMax(self.data().options.padSize(ms)); }
pub fn deinit(self: *CellWidget) void { defer self.* = undefined;
self.wd.min_size = self.wd.min_size.min(self.wd.options.max_sizeGet()); self.grid.cellMinSize(self.col, self.row, self.wd.min_size);
dvui.parentReset(self.data().id, self.data().parent); }
pub const EditableInitOptions = struct { text: []const u8,
/// When editing, this is passed to TextEntryWidget.filterIn. filter_in: []const u8 = &.{},
/// Limit number of bytes when editing. limit: usize = 10_000, };
/// If the user edits the value and presses enter or clicks away, we return /// the edited value. /// /// If the user makes no change or presses escape, return null. pub fn editable(self: *CellWidget, init_opts: EditableInitOptions, options: dvui.Options) ?[]u8 { const defs: dvui.Options = .{ .name = "Cell.editable", .margin = .{}, .border = .{}, .corners = .{}, .min_size_content = .{}, .expand = .both, .background = false }; const opts = defs.override(options); var ret: ?[]u8 = null;
const src = @src(); const id = dvui.parentGet().extendId(src, opts.idExtra()); const editing = dvui.dataGet(null, id, "__editing", bool) orelse false;
if (!editing) { var tl: dvui.TextLayoutWidget = undefined; tl.init(src, .{ .process_events_in_deinit = false }, opts); // specifically not calling touchEditing or processEvents tl.addText(init_opts.text, .{}); tl.deinit();
if (self.grid_focus) { // On desktop we enable text events so the user can start // typing to transition to editing. But phones show the on // screen keyboard, so don't if the grid was focused by touch. if (!self.grid.focus_touch) { dvui.wantTextInput(self.data().borderRectScale().r.toNatural()); }
const evts = dvui.events(); for (evts) |*e| { if (!dvui.eventMatch(e, .{ .id = self.grid.data().id, .r = self.data().rectScale().r })) continue;
switch (e.evt) { .mouse => |me| { if (dvui.captured(self.grid.data().id)) { // grid itself already handled the press and // motion parts, but since grid has capture we // need to check against our rect here if (me.action == .release and me.button.pointer() and self.data().rectScale().r.contains(me.p)) { e.handle(@src(), self.data()); dvui.captureMouse(null, e.num); if (dvui.dragging(me.p, null)) |_| { dvui.dragEnd(); } else { dvui.dataSet(null, id, "__editing", true); dvui.dataSet(null, id, "__editing_first_frame", true); dvui.focusWidget(id, null, e.num); dvui.refresh(null, @src(), self.data().id); } } } }, .key => |ke| { if (ke.action == .down and ke.code == .enter) { e.handle(@src(), self.data()); dvui.dataSet(null, id, "__editing", true); dvui.dataSet(null, id, "__editing_first_frame", true); dvui.focusWidget(id, null, e.num); dvui.refresh(null, @src(), self.data().id); } else if (ke.action == .down and (ke.code == .backspace or ke.code == .delete)) { e.handle(@src(), self.data()); dvui.refresh(null, @src(), self.data().id); return &.{}; } }, .text => |te| { if (te.action == .value) { e.handle(@src(), self.data()); dvui.dataSet(null, id, "__editing", true); dvui.dataSet(null, id, "__editing_first_frame", true); dvui.focusWidget(id, null, e.num); dvui.refresh(null, @src(), self.data().id);
dvui.dataSetSlice(null, id, "__editing_first_frame_text", te.action.value.txt); } }, else => {}, } } } } else { var te: dvui.TextEntryWidget = undefined; te.init(src, .{ .text = .{ .internal = .{ .limit = init_opts.limit } }, .multiline = true, .break_lines = true, .scroll_horizontal = false }, opts);
var escape = false; var enter = false; var enter_shift = false; const evts = dvui.events(); for (evts) |*e| { if (!te.matchEvent(e)) continue;
switch (e.evt) { .key => |*ke| { if (ke.action == .down and ke.code == .escape) { e.handle(@src(), te.data()); dvui.dataRemove(null, id, "__editing"); dvui.focusWidget(self.grid.data().id, null, e.num); dvui.refresh(null, @src(), id); escape = true; } else if (ke.action == .down and ke.code == .tab) { e.handle(@src(), te.data()); dvui.dataRemove(null, id, "__editing"); dvui.focusWidget(self.grid.data().id, null, e.num); _ = self.grid.moveCursorTab(ke.mod.shift()); dvui.refresh(null, @src(), id); } else if ((ke.action == .down or ke.action == .repeat) and ke.code == .enter) { if (ke.mod.matchBind("ctrl/cmd")) { // text entry will process enter like normal } else { e.handle(@src(), te.data()); enter = true; if (ke.mod.shift()) enter_shift = true; } } }, else => {}, } }
te.processEvents();
if (dvui.dataGet(null, id, "__editing_first_frame", bool) orelse false) { dvui.dataRemove(null, id, "__editing_first_frame"); if (dvui.dataGetSlice(null, id, "__editing_first_frame_text", []u8)) |txt| { te.textTyped(txt, false); } else { te.textTyped(init_opts.text, false); } }
te.filterIn(init_opts.filter_in);
te.draw();
if (!escape and id != dvui.focusedWidgetIdInCurrentSubwindow()) { // we lost focus if (!std.mem.eql(u8, init_opts.text, te.textGet())) ret = te.textGet(); dvui.dataRemove(null, id, "__editing"); dvui.refresh(null, @src(), id); }
if (enter) { if (!std.mem.eql(u8, init_opts.text, te.textGet())) ret = te.textGet(); dvui.dataRemove(null, id, "__editing"); dvui.focusWidget(self.grid.data().id, null, 0); dvui.refresh(null, @src(), id); if (enter_shift) { self.grid.moveCursor(self.grid.cursor.col, self.grid.cursor.row -| 1); } else { self.grid.moveCursor(self.grid.cursor.col, self.grid.cursor.row + 1); } }
te.deinit(); }
return ret; }
pub fn headerSortable(self: *CellWidget, text: []const u8, options: dvui.Options) ?SortDirection { const defs: dvui.Options = .{ .name = "Cell.headerSortable", .margin = .{}, .border = .{}, .corners = .{}, .min_size_content = .{}, .expand = .both }; const opts = defs.override(options);
const sort: SortDirection = if (self.col == self.grid.sort_col) self.grid.sort_dir else .unsorted; const src = @src(); const sort_changed = switch (sort) { // Use same src for each button so they get the same id and can retain focus accross frames. .unsorted => blk: { const clicked = dvui.button(src, text, .{}, opts);
// bump up cell min size to account for possible icon const h = opts.fontGet().textHeight(); const w = dvui.iconWidth("chevron_small_up", dvui.entypo.chevron_small_up, h) catch h; self.data().min_size.w += w;
break :blk clicked; }, .ascending => dvui.buttonLabelAndIcon(src, .{ .label = text, .icon_label = "sorted ascending", .tvg_bytes = dvui.entypo.chevron_small_up, }, opts), .descending => dvui.buttonLabelAndIcon(src, .{ .label = text, .icon_label = "sorted descending", .tvg_bytes = dvui.entypo.chevron_small_down, }, opts), };
if (sort_changed) { if (self.col == self.grid.sort_col) { self.grid.sort_dir = if (self.grid.sort_dir == .ascending) .descending else .ascending; } else { self.grid.sort_col = self.col; self.grid.sort_dir = .ascending; }
return self.grid.sort_dir; }
return null; }};
fn colWeight(self: *GridWidget, col: usize) f32 { if (col >= self.cols) return 0;
if (self.shrink and (col >= self.col_resizable.len or !self.col_resizable[col])) return 0;
if (self.shrink or (col < self.col_expands.len and self.col_expands[col])) { const w = self.col_widths[col]; if (w <= COL_MIN_WIDTH) return 0 else return w; }
return 0;}
pub fn colWidth(self: *GridWidget, col: usize) f32 { if (col < self.cols) { return @max(COL_MIN_WIDTH, self.col_widths[col] + self.col_expand * self.colWeight(col)); } return 100;}
pub fn colOffset(self: *GridWidget, col: usize) f32 { var x: f32 = 0; for (0..col) |i| x += self.colWidth(i); return x;}
pub fn rowHeight(self: *GridWidget, row: usize) f32 { if (std.sort.binarySearch(RowHeight, self.row_heights, row, RowHeight.order)) |idx| { return self.row_heights[idx].height; }
return self.row_height_default.* orelse self.default_min.h;}
pub fn rowOffset(self: *GridWidget, row: usize) f32 { var r = self.first_visible_row; var ry = self.first_visible_row_y; while (r > row) { r -= 1; ry -= self.rowHeight(r); } while (r < row) { ry += self.rowHeight(r); r += 1; }
return ry;}
pub const ColHeaderInitOptions = struct { col: usize, resizable: bool = true,};
pub fn colHeader(self: *GridWidget, init_opts: ColHeaderInitOptions, opts: dvui.Options) *CellWidget { if (self.cscroll == null) { if (self.bscroll != null) { dvui.log.debug("GridWidget {x} colHeader called after cell", .{self.data().id}); dvui.Debug.errorOutline(self.bscroll.?.data().rectScale().r); } else { self.cscroll = @as(dvui.ScrollAreaWidget, undefined); self.cscroll.?.init(@src(), .{ .horizontal_bar = .hide, .vertical_bar = .hide, .scroll_info = &self.csi, .frame_viewport = .{ .x = self.frame_viewport.x }, .process_events_after = false, }, .{ .name = "GridColumnHeaderScroll", .role = .header, .expand = .horizontal, }); if (!self.layout_only) { self.col_header_group.init(@src(), .{ .nav_key_dir = .horizontal }, .{ .tab_index = self.data().options.tab_index }); } } }
self.max_seen_col = @max(self.max_seen_col, @as(isize, @intCast(init_opts.col))); var hash = fnv.init(); hash.update("col"); hash.update(std.mem.asBytes(&init_opts.col)); hash.update("header");
const rect: dvui.Rect = .{ .x = self.colOffset(init_opts.col), .y = 0, .w = self.colWidth(init_opts.col), .h = self.col_header_height.*, };
const defs: dvui.Options = .{ .rect = rect, .id_extra = @truncate(hash.final()) };
self.cell_widget.init(@src(), .{ .grid = self, .col = init_opts.col, .row = std.math.maxInt(usize), .grid_focus = false }, defs.override(opts));
if (init_opts.col < self.col_resizable.len) self.col_resizable[init_opts.col] = init_opts.resizable;
if (init_opts.resizable) { // column resizing var rs = self.cell_widget.data().rectScale(); rs.r.x = rs.r.x + rs.r.w - COL_MIN_WIDTH * rs.s; rs.r.w = COL_MIN_WIDTH * rs.s; const wd = self.cell_widget.data(); const evts = dvui.events(); for (evts) |*e| { if (!dvui.eventMatch(e, .{ .id = wd.id, .r = rs.r })) continue;
switch (e.evt) { .mouse => |me| { if (me.action == .focus) { e.handle(@src(), wd); } else if (me.action == .press and me.button.pointer()) { e.handle(@src(), wd); dvui.captureMouse(wd, e.num); dvui.dragPreStart(me.button, me.p, .{}); } else if (me.action == .release and me.button.pointer()) { e.handle(@src(), wd); dvui.captureMouse(null, e.num); dvui.dragEnd(); } else if (me.action == .motion) { if (dvui.captured(wd.id)) { e.handle(@src(), wd); if (dvui.dragging(me.p, null)) |dp| { const dx = dp.x / rs.s; self.col_resize = init_opts.col; self.col_resize_amount += dx; dvui.refresh(null, @src(), wd.id); } } } else if (me.action == .position) { dvui.cursorSet(.arrow_w_e); } }, else => {}, } } }
return &self.cell_widget;}
pub fn ensureBodyScroll(self: *GridWidget) void { if (self.cscroll) |*cscroll| { if (!self.layout_only) { self.col_header_group.deinit(); }
var tw: f32 = 0; for (self.col_widths) |w| tw += w; const s: dvui.Size = .{ .w = tw, .h = self.col_header_height.* }; cscroll.scroll.?.minSizeForChild(s);
cscroll.deinit(); self.cscroll = null; }
if (self.bscroll == null) { self.bscroll = @as(dvui.ScrollContainerWidget, undefined); self.bscroll.?.init(@src(), self.msi, .{ .scroll_area = &self.scroll, .frame_viewport = self.frame_viewport, .event_rect = self.scroll.data().borderRectScale().r, }, .{ .name = "GridBodyScroll", .expand = .both, .background = false, }); self.bscroll.?.processEvents();
// record last_focus here so it doesn't cover the column headers self.last_focus = dvui.lastFocusedIdInFrame();
if (!self.layout_only) { // do this here so the body of the grid comes after the headers dvui.tabIndexSet(self.data().id, self.data().options.tab_index, self.data().rectScale().r); } }}
pub const CellOptions = struct { col: usize, row: usize, draw_focus: bool = true,};
pub fn cell(self: *GridWidget, cell_opts: CellOptions, opts: dvui.Options) *CellWidget { self.ensureBodyScroll();
self.max_seen_col = @max(self.max_seen_col, @as(isize, @intCast(cell_opts.col))); self.max_seen_row = @max(self.max_seen_row, @as(isize, @intCast(cell_opts.row)));
const rect: dvui.Rect = .{ .x = self.colOffset(cell_opts.col), .y = self.rowOffset(cell_opts.row), .w = self.colWidth(cell_opts.col), .h = self.rowHeight(cell_opts.row), };
const at_cursor = cell_opts.col == self.cursor.col and cell_opts.row == self.cursor.row; if (at_cursor) self.cell_found = true; if (!self.cell_found) { var dist: ?f32 = null; switch (self.cell_dir.*) { .mouse => { dist = @abs(@as(f32, @floatFromInt(self.cursor.col)) - @as(f32, @floatFromInt(cell_opts.col))) + @abs(@as(f32, @floatFromInt(self.cursor.row)) - @as(f32, @floatFromInt(cell_opts.row))); },
.next => { if (cell_opts.row > self.cursor.row or (cell_opts.row == self.cursor.row and cell_opts.col > self.cursor.col)) dist = @floatFromInt(cell_opts.row * self.cols + cell_opts.col); }, .prev => { if (cell_opts.row < self.cursor.row or (cell_opts.row == self.cursor.row and cell_opts.col < self.cursor.col)) { const rowdiff = self.cursor.row - cell_opts.row; // >= 0 dist = @floatFromInt(rowdiff * self.cols + (self.cols - cell_opts.col)); } }, .left => { if (cell_opts.row == self.cursor.row) dist = @floatFromInt(if (cell_opts.col < self.cursor.col) self.cursor.col - cell_opts.col else cell_opts.col); }, .right => { if (cell_opts.row == self.cursor.row) dist = @floatFromInt(if (cell_opts.col < self.cursor.col) self.cols + self.cursor.col - cell_opts.col else cell_opts.col); }, .up => { if (cell_opts.col == self.cursor.col) dist = @floatFromInt(if (cell_opts.row < self.cursor.row) self.cursor.row - cell_opts.row else cell_opts.row); }, .down => { if (cell_opts.col == self.cursor.col) dist = @floatFromInt(if (cell_opts.row < self.cursor.row) self.rows + self.cursor.row - cell_opts.row else cell_opts.row); }, }
if (dist) |d| { if (self.cell_nearest == null or d < self.cell_nearest.?.dist) self.cell_nearest = .{ .col = cell_opts.col, .row = cell_opts.row, .dist = d }; } }
const grid_focus = self.data().id == dvui.focusedWidgetId() and at_cursor;
if (grid_focus and self.scroll_to_cursor) { self.scroll_to_cursor = false; dvui.scrollTo(.{ .screen_rect = self.bscroll.?.screenRectScale(rect).r }); }
if (dvui.accesskit_enabled and !self.layout_only) { // If this is a new row, then create an accessible row node to parent all the cells // grid_cell_row must be set before the cell's box widget is created. if (self.ak_row_ids.get(cell_opts.row)) |row_id| { dvui.currentWindow().accesskit.grid_cell_row = row_id; } else { const rowrect: dvui.Rect = .{ .x = 0, .y = self.rowOffset(cell_opts.row), .w = self.colOffset(self.cols), .h = self.rowHeight(cell_opts.row), }; var vp = dvui.overlay(@src(), .{ .role = .row, .name = "GridRow", .id_extra = cell_opts.row, .rect = rowrect }); defer vp.deinit(); self.ak_row_ids.put(dvui.currentWindow().arena(), cell_opts.row, vp.data().id) catch {}; dvui.currentWindow().accesskit.grid_cell_row = vp.data().id; } }
const id_extra: usize = (cell_opts.col << @bitSizeOf(usize) / 2) | cell_opts.row; const defs: dvui.Options = .{ .role = .grid_cell, .rect = rect, .id_extra = id_extra };
self.cell_widget.init(@src(), .{ .grid = self, .col = cell_opts.col, .row = cell_opts.row, .grid_focus = grid_focus, .draw_focus = cell_opts.draw_focus }, defs.override(opts));
// now that cell_widget has done init/register, we can reset grid_cell_row dvui.currentWindow().accesskit.grid_cell_row = .zero; if (!self.layout_only) { if (self.cell_widget.data().accesskit_node()) |ak_node| { dvui.AccessKit.nodeSetRowIndex(ak_node, cell_opts.row); dvui.AccessKit.nodeSetColumnIndex(ak_node, cell_opts.col); } }
return &self.cell_widget;}
pub fn cellMinSize(self: *GridWidget, col: usize, row: usize, min_size: dvui.Size) void { while (col >= self.col_widths_auto.items.len) { self.col_widths_auto.append(dvui.currentWindow().arena(), 10) catch {}; } if (col < self.col_widths_auto.items.len) { self.col_widths_auto.items[col] = @max(self.col_widths_auto.items[col], COL_MIN_WIDTH, min_size.w); }
if (row == std.math.maxInt(usize)) { self.col_header_height_auto = @max(self.col_header_height_auto, min_size.h); } else { const h = @max(ROW_MIN_HEIGHT, min_size.h); if (self.row_height_default.*) |def| { self.row_height_default.* = @max(ROW_MIN_HEIGHT, @min(def, h)); } else { self.row_height_default.* = @max(ROW_MIN_HEIGHT, h); }
const pp = std.sort.partitionPoint(RowHeight, self.row_heights_auto.items, row, RowHeight.lower); if (pp == self.row_heights_auto.items.len or self.row_heights_auto.items[pp].row > row) { self.row_heights_auto.insert(dvui.currentWindow().arena(), pp, .{ .row = row, .height = h }) catch {}; } else { self.row_heights_auto.items[pp].height = @max(self.row_heights_auto.items[pp].height, h); } }}
pub fn cellFromPoint(self: *GridWidget, p: dvui.Point.Physical) ?Cell { self.ensureBodyScroll();
const logical = self.bscroll.?.pointFromPhysical(p); if (logical.x < 0 or logical.y < 0) return null;
var col: usize = 0; var x: f32 = 0; while (x < logical.x) { x += self.colWidth(col); col += 1; }
var row = self.first_visible_row; var y = self.first_visible_row_y; while (y < logical.y) { y += self.rowHeight(row); row += 1; } return .{ .col = col -| 1, .row = row -| 1, };}
/// If mouse is being used, return the grid cell under mouse if any. If/// keyboard is being used and focus is in the grid, return the grid cursor.pub fn cellHovered(self: *GridWidget) ?Cell { self.ensureBodyScroll();
if (self.mouse_mode.*) { const evts = dvui.events(); for (evts) |*e| { if (!dvui.eventMatchSimple(e, self.data())) continue;
if (e.evt == .mouse and e.evt.mouse.action == .position) { return self.cellFromPoint(e.evt.mouse.p); } } } else if (self.focus_in_grid.*) { return self.cursor; }
return null;}
pub const CellActivatedReturn = struct { cell: Cell, event: dvui.Event,};
pub fn cellActivated(self: *GridWidget) ?CellActivatedReturn { var ret: ?CellActivatedReturn = null;
self.ensureBodyScroll(); for (dvui.events()) |*e| { if (!dvui.eventMatchSimple(e, self.data())) continue;
switch (e.evt) { .mouse => |me| { // press and motion already handled in deinit if (me.action == .release and me.button.pointer()) { if (dvui.captured(self.data().id)) { e.handle(@src(), self.data()); dvui.captureMouse(null, e.num); if (dvui.dragging(me.p, null)) |_| { dvui.dragEnd(); continue; }
if (self.cellFromPoint(me.p)) |cel| { // need to focus ourselves again because // focusOnWidget could have stolen focus // during mouse down dvui.focusWidget(self.data().id, null, e.num); self.moveCursor(cel.col, cel.row); dvui.refresh(null, @src(), self.data().id); ret = .{ .cell = cel, .event = e.* }; continue; } } } }, .key => |ke| { if (ke.action == .down or ke.action == .repeat) { if (ke.matchBind("activate")) { e.handle(@src(), self.data()); ret = .{ .cell = self.cursor, .event = e.* }; dvui.refresh(null, @src(), self.data().id); continue; } } }, else => {}, } }
return ret;}
pub fn matchEvent(self: *GridWidget, e: *dvui.Event) bool { return dvui.eventMatchSimple(e, self.data());}
pub fn moveCursor(self: *GridWidget, col: usize, row: usize) void { self.cursor.col = @min(self.cols -| 1, col); self.cursor.row = @min(self.rows -| 1, row); self.scroll_to_cursor = true;}
/// False if trying to move past the last cell (or backwards past the first).////// If move_by_row is true, moves by whole rows.pub fn moveCursorTab(self: *GridWidget, shift: bool) bool { if (self.move_by_row) { if (shift) { self.cell_dir.* = .up; if (self.cursor.row == 0) { // at the first row, nowhere to go return false; } else { self.moveCursor(self.cursor.col, self.cursor.row - 1); } } else { self.cell_dir.* = .down; if (self.cursor.row + 1 == self.rows) { // at the final row, nowhere to go return false; } else { self.moveCursor(self.cursor.col, self.cursor.row + 1); } }
return true; }
if (shift) { // move backwards self.cell_dir.* = .prev; if (self.cursor.col == 0) { if (self.cursor.row == 0) { // at the first cell, nowhere to go return false; } else { self.moveCursor(self.cols -| 1, self.cursor.row - 1); } } else { self.moveCursor(self.cursor.col - 1, self.cursor.row); } } else { self.cell_dir.* = .next; if (self.cursor.col + 1 == self.cols) { if (self.cursor.row + 1 == self.rows) { // at the final cell, nowhere to go return false; } else { self.moveCursor(0, self.cursor.row + 1); } } else { self.moveCursor(self.cursor.col + 1, self.cursor.row); } }
return true;}
fn colExpanded(self: *GridWidget, col: usize) bool { return col < self.col_expands.len and self.col_expands[col];}
pub fn deinit(self: *GridWidget) void { defer if (dvui.widgetIsAllocated(self)) dvui.widgetFree(self); defer self.* = undefined;
self.ensureBodyScroll();
const focus_id = dvui.lastFocusedIdInFrameSince(self.last_focus); if (self.data().id != dvui.focusedWidgetId()) { if (focus_id != null) { if (self.focus_in_grid.* == false) dvui.refresh(null, @src(), self.data().id); self.focus_in_grid.* = true;
if (self.focus_on_widget) |id| { dvui.focusWidget(id, null, null); } } else { if (self.focus_in_grid.* == true) dvui.refresh(null, @src(), self.data().id); self.focus_in_grid.* = false; } }
if (!self.layout_only) { if (!self.cell_found) { if (self.cell_nearest) |cn| { self.moveCursor(cn.col, cn.row); } else if (self.cell_dir.* == .next) { dvui.tabIndexNext(null); // exit the grid } else if (self.cell_dir.* == .prev) { dvui.tabIndexPrev(null); // exit the grid }
self.cell_dir.* = .mouse; dvui.refresh(null, @src(), self.data().id); }
var focused_this_frame = false; const wd = self.data(); const evts = dvui.events(); for (evts) |*e| { if (!dvui.eventMatch(e, .{ .id = wd.id, .focus_id = focus_id, .r = wd.borderRectScale().r })) continue;
switch (e.evt) { .mouse => |me| { if (me.action == .focus) { e.handle(@src(), wd); if (!self.focus_in_grid.*) { focused_this_frame = true; if (self.cellFromPoint(me.p)) |cel| { self.moveCursor(cel.col, cel.row); } } // focus so that we can receive keyboard input dvui.focusWidget(wd.id, null, e.num); dvui.dataSet(null, wd.id, "__focus_touch", me.button.touch()); } else if (me.action == .press and me.button.pointer()) { e.handle(@src(), wd); // ignore the press if we just got focus, prevents: // * last-focused cell from flashing // * editing if you happened to click on the last-focused cell if (!focused_this_frame) { dvui.captureMouse(wd, e.num); dvui.dragPreStart(me.button, me.p, .{}); } } else if (me.action == .motion and me.button.touch()) { if (dvui.captured(wd.id)) { if (dvui.dragging(me.p, null)) |_| { // touch: overcame drag threshold, user wanted to scroll dvui.captureMouse(null, e.num); dvui.dragEnd(); } } } else if (me.action == .release and me.button.pointer()) { if (dvui.captured(wd.id)) { e.handle(@src(), wd); dvui.captureMouse(null, e.num); if (dvui.dragging(me.p, null)) |_| { dvui.dragEnd(); } else { // only process click if we didn't start a drag if (self.cellFromPoint(me.p)) |cel| { // need to focus ourselves again because // focusOnWidget could have stolen focus // during mouse down dvui.focusWidget(wd.id, null, e.num); self.moveCursor(cel.col, cel.row); self.cell_dir.* = .mouse; dvui.refresh(null, @src(), wd.id); } } } } }, .key => |ke| { if (ke.action == .down or ke.action == .repeat) { if (ke.matchBind("char_up")) { e.handle(@src(), self.data()); self.moveCursor(self.cursor.col, self.cursor.row -| 1); self.cell_dir.* = .up; dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("char_down")) { e.handle(@src(), self.data()); self.moveCursor(self.cursor.col, self.cursor.row + 1); self.cell_dir.* = .down; dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("char_left")) { e.handle(@src(), self.data()); self.moveCursor(self.cursor.col -| 1, self.cursor.row); self.cell_dir.* = .left; dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("char_right")) { e.handle(@src(), self.data()); self.moveCursor(self.cursor.col + 1, self.cursor.row); self.cell_dir.* = .right; dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("text_start")) { e.handle(@src(), self.data()); self.moveCursor(0, 0); // force scroll in case user is using rowsVisible, we only scroll to cursor if we run that cell self.bscroll.?.si.scrollToFraction(.vertical, 0.0); dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("text_end")) { e.handle(@src(), self.data()); self.moveCursor(self.cols -| 1, self.rows -| 1); // force scroll in case user is using rowsVisible, we only scroll to cursor if we run that cell self.bscroll.?.si.scrollToFraction(.vertical, 1.0); dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("line_start")) { e.handle(@src(), self.data()); self.moveCursor(0, self.cursor.row); self.cell_dir.* = .left; dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.matchBind("line_end")) { e.handle(@src(), self.data()); self.moveCursor(self.cols -| 1, self.cursor.row); self.cell_dir.* = .right; dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); continue; } if (ke.code == .tab) { if (self.moveCursorTab(ke.mod.shift())) { e.handle(@src(), self.data()); dvui.focusWidget(self.data().id, null, e.num); dvui.refresh(null, @src(), self.data().id); } else { // let dvui move focus outside the grid // // focus the grid in case we were focused on a // widget inside the grid without a tab index // so the focus moves predictably (otherwise // dvui assumes focus was lost and restarts // from the mouse position) dvui.focusWidget(self.data().id, null, e.num); self.focus_in_grid.* = false; } continue; } } }, else => {}, }
if (!e.handled) { self.bscroll.?.processEventAfter(e); } } }
var tw: f32 = 0; for (self.col_widths) |w| tw += w; const s: dvui.Size = .{ .w = tw, .h = self.rowOffset(self.rows) }; self.bscroll.?.minSizeForChild(s); self.bscroll.?.deinit();
self.scroll.deinit();
// sync header and main scroll info if (self.csi.viewport.x != self.frame_viewport.x) self.msi.viewport.x = self.csi.viewport.x; if (self.msi.viewport.x != self.frame_viewport.x) self.csi.viewport.x = self.msi.viewport.x;
dvui.dataSet(null, self.data().id, "__cols", @as(usize, @intCast(self.max_seen_col + 1))); dvui.dataSet(null, self.data().id, "__rows", @as(usize, @intCast(self.max_seen_row + 1))); if (!self.layout_only) { if (self.data().accesskit_node()) |ak_node| { const num_rows = if (self.rows_provided) self.rows else @as(usize, @intCast(self.max_seen_row + 1)); dvui.AccessKit.nodeSetRowCount(ak_node, num_rows); dvui.AccessKit.nodeSetColumnCount(ak_node, @intCast(self.max_seen_col + 1)); } }
if (self.auto_size) |which| { var auto_size_next_frame = false;
if (which == .cols or which == .both) { for (self.col_widths_auto.items, 0..) |w, col| { if (col >= self.col_widths.len or w != self.col_widths[col]) { //std.debug.print("col {d} prev {d} new {d}\n", .{ col, if (col >= self.col_widths.len) -1 else self.col_widths[col], w }); auto_size_next_frame = true; } }
dvui.dataSetSlice(null, self.data().id, "__col_widths", self.col_widths_auto.items); }
if (which == .rows or which == .both) { for (self.row_heights_auto.items) |rh| { if (rh.height != self.rowHeight(rh.row)) { //std.debug.print("row {d} prev {d} new {d}\n", .{ rh.row, self.rowHeight(rh.row), rh.height }); auto_size_next_frame = true; } }
// merge existing row heights into ones we saw this frame for (self.row_heights) |rh| { const pp = std.sort.partitionPoint(RowHeight, self.row_heights_auto.items, rh.row, RowHeight.lower); if (pp == self.row_heights_auto.items.len or self.row_heights_auto.items[pp].row > rh.row) { self.row_heights_auto.insert(dvui.currentWindow().arena(), pp, rh) catch {}; } } dvui.dataSetSlice(null, self.data().id, "__row_heights", self.row_heights_auto.items); self.col_header_height.* = self.col_header_height_auto; }
if (auto_size_next_frame) { //std.debug.print("auto sizing next frame\n", .{}); dvui.dataSet(null, self.data().id, "__auto_size", which); dvui.refresh(null, @src(), self.data().id); } }
if (self.auto_size == null or self.auto_size.? == .rows) { if (self.col_resize) |col| { // We are not autosizing columns, and the user is manually resizing col const factor = 1 + self.col_expand; var resize_expanded: f32 = 0;
if (self.col_resize_amount < 0) { // shrinking this column (and possibly columns to the left) var resize = self.col_resize_amount; var col_left = col; while (true) : (col_left -= 1) { if (col_left < self.col_resizable.len and !self.col_resizable[col_left]) { if (col_left == 0) break else continue; }
const weight = self.colWeight(col_left) > 0; var amt = resize; if (weight) amt /= factor; amt = @max(amt, COL_MIN_WIDTH - self.col_widths[col_left]); self.col_widths[col_left] += amt; if (weight) amt *= factor; resize -= amt;
if (!self.shrink and self.colExpanded(col_left)) resize_expanded += amt;
if (col_left == 0 or resize > -0.01) break; } } else { // expanding this column const col_weight = self.colWeight(col) > 0; self.col_widths[col] += if (col_weight) self.col_resize_amount / factor else self.col_resize_amount; if (!self.shrink and self.colExpanded(col)) resize_expanded += self.col_resize_amount; }
if (resize_expanded != 0) blk: { // need to give resize_expanded space to other expanded cols var col_right = (col + 1) % self.cols; while (col_right != col) : (col_right = (col_right + 1) % self.cols) { if (self.colExpanded(col_right)) { const old = self.col_widths[col_right]; self.col_widths[col_right] = @max(COL_MIN_WIDTH, self.col_widths[col_right] - resize_expanded / factor); resize_expanded -= (old - self.col_widths[col_right]) * factor; if (@abs(resize_expanded) < 0.01) break :blk; } }
// couldn't find enough expanded ones, distribute weighted by column size var total: f32 = 0; for (self.col_widths, 0..) |cw, i| { if (i >= self.col_resizable.len or !self.col_resizable[i]) continue; total += cw; }
col_right = (col + 1) % self.cols; while (col_right != col) : (col_right = (col_right + 1) % self.cols) { if (col_right < self.col_resizable.len and !self.col_resizable[col_right]) continue; const old = self.col_widths[col_right]; const r = resize_expanded * old / total; self.col_widths[col_right] = @max(COL_MIN_WIDTH, self.col_widths[col_right] - r); resize_expanded -= (old - self.col_widths[col_right]); if (@abs(resize_expanded) < 0.01) break :blk; } }
dvui.refresh(null, @src(), self.data().id); } dvui.dataSetSlice(null, self.data().id, "__col_widths", self.col_widths); }
if (self.auto_size == null or self.auto_size.? == .cols) { dvui.dataSetSlice(null, self.data().id, "__row_heights", self.row_heights); }
dvui.dataSetSlice(null, self.data().id, "__col_expands", self.col_expands_new);
dvui.dataSet(null, self.data().id, "__cursor", self.cursor); dvui.dataSet(null, self.data().id, "__scroll_to_cursor", self.scroll_to_cursor);
dvui.dataSet(null, self.data().id, "__sort_dir", self.sort_dir); dvui.dataSet(null, self.data().id, "__sort_col", self.sort_col);
dvui.dataSet(null, self.data().id, "__csi", self.csi);
self.data().minSizeSetAndRefresh(); self.data().minSizeReportToParent(); dvui.parentReset(self.data().id, self.data().parent);}