add a getter for a given views size and add some safety when setting the size

This commit is contained in:
Squibid 2025-12-13 07:58:58 -05:00
parent 12aa7b6448
commit 54c1a976c8
Signed by: squibid
GPG key ID: BECE5684D3C4005D
2 changed files with 50 additions and 2 deletions

26
src/lua/LuaUtils.zig Normal file
View file

@ -0,0 +1,26 @@
const LuaUtils = @This();
const std = @import("std");
const zlua = @import("zlua");
pub fn coerceNumber(comptime x: type, number: zlua.Number) error{InvalidNumber}!x {
if (number < std.math.minInt(x) or number > std.math.maxInt(x) or std.math.isNan(number)) {
return error.InvalidNumber;
}
switch (@typeInfo(x)) {
.int => return @as(x, @intFromFloat(number)),
.float => return @floatCast(number),
else => @compileError("unsupported type"),
}
}
pub fn coerceInteger(comptime x: type, number: zlua.Integer) error{InvalidInteger}!x {
if (number < std.math.minInt(x) or number > std.math.maxInt(x) or std.math.isNan(number)) {
return error.InvalidInteger;
}
switch (@typeInfo(x)) {
.int => return @intCast(number),
.float => return @as(x, @floatFromInt(number)),
else => @compileError("unsupported type"),
}
}

View file

@ -2,6 +2,7 @@ const std = @import("std");
const zlua = @import("zlua");
const View = @import("../View.zig");
const LuaUtils = @import("LuaUtils.zig");
const server = &@import("../main.zig").server;
@ -87,8 +88,8 @@ pub fn set_position(L: *zlua.Lua) i32 {
// ---@param height number height for view
pub fn set_size(L: *zlua.Lua) i32 {
const view_id: u64 = @intCast(L.checkInteger(1));
const width: i32 = @intFromFloat(@round(L.checkNumber(2)));
const height: i32 = @intFromFloat(@round(L.checkNumber(3)));
const width = LuaUtils.coerceNumber(i32, L.checkNumber(2)) catch L.raiseErrorStr("The width must be >= 0 and < inf", .{});
const height = LuaUtils.coerceNumber(i32, L.checkNumber(3)) catch L.raiseErrorStr("The height must be >= 0 and < inf", .{});
const view: ?*View = if (view_id == 0) server.seat.focused_view else server.root.viewById(view_id);
if(view) |v| {
@ -99,6 +100,27 @@ pub fn set_size(L: *zlua.Lua) i32 {
return 1;
}
pub fn get_size(L: *zlua.Lua) i32 {
const view_id: u64 = @intCast(L.checkInteger(1));
const view: ?*View = if (view_id == 0) server.seat.focused_view else server.root.viewById(view_id);
if (view) |v| {
L.newTable();
_ = L.pushString("width");
L.pushInteger(@intCast(v.xdg_toplevel.current.width));
L.setTable(-3);
_ = L.pushString("height");
L.pushInteger(@intCast(v.xdg_toplevel.current.height));
L.setTable(-3);
return 1;
}
L.pushNil();
return 1;
}
// ---Remove focus from current view, and set to given id
// ---@param view_id view_id Id of the view to be focused, or nil to remove focus
pub fn set_focused(L: *zlua.Lua) i32 {