Skip to content

Commit

Permalink
A function to construct a color by looking it up in the config file
Browse files Browse the repository at this point in the history
MakeColorSafe() is a gowid function to construct a color based on a
string. Gowid walks through various interpretations of the string to try
to construct the most likely color. This function adds an interpretation
at the beginning, which is as a key in the termshark toml file. This
lets you add something like

[theme]
  flashy = "theme.red"
  red = "#ff0000"

Now you can programmatically use "theme.flashy" as an argument and
construct a color from it.

This function takes an an extra argument, meaning foreground or
background. This allows for pairs of colors to be used:

[theme]
  ocean = ["#ffffff", "#0000ff"]    // white on blue

If you call MakeColorSafe() with "theme.ocean" and theme.Background,
you'll get the blue color.

Values can refer to other keys in the toml file; this can be done up to
10 times before the function gives up (in case there's a loop).
  • Loading branch information
gcla committed Sep 7, 2020
1 parent 00d0658 commit 962362d
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions theme/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2019-2020 Graham Clark. All rights reserved. Use of this source
// code is governed by the MIT license that can be found in the LICENSE
// file.

// package theme provides utilities for customizing the styling of termshark.
package theme

import (
"github.com/gcla/gowid"
"github.com/gcla/termshark/v2"
log "github.com/sirupsen/logrus"
)

//======================================================================

type Layer int

const (
Foreground Layer = 0
Background Layer = iota
)

// MakeColorSafe extends gowid's MakeColorSafe function, prefering to interpret
// its string argument as a toml file config key lookup first; if this fails, then
// fall back to gowid.MakeColorSafe, which will then read colors as urwid color names,
// #-prefixed hex digits, grayscales, etc.
func MakeColorSafe(s string, l Layer) (gowid.Color, error) {
loops := 10
cur := s
for {
next := termshark.ConfString(cur, "")
if next != "" {
cur = next
} else {
next := termshark.ConfStringSlice(cur, []string{})
if len(next) != 2 {
break
} else {
cur = next[l]
}
}
loops -= 1
if loops == 0 {
break
}
}
col, err := gowid.MakeColorSafe(cur)
if err == nil {
return gowid.Color{IColor: col, Id: s}, nil
}
col, err = gowid.MakeColorSafe(s)
if err != nil {
log.Infof("Could not understand configured theme color '%s'", s)
}
return col, err
}

//======================================================================
// Local Variables:
// mode: Go
// fill-column: 110
// End:

0 comments on commit 962362d

Please sign in to comment.