7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
# File 'lib/inlay/sizer.rb', line 7
def fit(image, width: nil, height: nil, scale: :auto, columns: nil, rows: nil, protocol: :blocks, env: ENV)
raise TypeError, "expected a Tessel::Image" unless image.is_a?(Tessel::Image)
raise ArgumentError, "unknown scale mode: #{scale}" unless i[auto fit pixel none].include?(scale)
return image if image.width.zero? || image.height.zero?
terminal = Termvas::Terminal.new(alt_screen: false, env: env)
terminal_columns, terminal_rows = terminal.size
columns ||= terminal_columns
rows ||= terminal_rows
block_pixels = protocol.to_sym == :blocks
cell_width, cell_height = terminal.cell_size
available_width = columns * (block_pixels ? 1 : cell_width)
available_height = [rows, Inlay.config.max_rows].min * (block_pixels ? 2 : cell_height)
if available_width * available_height > Inlay.config.max_pixels
factor = Math.sqrt(Inlay.config.max_pixels.to_f / (available_width * available_height))
available_width = [(available_width * factor).floor, 1].max
available_height = [(available_height * factor).floor, 1].max
end
width = [Integer(width || available_width), available_width].min
height = [Integer(height || available_height), available_height].min
raise ArgumentError, "display dimensions must be positive" unless width.positive? && height.positive?
pixel_scale = scale == :pixel || (scale == :auto && image.width <= 32 && image.height <= 32)
max_factor = [width / [image.width, 1].max, height / [image.height, 1].max].min
if pixel_scale && max_factor > 1
return image.scale_nearest(image.width * max_factor, image.height * max_factor)
end
return image if image.width <= width && image.height <= height
factor = [width.to_f / image.width, height.to_f / image.height, 1.0].min
resize_area(image, [(image.width * factor).floor, 1].max, [(image.height * factor).floor, 1].max)
end
|