~dricottone/image2ascii

ref: 80cd2b553b0a44ef00114d715cec803559bf936a image2ascii/terminal/terminal.go -rw-r--r-- 1.2 KiB
80cd2b55Dominic Ricottone Merging branch 'log-more-helpfully' from mjip/PR #22 2 years ago
                                                                                
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
52
53
54
55
56
57
package terminal

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

const (
	charWidthWindows = 0.714
	charWidthOther   = 0.5
)

// NewTerminalAccessor create a new terminal accessor
func NewTerminalAccessor() Terminal {
	return Accessor{}
}

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

// Accessor implement the Terminal interface and
// fetch the terminal basic information
type Accessor struct {
}

// CharWidth get the terminal char width
func (accessor Accessor) CharWidth() float64 {
	if accessor.IsWindows() {
		return charWidthWindows
	}
	return charWidthOther
}

// IsWindows check if current system is windows
func (accessor Accessor) IsWindows() bool {
	return runtime.GOOS == "windows"
}

// ScreenSize get the terminal screen size
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
}