summaryrefslogtreecommitdiff
path: root/termSize_linux.go
blob: 392efa3349174dc305f5e6eefdefe75986a360b0 (plain)
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
package cobol

import (
	"fmt"
	"os"

	"golang.org/x/term"
)

func osTerminalWidth() (int, bool) {
	w, _, err := ttyGetSize()
	if err == nil {
		return w, true
	}

	// term.IsTerminal checks if the given file descriptor is connected to a terminal.
	// We use os.Stdout.Fd() to check the standard output.
	if term.IsTerminal(int(os.Stdout.Fd())) {
		var err error
		// term.GetSize returns the dimensions of the given terminal.
		WIDTH, _, err = term.GetSize(int(os.Stdout.Fd()))
		if err != nil {
			// If we can't get the size for some reason, fall back to the default.
			fmt.Printf("could not get terminal size: %v", err)
			return WIDTH, false
		}
		return WIDTH, true
	}

	// If it's not a terminal, return the default width.
	return WIDTH, false
}

func ttyGetSize() (int, int, error) {
	tty, err := os.Open("/dev/tty")
	if err != nil {
		return 0, 0, err
	}
	w, h, err := term.GetSize(int(tty.Fd()))
	if err != nil {
		fmt.Println("linux.osTerminalWidth tty.Fd() err", w, h, err)
	}
	return w, h, err
}