summaryrefslogtreecommitdiff
path: root/internal/tui/common/viewport.go
blob: e1729dba6fed1d85e409398d5f30050c08a4a7f2 (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
package common

import (
	"os"

	xterm "github.com/charmbracelet/x/term"
)

const (
	defaultViewportWidth  = 80
	defaultViewportHeight = 24
)

// EffectiveViewport returns a usable terminal viewport size. Missing or invalid
// dimensions are resolved from the active terminal when possible.
func EffectiveViewport(width, height int) (int, int) {
	if width > 0 && height > 0 {
		return width, height
	}

	termWidth, termHeight, err := xterm.GetSize(os.Stdout.Fd())
	if err == nil {
		if width <= 0 && termWidth > 0 {
			width = termWidth
		}
		if height <= 0 && termHeight > 0 {
			height = termHeight
		}
	}

	if width <= 0 {
		width = defaultViewportWidth
	}
	if height <= 0 {
		height = defaultViewportHeight
	}
	return width, height
}