Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazily detect background color setting #61

Merged
merged 1 commit into from Feb 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 29 additions & 6 deletions color.go
Expand Up @@ -11,12 +11,12 @@ var (
colorProfile termenv.Profile
getColorProfile sync.Once
explicitColorProfile bool
colorProfileMtx sync.Mutex

// Because it's a potentially long operation (relatively speaking), we
// check the background color on initialization rather than at the last
// possible second.
hasDarkBackground = termenv.HasDarkBackground()
hasDarkBackground bool
getBackgroundColor sync.Once
explicitBackgroundColor bool

colorProfileMtx sync.Mutex
)

// ColorProfile returns the detected termenv color profile. It will perform the
Expand Down Expand Up @@ -53,11 +53,34 @@ func SetColorProfile(p termenv.Profile) {
explicitColorProfile = true
}

// HadDarkBackground returns whether or not the terminal has a dark background.
// HasDarkBackground returns whether or not the terminal has a dark background.
func HasDarkBackground() bool {
if !explicitBackgroundColor {
getBackgroundColor.Do(func() {
hasDarkBackground = termenv.HasDarkBackground()
})
}

return hasDarkBackground
}

// SetHasDarkBackground sets the value of the background color detection on a
// package-wide context. This function exists mostly for testing purposes so
// that you can assure you're testing against a specific background color
// setting.
//
// Outside of testing you likely won't want to use this function as
// HasDarkBackground() will detect and cache the terminal's current background
// color setting.
//
// This function is thread-safe.
func SetHasDarkBackground(b bool) {
colorProfileMtx.Lock()
defer colorProfileMtx.Unlock()
hasDarkBackground = b
explicitBackgroundColor = true
}

// TerminalColor is a color intended to be rendered in the terminal. It
// satisfies the Go color.Color interface.
type TerminalColor interface {
Expand Down