Skip to content

Commit

Permalink
Lazily detect background color setting
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
muesli committed Feb 4, 2022
1 parent 024177a commit b3934f5
Showing 1 changed file with 29 additions and 6 deletions.
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

0 comments on commit b3934f5

Please sign in to comment.