Skip to content

Instantly share code, notes, and snippets.

@kortschak
Last active January 2, 2016 04:59
Show Gist options
  • Select an option

  • Save kortschak/8254424 to your computer and use it in GitHub Desktop.

Select an option

Save kortschak/8254424 to your computer and use it in GitHub Desktop.
proposal for windows code for ct package
// Copyright ©2014 Dan Kortschak. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !ansi
package ct
import (
"fmt"
"syscall"
"unsafe"
)
const stdoutHandle = -11
func dword(i int) uintptr { return uintptr(uint32(i)) }
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
getStdHandle = kernel32.NewProc("GetStdHandle")
getConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
setConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute")
)
type state struct {
fmt.State
console
attr uint16
}
type (
coord [2]int16
shortRect [4]int16
// CONSOLE_SCREEN_BUFFER_INFO
info struct {
_ coord
_ coord
wAttributes uint16
_ shortRect
_ coord
}
)
type console uintptr
func (c console) getConsoleScreenBufferInfo() *info {
i := &info{}
r, _, _ := getConsoleScreenBufferInfo.Call(uintptr(c), uintptr(unsafe.Pointer(i)))
if r == 0 {
return nil
}
return i
}
func (c console) setConsoleTextAttribute(attr uint16) {
setConsoleTextAttribute.Call(uintptr(c), uintptr(attr))
}
func hook(fs fmt.State) fmt.State {
s := state{State: fs}
con, _, err := getStdHandle.Call(dword(stdoutHandle))
if err != nil {
panic(err)
}
s.console = console(con)
i := s.getConsoleScreenBufferInfo()
if i == nil {
return fs
}
s.attr = i.wAttributes
return s
}
const (
reverse = 0x4000
underscore = 0x8000
)
func (m Mode) set(w io.Writer) {
if m&(colorSet|(colorSet<<colorWidth)|Negative|Underline) == 0 {
return
}
s, ok := w.(state)
if !ok {
return
}
attr := uint16((m & colorMask) | ((m & (colorMask << colorWidth)) >> 1))
if m&Negative != 0 {
attr |= reverse
}
if m&Underline != 0 {
attr |= underscore
}
s.setConsoleTextAttribute(attr)
}
func (m Mode) reset(w io.Writer) {
if m&(colorSet|(colorSet<<colorWidth)|Negative|Underline) == 0 {
return
}
if s, ok := w.(state); ok {
s.setConsoleTextAttribute(s.attr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment