pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/terminal/window/size_posix.go (about)

     1  //go:build !windows
     2  // +build !windows
     3  
     4  // Package window provides methods for working terminal window
     5  package window
     6  
     7  // ////////////////////////////////////////////////////////////////////////////////// //
     8  //                                                                                    //
     9  //                         Copyright (c) 2022 ESSENTIAL KAOS                          //
    10  //      Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>     //
    11  //                                                                                    //
    12  // ////////////////////////////////////////////////////////////////////////////////// //
    13  
    14  import (
    15  	"os"
    16  	"syscall"
    17  	"unsafe"
    18  )
    19  
    20  // ////////////////////////////////////////////////////////////////////////////////// //
    21  
    22  type winsize struct {
    23  	rows    uint16
    24  	cols    uint16
    25  	xpixels uint16
    26  	ypixels uint16
    27  }
    28  
    29  // ////////////////////////////////////////////////////////////////////////////////// //
    30  
    31  // tty is a path to TTY device file
    32  var tty = "/dev/tty"
    33  
    34  // ////////////////////////////////////////////////////////////////////////////////// //
    35  
    36  // GetSize returns window width and height
    37  func GetSize() (int, int) {
    38  	t, err := os.OpenFile(tty, syscall.O_RDONLY, 0)
    39  
    40  	if err != nil {
    41  		return -1, -1
    42  	}
    43  
    44  	var sz winsize
    45  
    46  	_, _, _ = syscall.Syscall(
    47  		syscall.SYS_IOCTL, t.Fd(),
    48  		uintptr(syscall.TIOCGWINSZ),
    49  		uintptr(unsafe.Pointer(&sz)),
    50  	)
    51  
    52  	return int(sz.cols), int(sz.rows)
    53  }
    54  
    55  // GetWidth returns window width
    56  func GetWidth() int {
    57  	w, _ := GetSize()
    58  	return w
    59  }
    60  
    61  // GetHeight returns window height
    62  func GetHeight() int {
    63  	_, h := GetSize()
    64  	return h
    65  }