github.com/julianthome/gore@v0.0.0-20231109011145-b3a6bbe6fe55/terminal_windows.go (about)

     1  package gore
     2  
     3  import (
     4  	"syscall"
     5  	"unsafe"
     6  )
     7  
     8  type (
     9  	short int16
    10  	word  uint16
    11  )
    12  
    13  type coord struct {
    14  	x short
    15  	y short
    16  }
    17  
    18  type smallRect struct {
    19  	left   short
    20  	top    short
    21  	right  short
    22  	bottom short
    23  }
    24  
    25  type consoleScreenBufferInfo struct {
    26  	size              coord
    27  	cursorPosition    coord
    28  	attributes        word
    29  	window            smallRect
    30  	maximumWindowSize coord
    31  }
    32  
    33  var (
    34  	kernel32                       = syscall.NewLazyDLL("kernel32.dll")
    35  	procGetStdHandle               = kernel32.NewProc("GetStdHandle")
    36  	procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
    37  	procSetConsoleCursorPosition   = kernel32.NewProc("SetConsoleCursorPosition")
    38  	procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
    39  
    40  	stdoutHandle uintptr
    41  )
    42  
    43  func init() {
    44  	stdoutHandle = getStdHandle(syscall.STD_OUTPUT_HANDLE)
    45  }
    46  
    47  func getStdHandle(stdhandle int32) uintptr {
    48  	handle, _, _ := procGetStdHandle.Call(uintptr(stdhandle))
    49  	return handle
    50  }
    51  
    52  func cursorUp() {
    53  	var csbi consoleScreenBufferInfo
    54  	procGetConsoleScreenBufferInfo.Call(stdoutHandle, uintptr(unsafe.Pointer(&csbi)))
    55  
    56  	var cursor coord
    57  	cursor.x = csbi.cursorPosition.x
    58  	cursor.y = csbi.cursorPosition.y - 1
    59  
    60  	procSetConsoleCursorPosition.Call(stdoutHandle, uintptr(*(*int32)(unsafe.Pointer(&cursor))))
    61  }
    62  
    63  func eraseInLine() {
    64  	var csbi consoleScreenBufferInfo
    65  	procGetConsoleScreenBufferInfo.Call(stdoutHandle, uintptr(unsafe.Pointer(&csbi)))
    66  
    67  	var w uint32
    68  	procFillConsoleOutputCharacter.Call(stdoutHandle, uintptr(' '), uintptr(csbi.size.x), uintptr(*(*int32)(unsafe.Pointer(&csbi.cursorPosition))), uintptr(unsafe.Pointer(&w)))
    69  }