Skip to content

Commit

Permalink
Automatically fetch cursor width/height ratio
Browse files Browse the repository at this point in the history
  • Loading branch information
ichinaski committed May 31, 2016
1 parent 3e7193d commit f1a45c6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
12 changes: 12 additions & 0 deletions image.go
Expand Up @@ -3,6 +3,8 @@ package main
import (
"image"
"os"
"syscall"
"unsafe"
)

// load an image stored in the given path
Expand All @@ -16,6 +18,16 @@ func load(filename string) (image.Image, error) {
return img, err
}

// canvasSize returns the terminal columns, rows, and cursor aspect ratio
func canvasSize() (int, int, float64) {
var size [4]uint16
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(os.Stdout.Fd()), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&size)), 0, 0, 0); err != 0 {
panic(err)
}
rows, cols, width, height := size[0], size[1], size[2], size[3]
return int(cols), int(rows), float64(height/rows) / float64(width/cols)
}

// scales calculates the image scale to fit within the terminal width/height
func scale(imgW, imgH, termW, termH int, whratio float64) float64 {
hr := float64(imgH) / (float64(termH) * whratio)
Expand Down
17 changes: 6 additions & 11 deletions main.go
Expand Up @@ -12,26 +12,21 @@ import (
"github.com/nsf/termbox-go"
)

var whratio float64 // The terminal's cursor width/height ratio

func init() {
flag.Float64Var(&whratio, "r", 2.35, "Cursor width/height ratio in your terminal")
}

func draw(img image.Image) {
w, h := termbox.Size()
// Get terminal size and cursor width/height ratio
width, height, whratio := canvasSize()

bounds := img.Bounds()
imgW, imgH := bounds.Dx(), bounds.Dy()

imgScale := scale(imgW, imgH, w, h, whratio)
imgScale := scale(imgW, imgH, width, height, whratio)

// Resize canvas to fit scaled image
w, h = int(float64(imgW)/imgScale), int(float64(imgH)/(imgScale*whratio))
width, height = int(float64(imgW)/imgScale), int(float64(imgH)/(imgScale*whratio))

termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
// Calculate average color for the corresponding image rectangle
// fitting in this cell. We use a half-block trick, wherein the
// lower half of the cell displays the character ▄, effectively
Expand Down

0 comments on commit f1a45c6

Please sign in to comment.