From 68e95eba382c972aafde02ead2cd2426a8a92480 Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Fri, 28 Feb 2020 12:24:31 +0900 Subject: [PATCH] Add EnableColorsStdout --- colorable_appengine.go | 8 ++++++++ colorable_others.go | 8 ++++++++ colorable_windows.go | 21 +++++++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/colorable_appengine.go b/colorable_appengine.go index 0b0aef8..1f7806f 100644 --- a/colorable_appengine.go +++ b/colorable_appengine.go @@ -27,3 +27,11 @@ func NewColorableStdout() io.Writer { func NewColorableStderr() io.Writer { return os.Stderr } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/colorable_others.go b/colorable_others.go index 3fb771d..08cbd1e 100644 --- a/colorable_others.go +++ b/colorable_others.go @@ -28,3 +28,11 @@ func NewColorableStdout() io.Writer { func NewColorableStderr() io.Writer { return os.Stderr } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/colorable_windows.go b/colorable_windows.go index d172cc3..b9e9363 100644 --- a/colorable_windows.go +++ b/colorable_windows.go @@ -81,6 +81,7 @@ var ( procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) @@ -1010,3 +1011,23 @@ func n256setup() { n256backAttr[i] = c.backgroundAttr() } } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + var mode uint32 + h := os.Stdout.Fd() + if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 { + if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 { + if enabled != nil { + *enabled = true + } + return func() { + procSetConsoleMode.Call(h, uintptr(mode)) + } + } + } + if enabled != nil { + *enabled = true + } + return func() {} +}