~dricottone/image2ascii

ref: 4ad980ef244f080f793177b991b50fa6460c1eb8 image2ascii/terminal/terminal.go -rw-r--r-- 974 bytes
4ad980ef — qeesung Refactor the code to match the oop mode for easy mock and test 6 years ago
                                                                                
4ad980ef qeesung
1
2
3
4
5
6
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package terminal

import (
	"errors"
	"github.com/mattn/go-isatty"
	terminal "github.com/wayneashleyberry/terminal-dimensions"
	"os"
	"runtime"
)

const (
	charWidthWindows = 0.714
	charWidthOther   = 0.5
)

func NewTerminalAccessor() Terminal {
	return Accessor{}
}

// Terminal get the terminal basic information
type Terminal interface {
	CharWidth() float64
	ScreenSize() (width, height int, err error)
	IsWindows() bool
}

type Accessor struct {
}

func (accessor Accessor) CharWidth() float64 {
	if accessor.IsWindows() {
		return charWidthWindows
	}
	return charWidthOther
}

func (accessor Accessor) IsWindows() bool {
	return runtime.GOOS == "windows"
}

func (accessor Accessor) ScreenSize() (newWidth, newHeight int, err error) {
	if !isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()) {
		return 0, 0,
			errors.New("can not detect the terminal")
	}

	x, _ := terminal.Width()
	y, _ := terminal.Height()

	return int(x), int(y), nil
}