Debian Codegraph @

debian/vendor/github.com/nathan-fiscaletti/consolesize-go/consolesize_windows.go

raw
1 // +build windows, !unix
2
3 package consolesize
4
5 import (
6 "fmt"
7 "syscall"
8 "unsafe"
9 )
10
11 type (
12 short int16
13 word uint16
14 smallRect struct {
15 Left short
16 Top short
17 Right short
18 Bottom short
19 }
20 coord struct {
21 X short
22 Y short
23 }
24 consoleScreenBufferInfo struct {
25 Size coord
26 CursorPosition coord
27 Attributes word
28 Window smallRect
29 MaximumWindowSize coord
30 }
31 )
32
33 var kernel32DLL = syscall.NewLazyDLL("kernel32.dll")
34 var getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo")
35
36 // GetConsoleSize returns the current number of columns and rows in the active console window.
37 // The return value of this function is in the order of cols, rows.
38 func GetConsoleSize() (int, int) {
39 stdoutHandle := getStdHandle(syscall.STD_OUTPUT_HANDLE)
40 var info, err = getConsoleScreenBufferInfo(stdoutHandle)
41
42 if err != nil {
43 return 0, 0
44 }
45
46 return int(info.Window.Right - info.Window.Left + 1), int(info.Window.Bottom - info.Window.Top + 1)
47 }
48
49 func getError(r1, r2 uintptr, lastErr error) error {
50 // If the function fails, the return value is zero.
51 if r1 == 0 {
52 if lastErr != nil {
53 return lastErr
54 }
55 return syscall.EINVAL
56 }
57 return nil
58 }
59
60 func getStdHandle(stdhandle int) uintptr {
61 handle, err := syscall.GetStdHandle(stdhandle)
62 if err != nil {
63 panic(fmt.Errorf("could not get standard io handle %d", stdhandle))
64 }
65 return uintptr(handle)
66 }
67
68 func getConsoleScreenBufferInfo(handle uintptr) (*consoleScreenBufferInfo, error) {
69 var info consoleScreenBufferInfo
70 if err := getError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)); err != nil {
71 return nil, err
72 }
73 return &info, nil
74 }