-- Modified from folke/snacks.nvim (Apache-2.0); see lua/bugabinga/image/NOTICE. local function rectangle(info, image, cells) vim.validate('info', info, 'table') vim.validate('image', image, 'table') vim.validate('cells', cells, 'table') local cols = info.width - info.textoff local rows = info.height if cols < 1 or rows < 1 then return end local width_scale = math.min(1, cols * cells.cell_width / image.width) local height_scale = math.min(1, rows * cells.cell_height / image.height) local axis if cells.explicit_size then local scale = math.min(width_scale, height_scale) local max_cols = math.min(cols, math.max(1, math.floor(image.width / cells.cell_width))) local max_rows = math.min(rows, math.max(1, math.floor(image.height / cells.cell_height))) local width = math.max(1, math.min(max_cols, math.floor(image.width * scale / cells.cell_width + 0.5))) local height = math.max(1, math.min(max_rows, math.floor(image.height * scale / cells.cell_height + 0.5))) local a = { cols = width, rows = math.min(max_rows, math.max(1, math.floor(width * cells.cell_width * image.height / image.width / cells.cell_height + 0.5))) } local b = { rows = height, cols = math.min(max_cols, math.max(1, math.floor(height * cells.cell_height * image.width / image.height / cells.cell_width + 0.5))) } local function aspect_error(candidate) return math.abs(candidate.cols * cells.cell_width * image.height / (candidate.rows * cells.cell_height * image.width) - 1) end local best = aspect_error(a) <= aspect_error(b) and a or b cols, rows, axis = best.cols, best.rows, 'both' elseif height_scale < width_scale then axis = 'rows' rows = math.max(1, math.floor(image.height * height_scale / cells.cell_height)) cols = math.min(cols, math.ceil(rows * cells.cell_height * image.width / image.height / cells.cell_width)) else axis = 'cols' cols = math.max(1, math.floor(image.width * width_scale / cells.cell_width)) rows = math.min(rows, math.ceil(cols * cells.cell_width * image.height / image.width / cells.cell_height)) end return { row = info.winrow + (info.winbar or 0), col = info.wincol + info.textoff, cols = cols, rows = rows, axis = axis } end local function overlaps(a, b) vim.validate('a', a, 'table') vim.validate('b', b, 'table') return a.row < b.row + b.rows and b.row < a.row + a.rows and a.col < b.col + b.cols and b.col < a.col + a.cols end return { rectangle = rectangle, overlaps = overlaps }