From a3fade1cc513dde2821409aff0dea275d754d396 Mon Sep 17 00:00:00 2001 From: Christian Muehlhaeuser Date: Fri, 4 Feb 2022 04:48:20 +0100 Subject: [PATCH] Lazily detect background color setting This change prevents Lipgloss from querying the terminal's background color setting on init. Instead, the background color will get queried the first time the setting gets accessed by HasDarkBackground, and the result will be cached. Furthermore SetHasDarkBackground(bool) has been added, which explicitly sets a value and avoids the automatic detection from ever being run. --- color.go | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/color.go b/color.go index 28baafc3..1a880f0f 100644 --- a/color.go +++ b/color.go @@ -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 @@ -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 {